Astreus

插件

在 Astreus 文档中了解 插件,获取用于构建智能体系统的设置指导、API 模式和实用示例。 了解构建可靠的 Astreus 智能体系统所需的设置模式、API 和实用示例。

具备 JSON schema 校验和自动函数调用能力的可扩展工具系统

概述

插件(Plugin)通过提供可在对话中调用的工具来扩展代理的能力。插件系统基于装饰器模式构建,为代理增添工具执行能力。它提供自动参数校验、错误处理,并与 LLM 的函数调用无缝集成。

内置工具

Astreus 自带若干内置工具,所有代理均可使用:

知识库工具

  • search_knowledge:在代理的知识库中搜索相关信息
    • query(string,必填):搜索查询
    • limit(number,可选):最大结果数(默认:5)
    • threshold(number,可选):相似度阈值(默认:0.7)

视觉工具

  • analyze_image:使用自定义提示词进行通用图像分析
  • describe_image:生成无障碍友好的图像描述
  • extract_text_from_image:用于文本提取的 OCR 能力

创建自定义插件

1

定义你的工具

创建一个带有处理函数的工具定义:

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

创建插件

将工具打包为插件:

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

注册到代理

将插件注册到代理上:

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

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

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

工具参数类型

插件系统支持全面的参数校验:

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

参数示例

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

在对话中使用工具

自动工具调用

注册了插件的代理可以在对话过程中自动使用工具:

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

手动执行工具

你也可以手动执行工具:

// 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 模块在结构化任务中使用工具:

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

工具上下文与元数据

工具会接收到包含有用信息的执行上下文:

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

响应类型

理解工具执行的响应有助于正确处理结果和错误。

工具执行响应

执行工具会返回一个包含执行详情的 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
}

带有错误的工具执行

当工具执行失败时,错误信息会包含在结果中:

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
}

多工具执行响应

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

工具列表响应

获取可用工具会返回一个工具定义数组:

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

插件列表响应

列出已注册的插件:

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日