에이전트 런타임 컨텍스트(Runtime Context)

Mastra는 의존성 주입을 기반으로 한 시스템인 런타임 컨텍스트를 제공하여, 런타임 변수로 에이전트와 도구를 구성할 수 있게 해줍니다. 매우 유사한 작업을 수행하는 여러 다른 에이전트를 생성하고 있다면, 런타임 컨텍스트를 사용하여 이들을 하나의 에이전트로 결합할 수 있습니다.

개요

의존성 주입 시스템을 통해 다음과 같은 작업이 가능합니다:

  1. 타입 안전한 runtimeContext를 통해 에이전트에 런타임 구성 변수 전달

  2. 도구 실행 컨텍스트 내에서 이러한 변수에 액세스

  3. 기본 코드를 변경하지 않고 에이전트 동작 수정

  4. 동일한 에이전트 내의 여러 도구 간 구성 공유

기본 사용법

const agent = mastra.getAgent("weatherAgent");

// runtimeContext의 타입 구조 정의
type WeatherRuntimeContext = {
  "temperature-scale": "celsius" | "fahrenheit";
};

const runtimeContext = new RuntimeContext<WeatherRuntimeContext>();
runtimeContext.set("temperature-scale", "celsius");

const response = await agent.generate("오늘 날씨는 어때요?", {
  runtimeContext,
});

console.log(response.text);

REST API와 함께 사용하기

Cloudflare CF-IPCountry 헤더를 사용하여 사용자의 위치에 따라 온도 단위를 동적으로 설정하는 방법입니다:

src/index.ts:

import { Mastra } from "@mastra/core";
import { RuntimeContext } from "@mastra/core/di";
import { agent as weatherAgent } from "./agents/weather";

// 명확하고 설명적인 타입으로 RuntimeContext 타입 정의
type WeatherRuntimeContext = {
  "temperature-scale": "celsius" | "fahrenheit";
};

export const mastra = new Mastra({
  agents: {
    weather: weatherAgent,
  },
  server: {
    middleware: [
      async (c, next) => {
        const country = c.req.header("CF-IPCountry");
        const runtimeContext = c.get<WeatherRuntimeContext>("runtimeContext");

        // 국가에 따라 온도 척도 설정
        runtimeContext.set(
          "temperature-scale",
          country === "US" ? "fahrenheit" : "celsius",
        );

        await next(); // next() 호출을 잊지 마세요
      },
    ],
  },
});

변수를 사용한 도구 생성

도구는 runtimeContext 변수에 액세스할 수 있으며 에이전트의 runtimeContext 타입을 준수해야 합니다:

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

export const weatherTool = createTool({
  id: "getWeather",
  description: "특정 위치의 현재 날씨 정보를 가져옵니다",
  inputSchema: z.object({
    location: z.string().describe("날씨를 확인할 위치"),
  }),
  execute: async ({ context, runtimeContext }) => {
    // runtimeContext 변수에 타입 안전한 액세스
    const temperatureUnit = runtimeContext.get("temperature-scale");

    const weather = await fetchWeather(context.location, {
      temperatureUnit,
    });

    return { result: weather };
  },
});

async function fetchWeather(
  location: string,
  { temperatureUnit }: { temperatureUnit: "celsius" | "fahrenheit" },
): Promise<WeatherResponse> {
  // 날씨 API 호출 구현
  const response = await weatherApi.fetch(location, temperatureUnit);

  return {
    location,
    temperature: "72°F",
    conditions: "맑음",
    unit: temperatureUnit,
  };
}

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

Updated on