`Agent`

Agent (interface)

Agent 인터페이스는 프롬프트에 대한 응답으로 AI 생성 응답을 생성하거나 스트리밍할 수 있는 에이전트의 계약(contract)을 정의해요. 도구 사용, 멀티스텝 워크플로, 프롬프트 처리 같은 고급 로직을 캡슐화해, 간단한 에이전트부터 자율적인 AI 에이전트까지 모두 만들 수 있게 해줍니다.

출처: 문서

본문

Agent 인터페이스는 프롬프트에 대한 응답으로 AI 생성 응답을 생성하거나 스트리밍할 수 있는 에이전트의 계약을 정의합니다. 에이전트는 도구 사용, 멀티스텝 워크플로, 프롬프트 처리 같은 고급 로직을 캡슐화하여, 간단한 AI 에이전트와 자율적인 AI 에이전트를 모두 가능하게 합니다.

ToolLoopAgent 같은 Agent 인터페이스의 구현체들은 동일한 계약을 충족하며, 에이전트를 기대하는 모든 SDK API와 유틸리티와 원활하게 통합됩니다. 이 설계는 사용자가 커스텀 에이전트 클래스나 서드파티 체인용 래퍼를 제공할 수 있게 하면서, AI SDK 기능과의 호환성을 최대화합니다.

인터페이스 정의 (Interface Definition)

import {
  ModelMessage,
  Experimental_SandboxSession,
} from '@ai-sdk/provider-utils';
import { ToolSet } from '../generate-text/tool-set';
import { Output } from '../generate-text/output';
import { GenerateTextResult } from '../generate-text/generate-text-result';
import { StreamTextResult } from '../generate-text/stream-text-result';

export type AgentCallParameters<CALL_OPTIONS, TOOLS extends ToolSet = {}> = ([
  CALL_OPTIONS,
] extends [never]
  ? { options?: never }
  : { options: CALL_OPTIONS }) &
  (
    | {
        /**
         * A prompt. It can be either a text prompt or a list of messages.
         *
         * You can either use `prompt` or `messages` but not both.
         */
        prompt: string | Array<ModelMessage>;

        /**
         * A list of messages.
         *
         * You can either use `prompt` or `messages` but not both.
         */
        messages?: never;
      }
    | {
        /**
         * A list of messages.
         *
         * You can either use `prompt` or `messages` but not both.
         */
        messages: Array<ModelMessage>;

        /**
         * A prompt. It can be either a text prompt or a list of messages.
         *
         * You can either use `prompt` or `messages` but not both.
         */
        prompt?: never;
      }
  ) & {
    /**
     * Abort signal.
     */
    abortSignal?: AbortSignal;
    /**
     * Timeout in milliseconds. Can be specified as a number or as an object with a totalMs property.
     * The call will be aborted if it takes longer than the specified timeout.
     * Can be used alongside abortSignal.
     */
    timeout?: number | { totalMs?: number };
    /**
     * Experimental sandbox environment that is passed through to tool execution.
     */
    experimental_sandbox?: Experimental_SandboxSession;
    /**
     * Callback that is called when the agent operation begins, before any LLM calls.
     */
    onStart?: GenerateTextOnStartCallback<TOOLS>;
    /**
     * Callback that is called when a step (LLM call) begins, before the provider is called.
     */
    onStepStart?: GenerateTextOnStepStartCallback<TOOLS>;
    /**
     * Callback that is called before each tool execution begins.
     */
    onToolExecutionStart?: OnToolExecutionStartCallback<TOOLS>;
    /**
     * Callback that is called after each tool execution completes.
     */
    onToolExecutionEnd?: OnToolExecutionEndCallback<TOOLS>;
    /**
     * Callback that is called when each step (LLM call) ends, including intermediate steps.
     */
    onStepEnd?: GenerateTextOnStepEndCallback<TOOLS>;
    /**
     * Callback that is called when each step (LLM call) ends, including intermediate steps.
     *
     * @deprecated Use `onStepEnd` instead.
     */
    onStepFinish?: GenerateTextOnStepFinishCallback<TOOLS>;
    /**
     * Callback that is called when all steps are finished and the response is complete.
     */
    onEnd?: GenerateTextOnEndCallback<TOOLS>;
    /**
     * Callback that is called when all steps are finished and the response is complete.
     *
     * @deprecated Use `onEnd` instead.
     */
    onFinish?: GenerateTextOnEndCallback<TOOLS>;
  };

/**
 * An Agent receives a prompt (text or messages) and generates or streams an output
 * that consists of steps, tool calls, data parts, etc.
 *
 * You can implement your own Agent by implementing the `Agent` interface,
 * or use the `ToolLoopAgent` class.
 */
export interface Agent<
  CALL_OPTIONS = never,
  TOOLS extends ToolSet = {},
  OUTPUT extends Output = never,
> {
  /**
   * The specification version of the agent interface. This will enable
   * us to evolve the agent interface and retain backwards compatibility.
   */
  readonly version: 'agent-v1';

  /**
   * The id of the agent.
   */
  readonly id: string | undefined;

  /**
   * The tools that the agent can use.
   */
  readonly tools: TOOLS;

  /**
   * Generates an output from the agent (non-streaming).
   */
  generate(
    options: AgentCallParameters<CALL_OPTIONS, TOOLS>,
  ): PromiseLike<GenerateTextResult<TOOLS, OUTPUT>>;

  /**
   * Streams an output from the agent (streaming).
   */
  stream(
    options: AgentStreamParameters<CALL_OPTIONS, TOOLS>,
  ): PromiseLike<StreamTextResult<TOOLS, OUTPUT>>;
}

핵심 속성 & 메서드 (Core Properties & Methods)

이름 타입 설명
version 'agent-v1' 호환성을 위한 인터페이스 버전.
id string | undefined 선택적 에이전트 식별자.
tools ToolSet 이 에이전트가 사용할 수 있는 도구 집합.
generate() PromiseLike<GenerateTextResult<TOOLS, OUTPUT>> 텍스트 프롬프트 또는 메시지에 대한 완전한 비스트리밍 출력을 생성.
stream() PromiseLike<StreamTextResult<TOOLS, OUTPUT>> 텍스트 프롬프트 또는 메시지에 대한 출력(청크 또는 스텝)을 스트리밍.

제네릭 매개변수 (Generic Parameters)

매개변수 기본값 설명
CALL_OPTIONS never 에이전트에 전달할 수 있는 추가 호출 옵션의 선택적 타입.
TOOLS {} 이 에이전트가 사용할 수 있는 도구 집합의 타입.
OUTPUT never 에이전트가 생성할 수 있는 추가 출력 데이터의 타입.

메서드 매개변수 (Method Parameters)

generate()와 stream() 모두 AgentCallParameters<CALL_OPTIONS, TOOLS> 객체를 받습니다:

  • prompt (선택): 문자열 프롬프트 또는 ModelMessage 객체 배열
  • messages (선택): ModelMessage 객체 배열 (prompt와 상호 배타적)
  • options (선택): CALL_OPTIONS가 never가 아닐 때 추가 호출 옵션
  • abortSignal (선택): 작업을 취소할 AbortSignal
  • timeout (선택): 밀리초 단위 타임아웃. 숫자 또는 totalMs 속성을 가진 객체로 지정할 수 있습니다. 지정된 타임아웃보다 길어지면 호출이 중단됩니다. abortSignal과 함께 사용할 수 있습니다.
  • experimental_sandbox (선택): 도구 실행에 전달되는 실험적 샌드박스 환경
  • onStart (선택): LLM 호출 전, 에이전트 작업이 시작될 때 호출되는 콜백
  • onStepStart (선택): 프로바이더가 호출되기 전, 스텝(LLM 호출)이 시작될 때 호출되는 콜백
  • onToolExecutionStart (선택): 도구의 execute 함수가 실행되기 직전에 호출되는 콜백
  • onToolExecutionEnd (선택): 도구의 execute 함수가 완료되거나 오류가 난 직후에 호출되는 콜백
  • onStepEnd (선택): 각 에이전트 스텝(LLM/도구 호출)이 완료된 후 호출되는 콜백. 토큰 사용량, 스텝별 성능 추적 또는 로깅에 유용합니다.
  • onStepFinish (선택): onStepEnd의 지원 중단된 별칭
  • onEnd (선택): 모든 스텝이 끝나고 응답이 완료될 때 호출되는 콜백
  • onFinish (선택): onEnd의 지원 중단된 별칭

예제: 커스텀 에이전트 구현 (Example: Custom Agent Implementation)

자신만의 에이전트를 구현하는 방법은 다음과 같습니다:

import { Agent, GenerateTextResult, StreamTextResult } from 'ai';
import type { ModelMessage } from '@ai-sdk/provider-utils';

class MyEchoAgent implements Agent {
  version = 'agent-v1' as const;
  id = 'echo';
  tools = {};

  async generate({ prompt, messages, abortSignal }) {
    const text = prompt ?? JSON.stringify(messages);
    return { text, steps: [] };
  }

  async stream({ prompt, messages, abortSignal }) {
    const text = prompt ?? JSON.stringify(messages);
    return {
      textStream: (async function* () {
        yield text;
      })(),
    };
  }
}

사용법: 에이전트와 상호작용하기 (Usage: Interacting with Agents)

createAgentUIStream, createAgentUIStreamResponse, pipeAgentUIStreamToResponse를 포함해 에이전트를 받는 모든 SDK 유틸리티는 Agent 인터페이스를 따르는 객체를 기대합니다.

공식 ToolLoopAgent(도구 사용이 있는 멀티스텝 AI 워크플로에 권장)를 사용하거나, 자신만의 구현체를 제공할 수 있습니다:

import { ToolLoopAgent, createAgentUIStream } from "ai";

const agent = new ToolLoopAgent({ ... });

const stream = await createAgentUIStream({
  agent,
  messages: [{ role: "user", content: "What is the weather in NYC?" }]
});

for await (const chunk of stream) {
  console.log(chunk);
}

함께 보기 (See Also)

참고 사항 (Notes)

  • 에이전트는 SDK 유틸리티와의 호환성을 위해, 비어 있더라도({}) tools 속성을 정의해야 합니다.
  • 인터페이스는 일반 프롬프트와 메시지 배열을 모두 입력으로 받지만, 한 번에 하나만 받습니다.
  • CALL_OPTIONS 제네릭 매개변수는 에이전트가 필요할 때 추가 호출별 옵션을 받을 수 있게 합니다.
  • abortSignal 매개변수는 에이전트 작업의 취소를 가능하게 합니다.
  • 이 설계는 복잡한 자율 에이전트와 간단한 LLM 래퍼 모두에 확장 가능합니다.

더 알아보기 (Learn more)

전체 사이트맵