에이전트 워크플로

에이전트 워크플로 (Agent Workflows)

에이전트 워크플로는 하나 또는 여러 개의 에이전트를 도구와 함께 만들고 오케스트레이션해서 특정 작업을 수행하게 하는 강력한 시스템이에요. 기본 Workflow 시스템 위에 만들어져서, 에이전트 간 상호작용을 위한 매끄러운 인터페이스를 제공합니다.

출처: 공식문서

사용법

단일 에이전트 워크플로

가장 간단한 활용은 특정 도구를 가진 에이전트 하나를 만드는 거예요. 농담을 해주는 어시스턴트를 만드는 예시를 볼게요.

import { tool } from "llamaindex";
import { agent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";


// Define a joke-telling tool
const jokeTool = tool(
  () => "Baby Llama is called cria",
  {
    name: "joke",
    description: "Use this tool to get a joke",
  }
);


// Create an single agent workflow with the tool
const jokeAgent = agent({
  tools: [jokeTool],
  llm: openai({ model: "gpt-4o-mini" }),
});


// Run the workflow
const result = await jokeAgent.run("Tell me something funny");
console.log(result.data.result); // Baby Llama is called cria
console.log(result.data.message); // { role: 'assistant', content: 'Baby Llama is called cria' }

구조화 출력 (Structured Output)

에이전트 응답에 Zod 스키마가 담긴 responseFormat을 지정하면 응답에서 구조화 데이터를 뽑아낼 수 있어요. 응답을 특정 형식으로 받아야 추가 처리가 쉬울 때 유용합니다.

import { z } from "zod";
import { tool } from "llamaindex";
import { agent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";


// Define a weather tool
const weatherTool = tool({
  name: "weatherTool",
  description: "Get weather information",
  parameters: z.object({
    location: z.string(),
  }),
  execute: ({ location }) => {
    return `The weather in ${location} is sunny. The temperature is 72 degrees. The humidity is 50%. The wind speed is 10 mph.`;
  },
});


// Define the structure you want for the response
const responseSchema = z.object({
  temperature: z.number(),
  humidity: z.number(),
  windSpeed: z.number(),
});


// Create the agent
const weatherAgent = agent({
  name: "weatherAgent",
  tools: [weatherTool],
  llm: openai({ model: "gpt-4.1-mini" }),
});


// Run with structured output
const result = await weatherAgent.run("What's the weather in Tokyo?", {
  responseFormat: responseSchema,
});


console.log("Natural language result:", result.data.result);
console.log("Structured data:", result.data.object);
// Output: { temperature: 72, humidity: 50, windSpeed: 10 }

이때 에이전트는:

  1. 날씨 도구를 사용해 원시 날씨 정보를 가져오고
  2. 그 정보를 LLM으로 처리한 뒤
  3. 스키마에 맞춰 구조화 데이터를 추출하며
  4. 자연어 응답과 구조화 객체를 모두 반환해요

이벤트 스트리밍

에이전트 워크플로는 이벤트 스트리밍을 위한 통합 인터페이스를 제공해서, 실행 중에 발생하는 각종 이벤트를 추적하고 반응하기 쉬워요.

import { agentToolCallEvent, agentStreamEvent } from "@llamaindex/workflow";


// Get the workflow execution context
const events = jokeAgent.runStream("Tell me something funny");


// Stream and handle events
for await (const event of events) {
  if (agentToolCallEvent.include(event)) {
    console.log(`Tool being called: ${event.data.toolName}`);
  }
  if (agentStreamEvent.include(event)) {
    process.stdout.write(event.data.delta);
  }
}

멀티 에이전트 워크플로

에이전트 워크플로는 여러 에이전트를 오케스트레이션해서 복잡한 상호작용과 작업 인수인계(task handoff)를 가능하게 해줘요. 멀티 에이전트 워크플로의 각 에이전트는 다음이 필요합니다.

  • name: 에이전트를 구분하는 고유 식별자
  • description: 작업 라우팅에 쓰이는 목적 설명
  • tools: 에이전트가 사용할 수 있는 도구의 배열
  • canHandoffTo (선택): 이 에이전트가 작업을 위임할 수 있는 에이전트 이름 또는 인스턴스의 배열

농담과 날씨 정보를 결합하는 멀티 에이전트 시스템 예시를 볼게요.

import { tool } from "llamaindex";
import { multiAgent, agent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";
import { z } from "zod";


// Create a weather agent
const weatherAgent = agent({
  name: "WeatherAgent",
  description: "Provides weather information for any city",
  tools: [
    tool(
      {
        name: "fetchWeather",
        description: "Get weather information for a city",
        parameters: z.object({
          city: z.string(),
        }),
        execute: ({ city }) => `The weather in ${city} is sunny`,
      }
    ),
  ],
  llm: openai({ model: "gpt-4o-mini" }),
});


// Create a joke-telling agent
const jokeAgent = agent({
  name: "JokeAgent",
  description: "Tells jokes and funny stories",
  tools: [jokeTool], // Using the joke tool defined earlier
  llm: openai({ model: "gpt-4o-mini" }),
  canHandoffTo: [weatherAgent], // Can hand off to the weather agent
});


// Create the multi-agent workflow
const agents = multiAgent({
  agents: [jokeAgent, weatherAgent],
  rootAgent: jokeAgent, // Start with the joke agent
});


// Run the workflow
const result = await agents.run(
  "Give me a morning greeting with a joke and the weather in San Francisco"
);
console.log(result.data.result);

워크플로가 에이전트들을 조율하면서, 각 에이전트가 요청의 서로 다른 부분을 처리하고 적절한 때에 작업을 넘겨받게 돼요.

더 알아보기