에이전트 스트리밍(Agent Streaming)

Mastra의 에이전트는 강력한 스트리밍 프로토콜을 사용할 수 있습니다! 도구나 에이전트를 도구로서 원활하게 통합하여 응답을 클라이언트로 직접 스트리밍할 수 있어 보다 인터랙티브하고 몰입감 있는 경험을 제공합니다.

사용법

새로운 프로토콜을 사용하려면 에이전트에서 streamVNext 메서드를 사용할 수 있습니다. 이 메서드는 사용자 정의 MastraAgentStream을 반환합니다. 이 스트림은 ReadableStream을 확장하므로 모든 기본 스트림 메서드를 사용할 수 있습니다.

const stream = await agent.streamVNext({ role: "user", content: "이야기를 들려줘." });

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

각 청크(chunk)는 다음 속성을 가진 JSON 객체입니다:

{
  type: string;
  runId: string;
  from: string;
  payload: Record<string, any>;
}

스트리밍 과정을 돕기 위해 스트림에는 몇 가지 유틸리티 함수가 있습니다.

  • stream.finishReason — 에이전트가 스트리밍을 중단한 이유

  • stream.toolCalls — 에이전트가 호출한 도구 목록

  • stream.toolResults — 에이전트가 받은 도구 결과

  • stream.usage — 에이전트가 사용한 전체 토큰 수 (에이전트나 워크플로우가 도구로 사용된 경우 포함)

  • stream.text — 에이전트 응답의 전체 텍스트

  • stream.object — output 또는 실험적 output 사용 시 에이전트 응답 객체

  • stream.textStream — 에이전트 응답 텍스트를 방출하는 읽기 가능한 스트림

도구(tool)에서 스트림 사용하는 방법

각 도구는 writer 인자를 받게 되는데, 이는 사용자 정의 write 함수를 가진 쓰기 가능한 스트림입니다. 이 write 함수는 도구의 응답을 스트림에 작성하기 위해 사용됩니다.

src/mastra/tools/test-tool.ts:

import { createTool } from "@mastra/core/tools";
import { z } from "zod";

export const weatherInfo = createTool({
  id: "Get Weather Information",
  inputSchema: z.object({
    city: z.string(),
  }),
  outputSchema: z.object({
    conditions: z.string(),
    temperature: z.number(),
  }),
  description: `특정 도시의 현재 날씨 정보를 가져옵니다`,
  execute: async ({ context: { city }, writer }) => {
    writer.write({
      type: "weather-data",
      args: {
        city
      },
      status: "pending"
    });
    // 도구 로직 예: API 호출
    console.log("도구를 사용해", city, "날씨 정보를 가져오는 중");

    writer.write({
      type: "weather-data",
      args: {
        city
      },
      status: "success",
      result: {
        temperature: 20,
        conditions: "맑음"
      }
    });

    return { temperature: 20, conditions: "맑음" }; // 예시 반환값
  },
});

에이전트에서 스트림을 사용하고 싶다면, 에이전트의 streamVNext 메서드를 사용하여 에이전트의 입력 스트림으로 연결(pipe)할 수 있습니다.

src/mastra/tools/test-tool.ts:

import { createTool } from "@mastra/core/tools";
import { z } from "zod";

export const weatherInfo = createTool({
  id: "Get Weather Information",
  description: `특정 도시의 현재 날씨 정보를 가져옵니다`,
  inputSchema: z.object({
    city: z.string(),
  }),
  outputSchema: z.object({
    text: z.string(),
  }),
  execute: async ({ context: { city }, writer, mastra }) => {
    const agent = mastra.getAgent('weatherAgent');
    const stream = await agent.streamVNext(`What is the weather in ${city}?`);

    await stream.pipeTo(writer);

    return {
      text: await stream.text,
    };
  },
});

스트림을 에이전트의 입력 스트림으로 연결하면 에이전트의 사용량을 자동으로 합산하여 전체 사용량을 계산할 수 있습니다.


2025년 7월 26일 기준 번역
by dongne.lab@gmail.com

Updated on