Astreus

플러그인

Astreus 문서에서 플러그인에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.

JSON 스키마 검증과 자동 함수 호출을 갖춘 확장 가능한 도구 시스템

Overview

플러그인은 대화 중에 호출할 수 있는 도구를 제공하여 에이전트의 기능을 확장합니다. 플러그인 시스템은 도구 실행 기능으로 에이전트를 강화하는 데코레이터 패턴을 중심으로 구축되었습니다. 자동 매개변수 검증, 오류 처리, 함수 호출을 통한 원활한 LLM 통합을 제공합니다.

Built-in Tools

Astreus는 모든 에이전트가 사용할 수 있는 여러 내장 도구를 기본으로 제공합니다.

Knowledge Tools

  • search_knowledge: 관련 정보를 위해 에이전트의 지식 베이스를 검색합니다
    • query (string, required): 검색 쿼리
    • limit (number, optional): 최대 결과 수 (기본값: 5)
    • threshold (number, optional): 유사도 임계값 (기본값: 0.7)

Vision Tools

  • analyze_image: 커스텀 프롬프트를 사용한 일반 이미지 분석
  • describe_image: 접근성을 고려한 설명 생성
  • extract_text_from_image: 텍스트 추출을 위한 OCR 기능

Creating Custom Plugins

1

Define Your Tool

핸들러 함수와 함께 도구 정의를 만드세요.

import { ToolDefinition, ToolContext, ToolParameterValue } from '@astreus-ai/astreus';

const weatherTool: ToolDefinition = {
  name: 'get_weather',
  description: 'Get current weather information for a location',
  parameters: {
    location: {
      name: 'location',
      type: 'string',
      description: 'City name or location',
      required: true
    },
    units: {
      name: 'units',
      type: 'string',
      description: 'Temperature units (celsius or fahrenheit)',
      required: false
    }
  },
  handler: async (params: Record<string, ToolParameterValue>, context?: ToolContext) => {
    try {
      // Your tool implementation
      const weather = await fetchWeather(params.location as string, params.units as string);

      return {
        success: true,
        data: {
          temperature: weather.temp,
          conditions: weather.conditions,
          location: params.location
        }
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }
};
2

Create the Plugin

도구를 플러그인으로 묶으세요.

import { Plugin, ToolParameterValue } from '@astreus-ai/astreus';

const weatherPlugin: Plugin = {
  name: 'weather-plugin',
  version: '1.0.0',
  description: 'Weather information tools',
  tools: [weatherTool],
  
  // Optional: Plugin initialization
  initialize: async (config?: Record<string, ToolParameterValue>) => {
    console.log('Weather plugin initialized');
  },
  
  // Optional: Plugin cleanup
  cleanup: async () => {
    console.log('Weather plugin cleaned up');
  }
};
3

Register with Agent

에이전트에 플러그인을 등록하세요.

import { Agent } from '@astreus-ai/astreus';

const agent = await Agent.create({
  name: 'WeatherAgent',
  model: 'gpt-4o'
});

// Register the plugin
await agent.registerPlugin(weatherPlugin);

Tool Parameter Types

플러그인 시스템은 포괄적인 매개변수 검증을 지원합니다.

// Parameter type definitions
interface ToolParameter {
  name: string;              // Parameter name
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  description: string;       // Parameter description
  required?: boolean;        // Whether parameter is required (optional, defaults to false)
  enum?: Array<string | number>;  // Allowed values (supports both string and number)
  properties?: Record<string, ToolParameter>; // For object types (nested properties)
  items?: ToolParameter;     // For array types (item type definition)
}

Parameter Examples

const advancedTool: ToolDefinition = {
  name: 'process_data',
  description: 'Process data with various options',
  parameters: {
    // String with enum values
    format: {
      name: 'format',
      type: 'string',
      description: 'Output format',
      required: true,
      enum: ['json', 'csv', 'xml']
    },
    
    // Number parameter (optional)
    limit: {
      name: 'limit',
      type: 'number',
      description: 'Maximum records to process',
      required: false
    },
    
    // Object with nested properties
    options: {
      name: 'options',
      type: 'object',
      description: 'Processing options',
      required: false,
      properties: {
        includeHeaders: {
          name: 'includeHeaders',
          type: 'boolean',
          description: 'Include column headers',
          required: false
        }
      }
    },
    
    // Array of strings
    fields: {
      name: 'fields',
      type: 'array',
      description: 'Fields to include',
      required: false,
      items: {
        name: 'field',
        type: 'string',
        description: 'Field name'
      }
    }
  },
  handler: async (params) => {
    // Tool implementation
    return { success: true, data: params };
  }
};

Using Tools in Conversations

Automatic Tool Usage

등록된 플러그인을 가진 에이전트는 대화 중에 자동으로 도구를 사용할 수 있습니다.

const agent = await Agent.create({
  name: 'AssistantAgent',
  model: 'gpt-4o'
});

await agent.registerPlugin(weatherPlugin);

// Agent can automatically call tools based on conversation
const response = await agent.ask("What's the weather like in Tokyo?");
// Agent will automatically call get_weather tool and incorporate results

console.log(response);
// "The current weather in Tokyo is 22°C with clear skies..."

Manual Tool Execution

도구를 수동으로 실행할 수도 있습니다.

// Execute single tool
const result = await agent.executeTool({
  id: 'call-123',
  name: 'get_weather',
  parameters: {
    location: 'New York',
    units: 'celsius'
  }
});

console.log(result.result.success ? result.result.data : result.result.error);

// Execute multiple tools sequentially
const results = await Promise.all([
  agent.executeTool({ id: 'call-1', name: 'get_weather', parameters: { location: 'Tokyo' } }),
  agent.executeTool({ id: 'call-2', name: 'get_weather', parameters: { location: 'London' } })
]);

Tool-Enhanced Tasks

Task 모듈을 통해 구조화된 작업에서 도구를 사용하세요.

const task = await agent.createTask({
  prompt: "Compare the weather in Tokyo, London, and New York",
  useTools: true
});

const result = await agent.executeTask(task.id, {
  stream: true,
  onChunk: (chunk) => {
    console.log(chunk);
  }
});

Tool Context and Metadata

도구는 유용한 정보를 담은 실행 컨텍스트를 받습니다.

const contextAwareTool: ToolDefinition = {
  name: 'log_action',
  description: 'Log an action with context',
  parameters: {
    action: {
      name: 'action',
      type: 'string',
      description: 'Action to log',
      required: true
    }
  },
  handler: async (params, context) => {
    // Access execution context
    console.log(`Agent ${context?.agentId} performed: ${params.action}`);
    console.log(`Task ID: ${context?.taskId}`);
    console.log(`User ID: ${context?.userId}`);
    console.log(`Metadata:`, context?.metadata);
    
    return {
      success: true,
      data: { logged: true, timestamp: new Date().toISOString() }
    };
  }
};

Response Types

도구 실행 응답을 이해하면 결과와 오류를 올바르게 처리할 수 있습니다.

Tool Execution Response

도구를 실행하면 실행 세부 정보를 담은 ToolCallResult를 반환합니다.

const result = await agent.executeTool({
  id: "call-123",
  name: "get_weather",
  parameters: {
    location: "Tokyo",
    units: "celsius"
  }
});

// Response structure:
{
  id: "call-123",
  name: "get_weather",
  result: {
    success: true,
    data: {
      temperature: 22,
      conditions: "clear skies",
      location: "Tokyo",
      humidity: 65,
      wind: "5 km/h"
    }
  },
  executionTime: 250  // Execution time in milliseconds
}

Tool Execution with Error

도구가 실패하면 오류가 결과에 포함됩니다.

const result = await agent.executeTool({
  id: "call-456",
  name: "get_weather",
  parameters: {
    location: "InvalidCity"
  }
});

// Response with error:
{
  id: "call-456",
  name: "get_weather",
  result: {
    success: false,
    error: "Location 'InvalidCity' not found"
  },
  executionTime: 150
}

Multiple Tool Execution Response

Promise.all을 사용해 여러 도구를 실행하면 결과의 배열을 반환합니다.

const results = await Promise.all([
  agent.executeTool({ id: "call-1", name: "get_weather", parameters: { location: "Tokyo" } }),
  agent.executeTool({ id: "call-2", name: "get_weather", parameters: { location: "London" } }),
  agent.executeTool({ id: "call-3", name: "search_knowledge", parameters: { query: "climate" } })
]);

// Response structure:
[
  {
    id: "call-1",
    name: "get_weather",
    result: {
      success: true,
      data: { temperature: 22, conditions: "clear" }
    },
    executionTime: 200
  },
  {
    id: "call-2",
    name: "get_weather",
    result: {
      success: true,
      data: { temperature: 15, conditions: "cloudy" }
    },
    executionTime: 220
  },
  {
    id: "call-3",
    name: "search_knowledge",
    result: {
      success: true,
      data: [
        { content: "Climate patterns...", similarity: 0.92 },
        { content: "Global warming...", similarity: 0.85 }
      ]
    },
    executionTime: 180
  }
]

Tool List Response

사용 가능한 도구를 조회하면 도구 정의의 배열을 반환합니다.

const tools = agent.getTools();

// Response structure:
[
  {
    name: "get_weather",
    description: "Get current weather information for a location",
    parameters: {
      location: {
        name: "location",
        type: "string",
        description: "City name or location",
        required: true
      },
      units: {
        name: "units",
        type: "string",
        description: "Temperature units",
        required: false
      }
    },
    handler: [Function]
  },
  {
    name: "search_knowledge",
    description: "Search through the agent's knowledge base",
    parameters: { /* ... */ },
    handler: [Function]
  }
]

Plugin List Response

등록된 플러그인 목록입니다.

const plugins = agent.listPlugins();

// Response structure:
[
  {
    name: "weather-plugin",
    version: "1.0.0",
    description: "Weather information tools",
    tools: [ /* ToolDefinition[] */ ],
    initialize: [Function],
    cleanup: [Function]
  },
  {
    name: "data-plugin",
    version: "2.1.0",
    description: "Data processing utilities",
    tools: [ /* ToolDefinition[] */ ]
  }
]

마지막 업데이트: 2026년 7월 6일