Astreus

Plugin

Sistema di strumenti estensibile con validazione tramite schema JSON e chiamata automatica delle funzioni

Sistema di strumenti estensibile con validazione tramite schema JSON e chiamata automatica delle funzioni

Panoramica

I plugin estendono le capacità degli agent fornendo strumenti che possono essere richiamati durante le conversazioni. Il sistema di plugin è costruito attorno a un pattern decorator che potenzia gli agent con capacità di esecuzione degli strumenti. Fornisce validazione automatica dei parametri, gestione degli errori e integrazione fluida con l'LLM tramite function calling.

Strumenti integrati

Astreus include diversi strumenti integrati disponibili per tutti gli agent:

Strumenti Knowledge

  • search_knowledge: cerca nella knowledge base dell'agent le informazioni rilevanti
    • query (string, obbligatorio): query di ricerca
    • limit (number, opzionale): numero massimo di risultati (predefinito: 5)
    • threshold (number, opzionale): soglia di similarità (predefinito: 0.7)

Strumenti Vision

  • analyze_image: analisi generale delle immagini con prompt personalizzati
  • describe_image: genera descrizioni adatte all'accessibilità
  • extract_text_from_image: capacità OCR per l'estrazione del testo

Creare plugin personalizzati

1

Definisci il tuo strumento

Crea una definizione di strumento con la funzione handler:

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

Crea il plugin

Raggruppa i tuoi strumenti in un 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

Registra con l'Agent

Registra il tuo plugin con un agent:

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

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

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

Tipi di parametri degli strumenti

Il sistema di plugin supporta una validazione completa dei parametri:

// 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)
}

Esempi di parametri

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 };
  }
};

Usare gli strumenti nelle conversazioni

Utilizzo automatico degli strumenti

Gli agent con plugin registrati possono usare automaticamente gli strumenti durante le conversazioni:

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..."

Esecuzione manuale degli strumenti

Puoi anche eseguire gli strumenti manualmente:

// 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' } })
]);

Task potenziati dagli strumenti

Usa gli strumenti in task strutturati tramite il modulo 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);
  }
});

Contesto e metadati degli strumenti

Gli strumenti ricevono un contesto di esecuzione con informazioni utili:

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() }
    };
  }
};

Tipi di risposta

Capire le risposte di esecuzione degli strumenti ti aiuta a gestire correttamente risultati ed errori.

Risposta di esecuzione dello strumento

Eseguire uno strumento restituisce un ToolCallResult con i dettagli dell'esecuzione:

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
}

Esecuzione dello strumento con errore

Quando uno strumento fallisce, l'errore viene incluso nel risultato:

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
}

Risposta dell'esecuzione di più strumenti

Eseguire più strumenti tramite Promise.all restituisce un array di risultati:

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
  }
]

Risposta della lista di strumenti

Recuperare gli strumenti disponibili restituisce un array di definizioni di strumenti:

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]
  }
]

Risposta della lista di plugin

Elenco dei plugin registrati:

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[] */ ]
  }
]

Ultimo aggiornamento: 6 luglio 2026