From b4e88673620bf40abe11fb3091ab42d030021c58 Mon Sep 17 00:00:00 2001 From: Euraxluo Date: Sat, 17 May 2025 21:52:47 +0800 Subject: [PATCH 1/3] feat: add Agent API design spec --- julia/src/api/spec/api-spec.yaml | 233 ++++- julia/src/api/spec/paths/agents.yaml | 1128 +++++++++++++++++++++ julia/src/api/spec/schemas/agents.yaml | 1001 ++++++++++++++++++ julia/src/api/spec/schemas/responses.yaml | 106 ++ 4 files changed, 2426 insertions(+), 42 deletions(-) create mode 100644 julia/src/api/spec/paths/agents.yaml create mode 100644 julia/src/api/spec/schemas/agents.yaml create mode 100644 julia/src/api/spec/schemas/responses.yaml diff --git a/julia/src/api/spec/api-spec.yaml b/julia/src/api/spec/api-spec.yaml index 296df7b7..41d45416 100644 --- a/julia/src/api/spec/api-spec.yaml +++ b/julia/src/api/spec/api-spec.yaml @@ -1,50 +1,199 @@ -openapi: 3.1.0 +openapi: 3.0.3 info: title: JuliaOS API - description: API for JuliaOS backend server - version: 0.1.0 - + description: | + JuliaOS API provides a complete interface for managing agents, groups, price data, DEX interactions, and trading strategies. + + This API enables you to: + - Create, configure, and manage autonomous agents + - Organize agents into collaborative groups + - Obtain real-time and historical price data + - Interact with decentralized exchanges (DEXs) + - Configure and execute trading strategies + - Manage blockchain connections and wallets + version: 0.2.0 + license: + name: MIT + url: https://github.com/Juliaoscode/JuliaOS/blob/main/LICENSE servers: - url: /api/v1 - + +tags: + - name: Agents + description: | + The agent system is a flexible framework for creating, managing, and deploying autonomous agents. Agents can perform various tasks such as trading, monitoring, data collection, and notifications. + + Key features: + - Agent lifecycle management (create, start, pause, resume, stop, delete) + - Agent configuration and customization + - Agent monitoring and health checks + - Inter-agent communication through group mechanisms + - Agent memory management + - Extensible agent capabilities and skills + - Task execution based on capabilities and skills + - Integration with LLMs for AI-driven functionality + + Agent types: + - TRADING: Trading agents + - MONITOR: Monitoring agents + - ARBITRAGE: Arbitrage agents + - DATA_COLLECTION: Data collection agents + - NOTIFICATION: Notification agents + - CUSTOM: Custom agents + - name: Groups + description: Creation and management of agent groups + - name: Price Data + description: Real-time and historical price data + - name: DEX + description: Interactions with decentralized exchanges + - name: Blockchain + description: Blockchain network connections and wallet management + - name: Trading Strategies + description: Configuration, backtesting, and execution of trading strategies + paths: + # Agent related paths /agents: - get: - operationId: listAgents - summary: Get all agents - description: Retrieve a list of all agents - responses: - '200': - description: A list of agents - content: - application/json: - schema: - type: array - items: - $ref: '#/components/schemas/Agent' - post: - operationId: createAgent - summary: Create a new agent - description: Create a new agent with the provided details - requestBody: - required: true - content: - application/json: - schema: - $ref: '#/components/schemas/Agent' - responses: - '201': - description: Agent created successfully - content: - application/json: - schema: - $ref: '#/components/schemas/Agent' - + $ref: "./paths/agents.yaml#/paths/~1agents" + /agents/{agent_id}: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}" + /agents/{agent_id}/start: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1start" + /agents/{agent_id}/stop: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1stop" + /agents/{agent_id}/pause: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1pause" + /agents/{agent_id}/resume: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1resume" + /agents/{agent_id}/execute: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1execute" + /agents/{agent_id}/memory: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1memory" + /agents/{agent_id}/metrics: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1metrics" + /agents/{agent_id}/health: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1health" + /agents/monitor/start: + $ref: "./paths/agents.yaml#/paths/~1agents~1monitor~1start" + /agents/monitor/stop: + $ref: "./paths/agents.yaml#/paths/~1agents~1monitor~1stop" + /agents/{agent_id}/swarm/publish: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1swarm~1publish" + /agents/{agent_id}/swarm/subscribe: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1swarm~1subscribe" + /agents/{agent_id}/swarm/unsubscribe: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1swarm~1unsubscribe" + /agents/{agent_id}/swarm/connect: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1swarm~1connect" + /agents/{agent_id}/swarm/disconnect: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1swarm~1disconnect" + /agents/{agent_id}/clone: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1clone" + /agents/bulk-delete: + $ref: "./paths/agents.yaml#/paths/~1agents~1bulk-delete" + /agents/{agent_id}/abilities: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1abilities" + /agents/{agent_id}/skills: + $ref: "./paths/agents.yaml#/paths/~1agents~1{agent_id}~1skills" + components: + # 引用 schemas 组件 schemas: - Agent: - type: object - properties: - id: - type: string - example: "agent123" \ No newline at end of file + # Agent related models + AgentInfo: + $ref: './schemas/agents.yaml#/components/schemas/AgentInfo' + AgentConfig: + $ref: './schemas/agents.yaml#/components/schemas/AgentConfig' + AgentStatus: + $ref: './schemas/agents.yaml#/components/schemas/AgentStatus' + AgentCreated: + $ref: './schemas/agents.yaml#/components/schemas/AgentCreated' + AgentUpdate: + $ref: './schemas/agents.yaml#/components/schemas/AgentUpdate' + TaskRequest: + $ref: './schemas/agents.yaml#/components/schemas/TaskRequest' + TaskSubmitted: + $ref: './schemas/agents.yaml#/components/schemas/TaskSubmitted' + TaskInfo: + $ref: './schemas/agents.yaml#/components/schemas/TaskInfo' + AgentCloneRequest: + $ref: './schemas/agents.yaml#/components/schemas/AgentCloneRequest' + AgentDeleteResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentDeleteResponse' + AgentBulkDeleteRequest: + $ref: './schemas/agents.yaml#/components/schemas/AgentBulkDeleteRequest' + AgentBulkDeleteResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentBulkDeleteResponse' + # Agent memory related + AgentMemoryRequest: + $ref: './schemas/agents.yaml#/components/schemas/AgentMemoryRequest' + AgentMemoryResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentMemoryResponse' + AgentMemoryClearResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentMemoryClearResponse' + # Agent metrics and health status + AgentMetricsResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentMetricsResponse' + AgentHealthStatus: + $ref: './schemas/agents.yaml#/components/schemas/AgentHealthStatus' + AgentHealthResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentHealthResponse' + # Agent monitoring + MonitorResponse: + $ref: './schemas/agents.yaml#/components/schemas/MonitorResponse' + # Group communication + SwarmPublishRequest: + $ref: './schemas/agents.yaml#/components/schemas/SwarmPublishRequest' + SwarmSubscribeRequest: + $ref: './schemas/agents.yaml#/components/schemas/SwarmSubscribeRequest' + AgentSwarmOperationResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentSwarmOperationResponse' + SwarmConnectRequest: + $ref: './schemas/agents.yaml#/components/schemas/SwarmConnectRequest' + SwarmConnectResponse: + $ref: './schemas/agents.yaml#/components/schemas/SwarmConnectResponse' + SwarmDisconnectResponse: + $ref: './schemas/agents.yaml#/components/schemas/SwarmDisconnectResponse' + # Agent lifecycle + AgentLifecycleResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentLifecycleResponse' + # Agent capabilities and skills + AgentAbilityRequest: + $ref: './schemas/agents.yaml#/components/schemas/AgentAbilityRequest' + AgentAbilityResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentAbilityResponse' + AgentSkillRequest: + $ref: './schemas/agents.yaml#/components/schemas/AgentSkillRequest' + AgentSkillResponse: + $ref: './schemas/agents.yaml#/components/schemas/AgentSkillResponse' + + # Reference common responses + responses: + BadRequest: + $ref: "./schemas/responses.yaml#/components/responses/BadRequest" + NotFound: + $ref: "./schemas/responses.yaml#/components/responses/NotFound" + InternalError: + $ref: "./schemas/responses.yaml#/components/responses/InternalError" + Unauthorized: + $ref: "./schemas/responses.yaml#/components/responses/Unauthorized" + Forbidden: + $ref: "./schemas/responses.yaml#/components/responses/Forbidden" + TooManyRequests: + $ref: "./schemas/responses.yaml#/components/responses/TooManyRequests" + + # Security schemes + securitySchemes: + ApiKeyAuth: + type: apiKey + in: header + name: X-API-Key + BearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + +# Global security requirements +security: + - ApiKeyAuth: [] + - BearerAuth: [] diff --git a/julia/src/api/spec/paths/agents.yaml b/julia/src/api/spec/paths/agents.yaml new file mode 100644 index 00000000..eb1e673c --- /dev/null +++ b/julia/src/api/spec/paths/agents.yaml @@ -0,0 +1,1128 @@ +paths: + /agents: + get: + operationId: listAgents + summary: Get agent list + description: | + Lists all agents registered in the system. Results can be filtered using various criteria. + + Supported filters: + - Agent type (TRADING, MONITOR, ARBITRAGE, etc.) + - Agent status (CREATED, RUNNING, PAUSED, etc.) + - Agent name + + Results support sorting and pagination. + tags: + - Agents + parameters: + - name: type + in: query + description: | + Filter by agent type: + * TRADING - Trading agents + * MONITOR - Monitoring agents + * ARBITRAGE - Arbitrage agents + * DATA_COLLECTION - Data collection agents + * NOTIFICATION - Notification agents + * CUSTOM - Custom agents + schema: + type: string + enum: [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] + - name: status + in: query + description: | + Filter by agent status: + * CREATED - Created + * INITIALIZING - Initializing + * RUNNING - Running + * PAUSED - Paused + * STOPPED - Stopped + * ERROR - Error state + schema: + type: string + enum: [CREATED, INITIALIZING, RUNNING, PAUSED, STOPPED, ERROR] + - name: name + in: query + description: Filter by agent name keyword + schema: + type: string + - name: order_by + in: query + description: Sort field (created_at, name, type, etc.) + schema: + type: string + enum: [created_at, name, type, status] + - name: order_direction + in: query + description: Sort direction + schema: + type: string + enum: [asc, desc] + - name: limit + in: query + description: Number of records per page + schema: + type: integer + minimum: 1 + maximum: 100 + default: 20 + - name: offset + in: query + description: Pagination offset + schema: + type: integer + minimum: 0 + default: 0 + responses: + '200': + description: Successfully returned agent list + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentListResponse' + '400': + description: Request parameter error + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + + post: + operationId: createAgent + summary: Create new agent + description: | + Creates a new agent and initializes its configuration. After creation, the agent is in CREATED state and must be started using the start endpoint. + + Main parameters that can be configured: + * name - Agent name (required) + * type - Agent type (required) + * description - Agent description + * abilities - List of agent abilities + * chains - Supported blockchain networks + * llm_config - LLM configuration (for AI agents) + * memory_config - Memory configuration + * parameters - Custom parameters + * max_task_history - Maximum number of task history records + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentConfig' + responses: + '201': + description: Agent created successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentCreated' + '400': + description: Request data validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '409': + description: Name conflict + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentConflictError' + + /agents/{agent_id}: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + get: + operationId: getAgentStatus + summary: Get agent status + description: | + Get detailed status information for the specified agent, including: + * Basic information (ID, name, type, etc.) + * Current running status + * Recent task execution status + * Performance metrics + * Configuration information + * Last activity time + * Error information (if any) + tags: + - Agents + responses: + '200': + description: Successfully returned agent status + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStatus' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + put: + operationId: updateAgent + summary: Update agent + description: | + Update configuration information for an existing agent. Supports the following update operations: + * Modify agent name and description + * Update agent ability list + * Adjust model configuration + * Modify custom parameters + * Update metadata + + Note: Some core configurations (such as agent type) cannot be changed after creation. + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentUpdate' + responses: + '200': + description: Agent updated successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentInfo' + '400': + description: Request data validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + delete: + operationId: deleteAgent + summary: Delete agent + description: | + Delete the specified agent. The deletion process: + * Stops all executing tasks + * Clears the agent's memory state + * Removes the agent's configuration information + * Disconnects from groups + + Note: Deletion is irreversible, please proceed with caution. + tags: + - Agents + responses: + '200': + description: Agent deleted successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentDeleteResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Conflict, unable to delete (e.g., agent is executing important tasks) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/start: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: startAgent + summary: Start agent + description: | + Start the specified agent. The startup process includes: + * Initializing the agent runtime environment + * Loading configuration and capabilities + * Restoring memory state (if any) + * Connecting to necessary external services + * Beginning execution of predefined tasks + tags: + - Agents + responses: + '200': + description: Agent started successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentLifecycleResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: State conflict (e.g., agent is already running) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/stop: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: stopAgent + summary: Stop agent + description: | + Stop the specified agent. The stopping process includes: + * Safely terminating current executing tasks + * Saving current state + * Disconnecting from external services + * Releasing resources + + Note: The stop operation preserves the agent's configuration and state, which can be restarted at any time. + tags: + - Agents + responses: + '200': + description: Agent stopped successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentLifecycleResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: State conflict (e.g., agent is already stopped) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/pause: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: pauseAgent + summary: Pause agent + description: | + Pause the agent's execution. In paused state: + * Stops accepting new tasks + * Maintains existing connections + * Preserves memory state + * Can be quickly resumed + + The pause operation is suitable for temporarily interrupting agent activities. + tags: + - Agents + responses: + '200': + description: Agent paused successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentLifecycleResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: State conflict (e.g., agent is not running) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/resume: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: resumeAgent + summary: Resume agent + description: | + Resume a paused agent. The resumption process: + * Begins accepting tasks again + * Checks and restores previous work state + * Continues executing periodic tasks + * Reactivates all capabilities + tags: + - Agents + responses: + '200': + description: Agent resumed successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentLifecycleResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: State conflict (e.g., agent is not in paused state) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/execute: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: executeAgentTask + summary: Execute agent task + description: | + Have the agent execute a specified task. Supports: + * Synchronous execution: wait for task completion and return results + * Asynchronous execution: immediately return task ID, results queried via other APIs + * Scheduled execution: set task to execute at a specific time + * Conditional execution: set trigger conditions + + Detailed logs and performance metrics are recorded during task execution. + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentTaskRequest' + responses: + '200': + description: Task submitted successfully, execution results returned + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentTaskResponse' + '202': + description: Task accepted and queued, but not yet completed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/TaskSubmitted' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent cannot execute task (e.g., incorrect state) + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/memory: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + get: + operationId: getAgentMemory + summary: Get agent memory + description: | + Get the agent's memory state. Memory contains: + * Historical interaction records + * Learned knowledge + * Context information + * Temporary data + * Cached calculation results + + Can be used for analyzing agent behavior and debugging issues. + tags: + - Agents + responses: + '200': + description: Successfully returned agent memory state + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentMemoryResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + put: + operationId: updateAgentMemory + summary: Update agent memory + description: | + Update the agent's memory state. Supports: + * Adding new memory items + * Modifying existing memory + * Setting memory expiration time + * Adjusting memory priority + + Note: Modifying memory may affect agent behavior, please proceed with caution. + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentMemoryRequest' + responses: + '200': + description: Memory updated successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentMemoryResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + delete: + operationId: clearAgentMemory + summary: Clear agent memory + description: | + Clear the agent's memory state. This will: + * Delete all historical records + * Reset learning state + * Empty context information + * Delete cached data + + Suitable for resetting the agent to its initial state. + tags: + - Agents + responses: + '200': + description: Memory cleared successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentMemoryClearResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + /agents/{agent_id}/metrics: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + get: + operationId: getAgentMetrics + summary: Get agent metrics + description: | + Get the agent's performance metrics data. Includes: + * Task execution statistics (success rate, average duration, etc.) + * Resource usage (CPU, memory, network, etc.) + * Operation counters (API call count, event processing count, etc.) + * Error statistics + * Custom metrics + + Supports specified time range and aggregation methods. + tags: + - Agents + parameters: + - name: timeframe + in: query + description: Metrics time range (e.g., 1h, 24h, 7d, etc.) + schema: + type: string + responses: + '200': + description: Successfully returned agent metrics + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentMetricsResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + /agents/{agent_id}/health: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + get: + operationId: getAgentHealth + summary: Get agent health status + description: | + Get the agent's health status check results. Check items include: + * Core service status + * Necessary connection availability + * Resource usage level + * Error rate monitoring + * Performance metrics threshold check + * Data consistency verification + + Used for monitoring the agent's operation status and timely issue discovery. + tags: + - Agents + responses: + '200': + description: Successfully returned agent health status + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentHealthResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + + /agents/monitor/start: + post: + operationId: startAgentMonitor + summary: Start agent monitoring system + description: | + Start system-wide agent monitoring. Monitoring system features: + * Collect performance metrics of all agents + * Monitor agent health status + * Generate system-level statistical data + * Trigger alarm (when abnormal detected) + * Provide monitoring data storage and query + + Monitoring system has slight impact on system overall performance. + tags: + - Agents + responses: + '200': + description: Monitoring system started successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/MonitorResponse' + '409': + description: Monitoring system is already running + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/monitor/stop: + post: + operationId: stopAgentMonitor + summary: Stop agent monitoring system + description: | + Stop system-wide agent monitoring. The stopping operation will: + * Terminate all monitoring tasks + * Save current monitoring data + * Clean up temporary resources + * Stop alarm service + + Can be restarted at any time without losing historical data. + tags: + - Agents + responses: + '200': + description: Monitoring system stopped successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/MonitorResponse' + '409': + description: Monitoring system is not running + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/swarm/publish: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: publishToSwarm + summary: Publish message to swarm + description: | + Publish message to swarm. Supports: + * Publish to specific topic + * Broadcast to all subscribers + * Set message priority + * Message persistence + * Message confirmation mechanism + + Swarm communication is used for agent collaboration and information sharing. + tags: + - Agents + - Swarm + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmPublishRequest' + responses: + '200': + description: Message published successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentSwarmOperationResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent is not connected to swarm + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/swarm/subscribe: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: subscribeToSwarmTopic + summary: Subscribe swarm topic + description: | + Subscribe to swarm message topic. Supports: + * Subscribe to specific topic + * Use wildcard to subscribe to multiple topics + * Set message filter + * Configure subscription options (QoS, etc.) + * Set message processing callback + + After subscription, the agent will receive all messages of related topics. + tags: + - Agents + - Swarm + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmSubscribeRequest' + responses: + '200': + description: Subscription successful + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentSwarmOperationResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found or topic not subscribed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent is not connected to swarm + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/swarm/unsubscribe: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: unsubscribeFromSwarmTopic + summary: Unsubscribe swarm topic + description: | + Unsubscribe from swarm message topic. Will: + * Stop receiving messages of specified topic + * Clean up related subscription status + * Remove message processing callback + * Release related resources + + Does not affect other topic subscriptions. + tags: + - Agents + - Swarm + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmSubscribeRequest' + responses: + '200': + description: Unsubscribe successful + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentSwarmOperationResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found or topic not subscribed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent is not connected to swarm + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/swarm/connect: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: connectToSwarm + summary: Connect to swarm + description: | + Connect the agent to swarm communication backend. Includes: + * Establishing connection with swarm server + * Identity verification and authorization + * Restoring previous subscription (if any) + * Initializing message queue + * Setting heartbeat detection + + After connection establishment, the agent can start swarm communication. + tags: + - Agents + - Swarm + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmConnectRequest' + responses: + '200': + description: Connection successful + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmConnectResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent is already connected to swarm + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/swarm/disconnect: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: disconnectFromSwarm + summary: Disconnect swarm connection + description: | + Disconnect the agent from swarm communication backend. Will: + * Cancel all topic subscriptions + * Close message queue + * Save necessary status + * Clean up connection resources + * Stop heartbeat detection + + After disconnection, it can be reconnected at any time. + tags: + - Agents + - Swarm + responses: + '200': + description: Disconnection successful + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/SwarmDisconnectResponse' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Agent is not connected to swarm + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentStateConflictError' + + /agents/{agent_id}/clone: + parameters: + - name: agent_id + in: path + required: true + description: Clone agent ID + schema: + type: string + post: + operationId: cloneAgent + summary: Clone agent + description: Clone an existing agent and can override some configuration parameters + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentCloneRequest' + responses: + '201': + description: Agent cloned successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentCreated' + '400': + description: Request data validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Source agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Name conflict + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentConflictError' + + /agents/bulk-delete: + post: + operationId: bulkDeleteAgents + summary: Bulk delete agents + description: Bulk delete multiple agents + tags: + - Agents + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentBulkDeleteRequest' + responses: + '200': + description: Bulk delete operation completed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentBulkDeleteResponse' + '400': + description: Request data validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + + /agents/{agent_id}/abilities: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: registerAgentAbility + summary: Register agent ability + description: Register new ability for specified agent + tags: + - Agents + - Abilities + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentAbilityRequest' + responses: + '200': + description: Ability registered successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentAbilityResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Ability name conflict + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentConflictError' + + /agents/{agent_id}/skills: + parameters: + - name: agent_id + in: path + required: true + description: Unique identifier of the agent + schema: + type: string + post: + operationId: registerAgentSkill + summary: Register agent skill + description: Register new skill for specified agent, optionally set skill execution scheduling + tags: + - Agents + - Skills + requestBody: + required: true + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentSkillRequest' + responses: + '200': + description: Skill registered successfully + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentSkillResponse' + '400': + description: Request parameter validation failed + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/InvalidRequestError' + '404': + description: Agent not found + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentNotFoundError' + '409': + description: Skill name conflict + content: + application/json: + schema: + $ref: '../schemas/agents.yaml#/components/schemas/AgentConflictError' diff --git a/julia/src/api/spec/schemas/agents.yaml b/julia/src/api/spec/schemas/agents.yaml new file mode 100644 index 00000000..7fbace5a --- /dev/null +++ b/julia/src/api/spec/schemas/agents.yaml @@ -0,0 +1,1001 @@ +components: + schemas: + # Agent related schema definitions + AgentInfo: + type: object + required: + - id + - name + - type + - status + - created_at + properties: + id: + type: string + description: Unique identifier of the agent + example: "agent-123456" + name: + type: string + description: Agent name + example: "Market Data Analysis Agent" + type: + type: string + description: Agent type + enum: [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] + example: "TRADING" + status: + type: string + description: Current agent status + enum: [CREATED, INITIALIZING, RUNNING, PAUSED, STOPPED, ERROR] + example: "CREATED" + version: + type: string + description: Agent version number + example: "1.0.0" + description: + type: string + description: Agent functionality description + example: "Agent that analyzes market data and generates trading signals" + created_at: + type: string + format: date-time + description: Agent creation time + example: "2023-01-01T12:00:00Z" + last_active: + type: string + format: date-time + description: Agent last activity time + example: "2023-01-02T15:30:00Z" + capabilities: + type: array + description: List of capabilities supported by the agent + items: + type: string + example: "MARKET_ANALYSIS" + metrics: + type: object + description: Agent performance metrics + properties: + task_count: + type: integer + description: Number of completed tasks + example: 42 + success_rate: + type: number + format: float + description: Task success rate + minimum: 0 + maximum: 1 + example: 0.95 + avg_response_time: + type: number + format: float + description: Average response time (seconds) + example: 1.25 + + AgentConfig: + type: object + required: + - name + - type + properties: + name: + type: string + description: Agent name + example: "Market Data Analysis Agent" + type: + type: string + description: Agent type + enum: [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] + example: "TRADING" + description: + type: string + description: Agent functionality description + example: "Agent that analyzes market data and generates trading signals" + abilities: + type: array + description: List of abilities to enable + items: + type: string + example: "MARKET_ANALYSIS" + chains: + type: array + description: List of supported blockchains + items: + type: string + example: "ethereum" + llm_config: + type: object + description: Model configuration for LLM-based agents + properties: + provider: + type: string + description: LLM provider + example: "openai" + model_name: + type: string + description: Model name to use + example: "gpt-4o-mini" + temperature: + type: number + description: Model temperature parameter + minimum: 0 + maximum: 1 + example: 0.7 + max_tokens: + type: integer + description: Maximum tokens to generate + example: 1024 + memory_config: + type: object + description: Agent memory configuration + properties: + max_size: + type: integer + description: Maximum items in memory + example: 1000 + retention_policy: + type: string + description: Memory retention policy + enum: [lru, fifo, lifo] + example: "lru" + parameters: + type: object + description: Agent parameter configuration + additionalProperties: true + example: + analysis_depth: "STANDARD" + update_frequency: 300 + indicator_list: ["MA", "RSI", "MACD"] + max_task_history: + type: integer + description: Maximum number of task history records + example: 100 + metadata: + type: object + description: User-defined metadata + additionalProperties: true + example: + team: "Trading" + purpose: "Market Analysis" + priority: "high" + + AgentCreated: + type: object + required: + - id + - name + - type + - created_at + properties: + id: + type: string + description: ID of the newly created agent + example: "agent-123456" + name: + type: string + description: Agent name + example: "Market Data Analysis Agent" + type: + type: string + description: Agent type + enum: [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] + example: "TRADING" + created_at: + type: string + format: date-time + description: Agent creation time + example: "2023-01-01T12:00:00Z" + message: + type: string + description: Success message + example: "Agent created successfully" + + AgentStatus: + type: object + required: + - id + - name + - type + - status + - created_at + properties: + id: + type: string + description: Unique identifier of the agent + example: "agent-123456" + name: + type: string + description: Agent name + example: "Market Data Analysis Agent" + type: + type: string + description: Agent type + enum: [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] + example: "TRADING" + status: + type: string + description: Current agent status + enum: [CREATED, INITIALIZING, RUNNING, PAUSED, STOPPED, ERROR] + example: "RUNNING" + current_task: + type: object + description: Current executing task (if any) + properties: + id: + type: string + description: Task ID + example: "task-789012" + name: + type: string + description: Task name + example: "Market Data Analysis" + progress: + type: number + description: Task completion percentage + minimum: 0 + maximum: 100 + example: 75 + started_at: + type: string + format: date-time + description: Task start time + example: "2023-01-02T14:30:00Z" + last_error: + type: object + description: Last error (if any) + properties: + timestamp: + type: string + format: date-time + description: Error occurrence time + example: "2023-01-02T13:45:00Z" + message: + type: string + description: Error message + example: "Unable to connect to data source" + code: + type: string + description: Error code + example: "CONNECTION_ERROR" + created_at: + type: string + format: date-time + description: Agent creation time + example: "2023-01-01T12:00:00Z" + last_active: + type: string + format: date-time + description: Agent last activity time + example: "2023-01-02T15:30:00Z" + metrics: + type: object + description: Agent performance metrics + properties: + task_count: + type: integer + description: Number of completed tasks + example: 42 + success_rate: + type: number + format: float + description: Task success rate + minimum: 0 + maximum: 1 + example: 0.95 + avg_response_time: + type: number + format: float + description: Average response time (seconds) + example: 1.25 + configuration: + type: object + description: Current agent configuration + properties: + abilities: + type: array + description: List of enabled abilities + items: + type: string + example: "MARKET_ANALYSIS" + parameters: + type: object + description: Agent parameter configuration + additionalProperties: true + example: + analysis_depth: "STANDARD" + update_frequency: 300 + model_config: + type: object + description: Model configuration (if applicable) + properties: + model_name: + type: string + example: "gpt-4o-mini" + temperature: + type: number + example: 0.7 + + AgentUpdate: + type: object + properties: + name: + type: string + description: New agent name + example: "Enhanced Market Analysis Agent" + description: + type: string + description: New functionality description + example: "Provides advanced market data analysis and trading signal generation" + abilities: + type: array + description: Updated ability list + items: + type: string + example: "ADVANCED_MARKET_ANALYSIS" + model_config: + type: object + description: Updated model configuration + properties: + provider: + type: string + description: LLM provider + example: "openai" + model_name: + type: string + description: Model name to use + example: "gpt-4o" + temperature: + type: number + description: Model temperature parameter + minimum: 0 + maximum: 1 + example: 0.8 + max_tokens: + type: integer + description: Maximum tokens to generate + example: 4096 + parameters: + type: object + description: Updated parameter configuration + additionalProperties: true + example: + analysis_depth: "ADVANCED" + update_frequency: 180 + indicator_list: ["MA", "RSI", "MACD", "Bollinger", "Ichimoku"] + metadata: + type: object + description: Updated metadata + additionalProperties: true + example: + team: "Advanced Trading" + purpose: "Advanced Market Analysis" + priority: "critical" + + TaskRequest: + type: object + required: + - task_type + - input + properties: + task_type: + type: string + description: Task type + example: "price_analysis" + input: + type: object + description: Task input data + additionalProperties: true + priority: + type: integer + description: Task priority (1-10, 10 is highest) + minimum: 1 + maximum: 10 + default: 5 + timeout_seconds: + type: integer + description: Task timeout in seconds + minimum: 1 + default: 300 + callback_url: + type: string + description: Callback URL after task completion + example: "https://example.com/webhook/task-complete" + + TaskSubmitted: + type: object + properties: + task_id: + type: string + description: Task ID + example: "task-789012" + agent_id: + type: string + description: Agent ID + example: "agent-123456" + status: + type: string + description: Task status + example: "PENDING" + estimated_completion: + type: string + format: date-time + description: Estimated completion time + example: "2023-07-10T15:35:45Z" + priority: + type: integer + description: Task priority + example: 5 + task_type: + type: string + description: Task type + example: "price_analysis" + + TaskInfo: + type: object + properties: + task_id: + type: string + description: Task ID + example: "task-789012" + agent_id: + type: string + description: Agent ID + example: "agent-123456" + task_type: + type: string + description: Task type + example: "price_analysis" + status: + type: string + enum: [PENDING, RUNNING, COMPLETED, FAILED, CANCELLED] + example: "RUNNING" + created_at: + type: string + format: date-time + description: Task creation time + example: "2023-07-10T15:30:45Z" + started_at: + type: string + format: date-time + description: Task start time + example: "2023-07-10T15:31:00Z" + completed_at: + type: string + format: date-time + description: Task completion time + example: "2023-07-10T15:35:30Z" + progress_percent: + type: number + format: float + description: Task progress percentage + minimum: 0 + maximum: 100 + example: 75 + error: + type: string + description: Error message if failed + example: "API request timed out" + priority: + type: integer + description: Task priority + minimum: 1 + maximum: 10 + example: 5 + timeout_seconds: + type: integer + description: Task timeout in seconds + example: 300 + input_summary: + type: string + description: Task input summary + example: "Analysis for BTC/USD pair over 24h period" + AgentCloneRequest: # Clone agent request body + type: object + required: + - new_name + properties: + new_name: + type: string + description: New name for the cloned agent + example: "ClonedAgent1" + parameter_overrides: + type: object + description: Parameters to override, in key-value format + additionalProperties: true + + AgentDeleteResponse: # Agent deletion response body + type: object + properties: + message: + type: string + example: "Agent deleted successfully" + agent_id: + type: string + example: "agent-123" + + AgentBulkDeleteRequest: # Bulk agent deletion request body + type: object + required: + - agent_ids + properties: + agent_ids: + type: array + description: List of agent IDs to delete + items: + type: string + example: "agent-123" + + AgentBulkDeleteResponse: # Bulk agent deletion response body + type: object + properties: + results: + type: array + items: + type: object + properties: + agent_id: + type: string + example: "agent-123" + success: + type: boolean + example: true + error: + type: string + example: "Agent not found" + all_successful: + type: boolean + example: false + + # Agent health status schema + AgentHealthStatus: + type: object + properties: + agent_id: + type: string + description: Agent ID + example: "agent-123456" + status: + type: string + description: Health status + enum: [HEALTHY, WARNING, CRITICAL, UNKNOWN] + example: "HEALTHY" + message: + type: string + description: Status description + example: "Agent running in good condition" + timestamp: + type: string + format: date-time + description: Check time + example: "2023-10-12T15:31:00Z" + details: + type: object + description: Detailed information + additionalProperties: true + + # Agent task schema + AgentTaskRequest: + type: object + required: + - ability + properties: + ability: + type: string + description: Name of ability to execute + example: "ping" + mode: + type: string + description: Execution mode (direct execution or queue) + enum: [direct, queue] + default: "direct" + priority: + type: number + description: Task priority (only for queue mode) + default: 0 + additionalProperties: true + + AgentTaskResponse: + type: object + properties: + success: + type: boolean + description: Whether task executed successfully + example: true + queued: + type: boolean + description: Whether task is queued + example: false + agent_id: + type: string + description: Agent ID + example: "agent-123456" + result: + type: object + description: Task execution result + additionalProperties: true + example: + msg: "pong" + agent_id: "agent-123456" + agent_name: "Test Agent" + + # Agent memory operation schema + AgentMemoryRequest: + type: object + required: + - key + - value + properties: + key: + type: string + description: Memory key + example: "last_greeting" + value: + description: Memory value (any type) + example: "Hello!" + + AgentMemoryResponse: + type: object + properties: + success: + type: boolean + description: Whether operation was successful + example: true + agent_id: + type: string + description: Agent ID + example: "agent-123456" + memory: + type: object + description: Memory content + additionalProperties: true + example: + last_greeting: "Hello!" + counter: 42 + + AgentMemoryClearResponse: + type: object + properties: + success: + type: boolean + description: Whether operation was successful + example: true + agent_id: + type: string + description: Agent ID + example: "agent-123456" + message: + type: string + description: Success message + example: "Agent memory cleared" + + # Agent metrics response + AgentMetricsResponse: + type: object + properties: + success: + type: boolean + description: Whether operation was successful + example: true + data: + type: object + additionalProperties: + type: object + properties: + current: + type: number + example: 42 + type: + type: string + example: "GAUGE" + history: + type: array + items: + type: array + items: + oneOf: + - type: string + format: date-time + - type: number + example: [["2023-10-12T15:30:00Z", 42], ["2023-10-12T15:31:00Z", 43]] + last_updated: + type: string + format: date-time + example: "2023-10-12T15:31:00Z" + + # Agent health check response + AgentHealthResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + status: + type: string + enum: [HEALTHY, WARNING, CRITICAL, UNKNOWN] + example: "HEALTHY" + message: + type: string + example: "Agent running in good condition" + timestamp: + type: string + format: date-time + example: "2023-10-12T15:31:00Z" + details: + type: object + additionalProperties: true + + # Agent monitoring system response + MonitorResponse: + type: object + properties: + success: + type: boolean + example: true + message: + type: string + example: "Agent monitoring system started" + + # Swarm operation schema + SwarmPublishRequest: + type: object + required: + - topic + - message + properties: + topic: + type: string + description: Topic + example: "market.update" + message: + type: object + description: Message content + additionalProperties: true + example: + type: "price_update" + symbol: "BTC/USD" + price: 45000.25 + + SwarmSubscribeRequest: + type: object + required: + - topic + properties: + topic: + type: string + description: Topic + example: "market.update" + + AgentSwarmOperationResponse: + type: object + properties: + success: + type: boolean + description: Whether operation was successful + example: true + agent_id: + type: string + description: Agent ID + example: "agent-123456" + topic: + type: string + description: Topic + example: "market.update" + + # Agent ability registration request + AgentAbilityRequest: + type: object + required: + - name + - function + properties: + name: + type: string + description: Ability name + example: "analyze_market" + function: + type: string + description: Function code representing the ability + example: "function(agent, params) { return {result: 'Market analyzed'}; }" + description: + type: string + description: Ability description + example: "Analyze market status and generate report" + + # Agent ability registration response + AgentAbilityResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + ability_name: + type: string + example: "analyze_market" + message: + type: string + example: "Ability registered successfully" + + # Agent skill registration request + AgentSkillRequest: + type: object + required: + - name + - function + properties: + name: + type: string + description: Skill name + example: "monitor_prices" + function: + type: string + description: Function code representing the skill + example: "function(agent) { return {monitored: true}; }" + schedule: + type: number + description: Skill execution schedule interval (seconds), 0 means execute on demand only + example: 60 + description: + type: string + description: Skill description + example: "Regularly monitor price changes" + + # Agent skill registration response + AgentSkillResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + skill_name: + type: string + example: "monitor_prices" + schedule: + type: number + example: 60 + message: + type: string + example: "Skill registered successfully" + + # Swarm connection request + SwarmConnectRequest: + type: object + properties: + backend: + type: string + description: Swarm backend type + enum: [NONE, MEMORY, REDIS, NATS, ZEROMQ] + default: "MEMORY" + connection_string: + type: string + description: Connection string + example: "redis://localhost:6379" + + # Swarm connection response + SwarmConnectResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + backend: + type: string + example: "MEMORY" + message: + type: string + example: "Agent connected to swarm backend" + + # Swarm disconnect response + SwarmDisconnectResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + message: + type: string + example: "Agent disconnected from swarm backend" + + # Agent lifecycle response + AgentLifecycleResponse: + type: object + properties: + success: + type: boolean + example: true + agent_id: + type: string + example: "agent-123456" + status: + type: string + description: New agent status + example: "RUNNING" + message: + type: string + description: Operation success message + example: "Agent operation successful" + + # The following are common schemas extracted from paths/agents.yaml + # Pagination response structure + PaginationInfo: + type: object + properties: + total: + type: integer + description: Total number of records + example: 42 + limit: + type: integer + description: Records per page + example: 20 + offset: + type: integer + description: Offset + example: 0 + next_offset: + type: integer + description: Next page offset (if there is a next page) + example: 20 + + # Agent list response + AgentListResponse: + type: object + properties: + agents: + type: array + items: + $ref: '#/components/schemas/AgentInfo' + pagination: + $ref: '#/components/schemas/PaginationInfo' + + # Error response schema + ErrorResponse: + type: object + properties: + error: + type: string + example: "Error message" + + # Specific error responses + InvalidRequestError: + type: object + properties: + error: + type: string + example: "Invalid request format" + + AgentNotFoundError: + type: object + properties: + error: + type: string + example: "Agent not found" + + AgentConflictError: + type: object + properties: + error: + type: string + example: "Agent with this name already exists" + + AgentStateConflictError: + type: object + properties: + error: + type: string + example: "Agent is already running" \ No newline at end of file diff --git a/julia/src/api/spec/schemas/responses.yaml b/julia/src/api/spec/schemas/responses.yaml new file mode 100644 index 00000000..8f6ed478 --- /dev/null +++ b/julia/src/api/spec/schemas/responses.yaml @@ -0,0 +1,106 @@ +components: + responses: + BadRequest: + description: Request validation error or parameter error + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Bad Request" + message: + type: string + example: "Invalid parameter: 'limit' must be a positive integer" + validation_errors: + type: array + items: + type: object + properties: + field: + type: string + example: "limit" + message: + type: string + example: "must be a positive integer" + + NotFound: + description: The requested resource does not exist + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Not Found" + message: + type: string + example: "The requested resource was not found" + resource_id: + type: string + example: "agent-123" + + InternalError: + description: An internal server error occurred + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Internal Server Error" + message: + type: string + example: "An unexpected error occurred. Please try again later." + error_id: + type: string + example: "err-abc-123" + + Unauthorized: + description: Unauthorized access + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Unauthorized" + message: + type: string + example: "Authentication required to access this resource" + + Forbidden: + description: Access forbidden + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Forbidden" + message: + type: string + example: "You do not have permission to access this resource" + + TooManyRequests: + description: Request frequency exceeds limit + content: + application/json: + schema: + type: object + properties: + error: + type: string + example: "Too Many Requests" + message: + type: string + example: "Rate limit exceeded. Please try again later." + retry_after: + type: integer + example: 60 + description: "Recommended seconds to wait before retrying" \ No newline at end of file From 6d384194ef8dbc0032242bd87cf4c69224e57998 Mon Sep 17 00:00:00 2001 From: Euraxluo Date: Sun, 18 May 2025 08:18:24 +0800 Subject: [PATCH 2/3] add agent-design doc --- agent-design.md | 1844 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1844 insertions(+) create mode 100644 agent-design.md diff --git a/agent-design.md b/agent-design.md new file mode 100644 index 00000000..58ba1ac1 --- /dev/null +++ b/agent-design.md @@ -0,0 +1,1844 @@ +# Agent API Detailed Design Document + +## Table of Contents + +1. [Introduction](#introduction) +2. [System Overview](#system-overview) +3. [Object Design](#object-design) +4. [API Architecture](#api-architecture) +5. [API Endpoints](#api-endpoints) + - [Agent Management](#agent-management) + - [Agent Lifecycle](#agent-lifecycle) + - [Task Execution](#task-execution) + - [Agent Monitoring](#agent-monitoring) + - [Memory Management](#memory-management) + - [Swarm Communication](#swarm-communication) + - [Abilities & Skills Management](#abilities--skills-management) + - [Bulk Operations](#bulk-operations) +6. [Schema Definitions](#schema-definitions) + - [Agent Related Schemas](#agent-related-schemas) + - [Task Related Schemas](#task-related-schemas) + - [Memory Related Schemas](#memory-related-schemas) + - [Monitoring Related Schemas](#monitoring-related-schemas) + - [Swarm Related Schemas](#swarm-related-schemas) + - [Abilities & Skills Related Schemas](#abilities--skills-related-schemas) + - [Error Related Schemas](#error-related-schemas) +7. [Best Practices](#best-practices) +8. [Implementation Considerations](#implementation-considerations) + +## Introduction + +This document describes the design and implementation of the Agent System, a flexible framework for creating, managing, and deploying autonomous agents for various tasks. The system provides a comprehensive REST API for agent lifecycle management, configuration, monitoring, and inter-agent communication, with implementation built on Julia programming language. + +The Agent System is designed to support the creation and management of different types of autonomous agents that can perform various tasks such as trading, monitoring, data collection, and notifications. The system allows users to create agents with specific capabilities, configure their behavior, and monitor their performance. + +### Key Features + +The Agent System includes the following key features: + +- Agent lifecycle management (create, start, pause, resume, stop, delete) +- Agent configuration and customization +- Agent monitoring and health checks +- Inter-agent communication via a swarm mechanism +- Agent memory management +- Extensible agent abilities and skills +- Task execution through abilities and skills +- LLM integration for AI-powered capabilities + +## System Overview + +The Agent System is designed to support the creation and management of different types of autonomous agents that can perform various tasks. The architecture is structured around several key concepts: + +1. **Agents**: Core entities that represent autonomous components capable of performing tasks. +2. **Abilities**: Functional capabilities that agents can perform. +3. **Skills**: Specialized functions that can be scheduled for automatic execution. +4. **Tasks**: Units of work that agents execute. +5. **Memory**: Key-value store for persisting agent state. +6. **Swarm**: Communication mechanism between agents. + +The system is built with flexibility, scalability, and extensibility in mind. It can be integrated with various backend services and supports multiple communication protocols for inter-agent communication. + +## Object Design + +### Core Objects + +The Agent System is built around several core object types: + +#### Agent + +The central entity representing an autonomous component capable of performing tasks. + +**Properties:** +- `id`: Unique identifier +- `name`: Human-readable name +- `type`: Type of agent (TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM) +- `status`: Current status (CREATED, INITIALIZING, RUNNING, PAUSED, STOPPED, ERROR) +- `version`: Agent version +- `description`: Descriptive text +- `created_at`: Creation timestamp +- `last_active`: Last activity timestamp +- `capabilities`: List of agent capabilities +- `metrics`: Performance metrics + +#### AgentConfig + +Configuration parameters for creating or updating an agent. + +**Properties:** +- `name`: Agent name +- `type`: Agent type +- `description`: Description of the agent's function +- `abilities`: List of enabled abilities +- `chains`: Supported blockchain networks +- `llm_config`: LLM configuration (for AI-powered agents) +- `memory_config`: Memory configuration +- `parameters`: Custom parameters for agent behavior +- `max_task_history`: Maximum number of tasks to keep in history +- `metadata`: User-defined metadata + +#### Task + +A unit of work that an agent can execute. + +**Properties:** +- `task_id`: Unique identifier +- `agent_id`: The agent executing the task +- `task_type`: Type of task +- `status`: Task status (PENDING, RUNNING, COMPLETED, FAILED, CANCELLED) +- `created_at`: Creation timestamp +- `started_at`: Start timestamp +- `completed_at`: Completion timestamp +- `progress_percent`: Completion percentage +- `error`: Error message (if failed) +- `priority`: Task priority level +- `timeout_seconds`: Task timeout +- `input_summary`: Summary of task input + +### Additional Components + +#### AgentAbility + +A functional capability that agents can perform. + +**Properties:** +- `name`: Ability name +- `function`: Function code that implements the ability +- `description`: Description of what the ability does + +#### AgentSkill + +A specialized function that can be scheduled for automatic execution. + +**Properties:** +- `name`: Skill name +- `function`: Function code that implements the skill +- `schedule`: Execution frequency in seconds (0 for on-demand only) +- `description`: Description of what the skill does + +#### AgentMemory + +Key-value store for persisting agent state. + +### UML Class Diagram + +```mermaid +classDiagram + class Agent { + +String id + +String name + +AgentType type + +AgentStatus status + +String version + +String description + +DateTime created_at + +DateTime last_active + +String[] capabilities + +Object metrics + } + + class AgentConfig { + +String name + +AgentType type + +String description + +String[] abilities + +String[] chains + +Object llm_config + +Object memory_config + +Object parameters + +Integer max_task_history + +Object metadata + } + + class Task { + +String task_id + +String agent_id + +String task_type + +String status + +DateTime created_at + +DateTime started_at + +DateTime completed_at + +Float progress_percent + +String error + +Integer priority + +Integer timeout_seconds + +String input_summary + } + + class AgentMemory { + +KeyValueStorage storage + } + + class AgentAbility { + +String name + +Function function + +String description + } + + class AgentSkill { + +String name + +Function function + +Number schedule + +String description + } + + Agent "1" -- "1" AgentConfig : configured by + Agent "1" -- "1" AgentMemory : stores state in + Agent "1" -- "*" Task : executes + Agent "1" -- "*" AgentAbility : has + Agent "1" -- "*" AgentSkill : has + Task --> AgentAbility : uses + AgentSkill --> AgentAbility : may use +``` + +## API Architecture + +The Agent System API follows REST principles and is organized around resource-oriented URLs. The API uses standard HTTP methods to perform actions on resources: + +- **GET**: Retrieve resources +- **POST**: Create new resources or trigger actions +- **PUT**: Update existing resources +- **DELETE**: Remove resources + +All API responses are in JSON format, with appropriate HTTP status codes to indicate success or failure. Authentication and authorization mechanisms are implemented to ensure secure access to the API. + +### Key Resources + +| API Path | HTTP Method | Description | Implementation in AgentHandlers.jl | +|----------|-------------|-------------|-----------------------------------| +| `/agents` | `GET` | List all agents | ✅ `list_agents_handler` | +| `/agents` | `POST` | Create a new agent | ✅ `create_agent_handler` | +| `/agents/{agent_id}` | `GET` | Get agent status | ✅ `get_agent_status_handler` | +| `/agents/{agent_id}` | `PUT` | Update agent configuration | ✅ `update_agent_handler` | +| `/agents/{agent_id}` | `DELETE` | Delete an agent | ✅ `delete_agent_handler` | +| `/agents/{agent_id}/start` | `POST` | Start agent lifecycle | ✅ `start_agent_handler` | +| `/agents/{agent_id}/stop` | `POST` | Stop agent | ✅ `stop_agent_handler` | +| `/agents/{agent_id}/pause` | `POST` | Pause agent | ✅ `pause_agent_handler` | +| `/agents/{agent_id}/resume` | `POST` | Resume agent | ✅ `resume_agent_handler` | +| `/agents/{agent_id}/execute` | `POST` | Execute agent task | ✅ `execute_agent_task_handler` | +| `/agents/{agent_id}/memory` | `GET` | Get agent memory | ✅ `get_agent_memory_handler` | +| `/agents/{agent_id}/memory` | `PUT` | Update agent memory | ✅ `set_agent_memory_handler` | +| `/agents/{agent_id}/memory` | `DELETE` | Clear agent memory | ✅ `clear_agent_memory_handler` | +| `/agents/{agent_id}/metrics` | `GET` | Get agent performance metrics | ❓ Not explicitly found | +| `/agents/{agent_id}/health` | `GET` | Get agent health status | ❓ Not explicitly found | +| `/agents/monitor/start` | `POST` | Start system monitoring | ❓ Not explicitly found | +| `/agents/monitor/stop` | `POST` | Stop system monitoring | ❓ Not explicitly found | +| `/agents/{agent_id}/swarm/publish` | `POST` | Publish message to swarm | ❓ Not explicitly found | +| `/agents/{agent_id}/swarm/subscribe` | `POST` | Subscribe to swarm topic | ❓ Not explicitly found | +| `/agents/{agent_id}/swarm/unsubscribe` | `POST` | Unsubscribe from swarm topic | ❓ Not explicitly found | +| `/agents/{agent_id}/swarm/connect` | `POST` | Connect to swarm | ❓ Not explicitly found | +| `/agents/{agent_id}/swarm/disconnect` | `POST` | Disconnect from swarm | ❓ Not explicitly found | +| `/agents/{agent_id}/abilities` | `POST` | Register agent abilities | ❓ Not explicitly found | +| `/agents/{agent_id}/skills` | `POST` | Register agent skills | ❓ Not explicitly found | +| `/agents/{agent_id}/clone` | `POST` | Clone an agent | ✅ `clone_agent_handler` | +| `/agents/bulk-delete` | `POST` | Batch delete agents | ✅ `bulk_delete_agents_handler` | + +*Note: Additional implemented endpoints in AgentHandlers.jl not mentioned in API spec:* +- `/agents/{agent_id}/tasks` - `GET` - `list_agent_tasks_handler` +- `/agents/{agent_id}/tasks/{task_id}` - `GET` - `get_task_status_handler` +- `/agents/{agent_id}/tasks/{task_id}/result` - `GET` - `get_task_result_handler` +- `/agents/{agent_id}/tasks/{task_id}/cancel` - `POST` - `cancel_task_handler` +- `/agents/{agent_id}/evaluate_fitness` - `POST` - `evaluate_agent_fitness_handler` + +## API Endpoints + +This section details the various API endpoints provided by the Agent System and their functionalities. + +### Agent Management + +#### List Agents (GET /agents) + +This endpoint lists all agents registered in the system, supporting various filtering conditions and pagination. + +**Request Parameters:** +- `type` (query parameter): Filter by agent type (TRADING, MONITOR, etc.) +- `status` (query parameter): Filter by agent status (CREATED, RUNNING, etc.) +- `name` (query parameter): Filter by agent name keyword (fuzzy matching) +- `order_by` (query parameter): Sort field (created_at, name, type, status) +- `order_direction` (query parameter): Sort direction (asc, desc) +- `limit` (query parameter): Page size (default 20) +- `offset` (query parameter): Pagination start position (default 0) + +**Functionality:** +- Supports filtering by type, status, and name +- Supports sorting by multiple fields +- Supports pagination for handling large data sets +- Returns list of basic agent information + +**Response:** +- On success, returns agent list and pagination information +- `200 OK`: Operation successful +- `400 Bad Request`: Request parameter error + +#### Create Agent (POST /agents) + +This endpoint creates a new agent and initializes its configuration, with the agent starting in CREATED state. + +**Request Body:** +- `name` (required): Agent name +- `type` (required): Agent type +- `description`: Agent description +- `abilities`: List of abilities +- `chains`: Supported blockchain networks +- `llm_config`: LLM configuration +- `memory_config`: Memory configuration +- `parameters`: Custom parameters +- `max_task_history`: Maximum number of task history records + +**Functionality:** +- Initializes a new agent instance +- Sets basic configuration and abilities +- Assigns a unique identifier +- Prepares the agent execution environment + +**Response:** +- `201 Created`: Agent created successfully +- `400 Bad Request`: Request data validation failed +- `409 Conflict`: Name conflict + +#### Get Agent Status (GET /agents/{agent_id}) + +This endpoint retrieves detailed status information for a specific agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Functionality:** +- Returns basic agent information (ID, name, type, etc.) +- Provides current running status information +- Displays recent task execution status +- Includes performance metrics information +- Shows configuration information +- Displays last activity time +- Provides error information if any + +**Response:** +- `200 OK`: Successfully returned agent status +- `404 Not Found`: Agent not found + +#### Update Agent (PUT /agents/{agent_id}) + +This endpoint updates the configuration of an existing agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `name`: New agent name +- `description`: New function description +- `abilities`: Updated list of abilities +- `model_config`: Updated model configuration +- `parameters`: Updated parameter configuration +- `metadata`: Updated metadata + +**Functionality:** +- Supports modifying agent name and description +- Allows updating agent abilities list +- Supports adjusting model configuration +- Can modify custom parameters +- Allows updating metadata +- Some core configurations (such as agent type) cannot be changed after creation + +**Response:** +- `200 OK`: Agent updated successfully +- `400 Bad Request`: Request data validation failed +- `404 Not Found`: Agent not found + +#### Delete Agent (DELETE /agents/{agent_id}) + +This endpoint deletes the specified agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Functionality:** +- Stops all executing tasks +- Clears the agent's memory state +- Removes the agent's configuration information +- Disconnects from the swarm +- Delete operation is irreversible, please use with caution + +**Response:** +- `200 OK`: Agent deleted successfully +- `404 Not Found`: Agent not found +- `409 Conflict`: Conflict, unable to delete (e.g., agent is executing important tasks) + +### Agent Lifecycle + +#### Starting an Agent (POST /agents/{agent_id}/start) + +This endpoint is used to start a specified agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Initializes the running environment of the agent +- Loads configuration and abilities +- Restores memory state (if any) +- Connects to necessary external services +- Starts executing predefined tasks + +**Response:** +- `200 OK`: Agent started successfully +- `404 Not Found`: Agent not found +- `409 Conflict`: Status conflict (e.g., agent is already running) + +#### Stopping an Agent (POST /agents/{agent_id}/stop) + +This endpoint is used to stop a specified agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Safely terminates the currently executing task +- Saves current state +- Disconnects from external services +- Releases resources +- Stopping operation preserves the configuration and state of the agent, allowing it to be restarted at any time + +**Response:** +- `200 OK`: Agent stopped successfully +- `404 Not Found`: Agent not found +- `409 Conflict`: Status conflict (e.g., agent is already stopped) + +#### Pausing an Agent (POST /agents/{agent_id}/pause) + +This endpoint is used to pause the execution of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Stops accepting new tasks +- Maintains existing connections +- Preserves memory state +- Can be quickly resumed +- Pausing operation is suitable for temporary interruptions in agent activity + +**Response:** +- `200 OK`: Agent paused successfully +- `404 Not Found`: Agent not found +- `409 Conflict`: Status conflict (e.g., agent is not running) + +#### Resuming an Agent (POST /agents/{agent_id}/resume) + +This endpoint is used to resume a paused agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Starts accepting tasks again +- Checks and restores previous working state +- Continues executing periodic tasks +- Reactivates all abilities + +**Response:** +- `200 OK`: Agent resumed successfully +- `404 Not Found`: Agent not found +- `409 Conflict`: Status conflict (e.g., agent is not in pause state) + +### Task Execution + +#### Executing Agent Task (POST /agents/{agent_id}/execute) + +This endpoint is used to allow an agent to execute a specified task. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `ability` (required): Name of the ability to execute +- `mode`: Execution mode (direct direct execution or queue queue mode) +- `priority`: Task priority (only used in queue mode) +- Additional custom parameters can be added + +**Description:** +- Supports synchronous execution: waiting for the task to complete and returning the result +- Supports asynchronous execution: immediately returns the task ID, result via other API +- Supports scheduled execution: setting tasks to execute at specific times +- Supports conditional execution: setting trigger conditions +- Records detailed logs and performance metrics + +**Response:** +- `200 OK`: Task submission successful, returns execution result +- `202 Accepted`: Task accepted and queued, but not yet completed +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found +- `409 Conflict`: Agent unable to execute task (e.g., incorrect state) + +### Memory Management + +#### Getting Agent Memory (GET /agents/{agent_id}/memory) + +This endpoint is used to get the memory state of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Retrieves historical interaction records +- Retrieves learned knowledge +- Retrieves contextual information +- Retrieves temporary data +- Retrieves cached calculation results +- Can be used for analyzing agent behavior and debugging issues + +**Response:** +- `200 OK`: Successfully returns the memory state of the agent +- `404 Not Found`: Agent not found + +#### Updating Agent Memory (PUT /agents/{agent_id}/memory) + +This endpoint is used to update the memory state of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `key` (required): Memory key +- `value` (required): Memory value + +**Description:** +- Adds a new memory item +- Modifies existing memory +- Sets expiration time for memory +- Adjusts memory priority +- Note: Modifying memory may affect agent behavior, please proceed with caution + +**Response:** +- `200 OK`: Memory updated successfully +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found + +#### Clearing Agent Memory (DELETE /agents/{agent_id}/memory) + +This endpoint is used to clear the memory state of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Deletes all historical records +- Resets learning state +- Clears contextual information +- Deletes cached data +- Suitable for resetting the agent to its initial state + +**Response:** +- `200 OK`: Memory cleared successfully +- `404 Not Found`: Agent not found + +### Agent Monitoring + +#### Getting Agent Metrics (GET /agents/{agent_id}/metrics) + +This endpoint is used to get performance metrics data of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Query Parameters:** +- `timeframe`: Time range for metrics (e.g., 1h, 24h, 7d, etc.) + +**Description:** +- Statistics of task execution (success rate, average duration, etc.) +- Resource usage (CPU, memory, network, etc.) +- Counter for operations (number of API calls, number of event processing, etc.) +- Error statistics +- Custom metrics +- Supports specifying time range and aggregation method + +**Response:** +- `200 OK`: Successfully returns agent metrics +- `404 Not Found`: Agent not found + +#### Getting Agent Health Status (GET /agents/{agent_id}/health) + +This endpoint is used to get health status check results of an agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Core service status +- Necessary connection availability +- Level of resource usage +- Error rate monitoring +- Performance threshold checks +- Data consistency verification +- Used for monitoring the running state of the agent and detecting issues in a timely manner + +**Response:** +- `200 OK`: Successfully returns agent health status +- `404 Not Found`: Agent not found + +#### Starting Agent Monitoring System (POST /agents/monitor/start) + +This endpoint is used to start system-wide agent monitoring. + +**Description:** +- Collects performance metrics of all agents +- Monitors health status of agents +- Generates system-level statistics +- Triggers alerts (when anomalies are detected) +- Provides storage and querying of monitoring data +- Monitoring system has a slight impact on system performance + +**Response:** +- `200 OK`: Monitoring system started successfully +- `409 Conflict`: Monitoring system is already running + +#### Stopping Agent Monitoring System (POST /agents/monitor/stop) + +This endpoint is used to stop system-wide agent monitoring. + +**Description:** +- Terminates all monitoring tasks +- Saves current monitoring data +- Cleans up temporary resources +- Stops alert service +- Can be restarted at any time without losing historical data + +**Response:** +- `200 OK`: Monitoring system stopped successfully +- `409 Conflict`: Monitoring system is not running + +### Swarm Communication + +#### Publishing Message to Swarm (POST /agents/{agent_id}/swarm/publish) + +This endpoint is used to publish a message to Swarm. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `topic` (required): Topic +- `message` (required): Message content + +**Description:** +- Publishes to a specific topic +- Broadcasts to all subscribers +- Sets message priority +- Message persistence +- Message confirmation mechanism +- Swarm communication is used for agent collaboration and information sharing + +**Response:** +- `200 OK`: Message published successfully +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found +- `409 Conflict`: Agent not connected to Swarm + +#### Subscribing to Swarm Topic (POST /agents/{agent_id}/swarm/subscribe) + +This endpoint is used to subscribe to Swarm message topics. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `topic` (required): Topic + +**Description:** +- Subscribes to a specific topic +- Uses wildcards to subscribe to multiple topics +- Sets message filter +- Configures subscription options (QoS, etc.) +- Sets message processing callback +- After subscribing, the agent will receive all messages related to the topic + +**Response:** +- `200 OK`: Subscription successful +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found or topic not subscribed +- `409 Conflict`: Agent not connected to Swarm + +#### Unsubscribing from Swarm Topic (POST /agents/{agent_id}/swarm/unsubscribe) + +This endpoint is used to unsubscribe from Swarm message topics. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `topic` (required): Topic + +**Description:** +- Stops receiving messages from a specific topic +- Cleans up related subscription state +- Removes message processing callback +- Releases related resources +- Does not affect other topic subscriptions + +**Response:** +- `200 OK`: Unsubscription successful +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found or topic not subscribed +- `409 Conflict`: Agent not connected to Swarm + +#### Connecting to Swarm (POST /agents/{agent_id}/swarm/connect) + +This endpoint is used to connect the agent to Swarm backend. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `backend`: Swarm backend type (NONE, MEMORY, REDIS, NATS, ZEROMQ, default MEMORY) +- `connection_string`: Connection string + +**Description:** +- Establishes connection with Swarm server +- Authentication and authorization +- Restores previous subscription (if any) +- Initializes message queue +- Sets heartbeat detection +- After connection is established, the agent can start Swarm communication + +**Response:** +- `200 OK`: Connection successful +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found +- `409 Conflict`: Agent already connected to Swarm + +#### Disconnecting from Swarm (POST /agents/{agent_id}/swarm/disconnect) + +This endpoint is used to disconnect the agent from Swarm backend. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Description:** +- Cancels all topic subscriptions +- Closes message queue +- Saves necessary state +- Cleans up connection resources +- Stops heartbeat detection +- Disconnection can be reestablished at any time + +**Response:** +- `200 OK`: Disconnection successful +- `404 Not Found`: Agent not found +- `409 Conflict`: Agent not connected to Swarm + +### Abilities & Skills Management + +#### Registering Agent Abilities (POST /agents/{agent_id}/abilities) + +This endpoint is used to register new abilities for a specified agent. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `name` (required): Name of the ability +- `function` (required): Function code representing the ability +- `description`: Description of the ability + +**Description:** +- Adds new functional abilities to the agent +- Defines the behavior logic of the ability +- Provides descriptive information about the ability +- Abilities can be directly invoked through the execute endpoint + +**Response:** +- `200 OK`: Ability registered successfully +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found +- `409 Conflict`: Ability name conflict + +#### Registering Agent Skills (POST /agents/{agent_id}/skills) + +This endpoint is used to register new skills for a specified agent, with optional skill execution scheduling. + +**Path Parameters:** +- `agent_id`: Unique identifier of the agent + +**Request Body:** +- `name` (required): Name of the skill +- `function` (required): Function code representing the skill +- `schedule`: Skill execution scheduling interval (seconds), 0 means execute on demand +- `description`: Description of the skill + +**Description:** +- Skills are special functions that can be automatically executed by the scheduler +- Frequency of execution can be set +- Skills can utilize the abilities of the agent +- Skills have an experience system, making common skills have higher priority + +**Response:** +- `200 OK`: Skill registered successfully +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Agent not found +- `409 Conflict`: Skill name conflict + +### Bulk Operations + +#### Cloning an Agent (POST /agents/{agent_id}/clone) + +This endpoint is used to clone an existing agent, and some configuration parameters can be overridden. + +**Path Parameters:** +- `agent_id`: ID of the agent to clone + +**Request Body:** +- `new_name` (required): New name for the cloned agent +- `parameter_overrides`: Parameters to override, in key-value format + +**Description:** +- Creates a new instance based on the existing agent +- Preserves original configuration and abilities +- Allows selecting which parameters to override +- Allocates a new unique identifier + +**Response:** +- `201 Created`: Agent cloned successfully +- `400 Bad Request`: Failed data validation +- `404 Not Found`: Source agent not found +- `409 Conflict`: Name conflict + +#### Batch Deleting Agents (POST /agents/bulk-delete) + +This endpoint is used to batch delete multiple agents. + +**Request Body:** +- `agent_ids` (required): List of IDs of agents to delete + +**Description:** +- Batch processes deletion of multiple agents +- Provides detailed information about the deletion result for each agent +- Even if some deletions fail, processing continues for the remaining agents + +**Response:** +- `200 OK`: Batch deletion operation completed +- `400 Bad Request`: Failed data validation + +## Schema Definitions + +This section provides detailed descriptions of various data models (schemas) used in the API of the Agent system. + +### Agent Related Schemas + +#### AgentInfo + +Represents the data structure for basic information about an agent. + +**Attributes:** +- `id` (string, required): Unique identifier of the agent, e.g., "agent-123456" +- `name` (string, required): Name of the agent, e.g., "Market Data Analysis Agent" +- `type` (string, required): Type of the agent, enum values are [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] +- `status` (string, required): Current status of the agent, enum values are [CREATED, INITIALIZING, RUNNING, PAUSED, STOPPED, ERROR] +- `version` (string): Version number of the agent, e.g., "1.0.0" +- `description` (string): Description of the agent's functionality +- `created_at` (string, date-time format, required): Timestamp of creation +- `last_active` (string, date-time format): Timestamp of last activity +- `capabilities` (string array): List of supported abilities of the agent +- `metrics` (object): Performance metrics of the agent + - `task_count` (integer): Number of completed tasks + - `success_rate` (float, 0-1): Task success rate + - `avg_response_time` (float): Average response time (seconds) + +**Example:** +```json +{ + "id": "agent-123456", + "name": "Market Data Analysis Agent", + "type": "TRADING", + "status": "RUNNING", + "version": "1.0.0", + "description": "Agent that analyzes market data and generates trading signals", + "created_at": "2023-01-01T12:00:00Z", + "last_active": "2023-01-02T15:30:00Z", + "capabilities": ["MARKET_ANALYSIS", "SIGNAL_GENERATION"], + "metrics": { + "task_count": 42, + "success_rate": 0.95, + "avg_response_time": 1.25 + } +} +``` + +#### AgentConfig + +Used to create or configure data structures for agents. + +**Attributes:** +- `name` (string, required): Name of the agent +- `type` (string, required): Type of the agent, enum values are [TRADING, MONITOR, ARBITRAGE, DATA_COLLECTION, NOTIFICATION, CUSTOM] +- `description` (string): Description of the agent's functionality +- `abilities` (string array): List of abilities to enable +- `chains` (string array): Supported blockchain networks +- `llm_config` (object): LLM model configuration + - `provider` (string): LLM provider, e.g., "openai" + - `model_name` (string): Name of the model to use, e.g., "gpt-4o-mini" + - `temperature` (float, 0-1): Model temperature parameter + - `max_tokens` (integer): Maximum number of tokens generated +- `memory_config` (object): Memory configuration for the agent + - `max_size` (integer): Maximum number of items in memory + - `retention_policy` (string): Memory retention policy, enum values are [lru, fifo, lifo] +- `parameters` (object): Configuration for agent parameters, supports arbitrary attributes +- `max_task_history` (integer): Maximum number of historical records for tasks +- `metadata` (object): User-defined metadata, supports arbitrary attributes + +**Example:** +```json +{ + "name": "Market Data Analysis Agent", + "type": "TRADING", + "description": "Agent that analyzes market data and generates trading signals", + "abilities": ["MARKET_ANALYSIS", "SIGNAL_GENERATION"], + "chains": ["ethereum", "bitcoin"], + "llm_config": { + "provider": "openai", + "model_name": "gpt-4o-mini", + "temperature": 0.7, + "max_tokens": 1024 + }, + "memory_config": { + "max_size": 1000, + "retention_policy": "lru" + }, + "parameters": { + "analysis_depth": "STANDARD", + "update_frequency": 300, + "indicator_list": ["MA", "RSI", "MACD"] + }, + "max_task_history": 100, + "metadata": { + "team": "Trading", + "purpose": "Market Analysis", + "priority": "high" + } +} +``` + +#### AgentCreated + +Represents the response data structure after an agent is successfully created. + +**Attributes:** +- `id` (string, required): ID of the newly created agent +- `name` (string, required): Name of the agent +- `type` (string, required): Type of the agent +- `created_at` (string, date-time format, required): Timestamp of creation +- `message` (string): Success message + +**Example:** +```json +{ + "id": "agent-123456", + "name": "Market Data Analysis Agent", + "type": "TRADING", + "created_at": "2023-01-01T12:00:00Z", + "message": "Agent created successfully" +} +``` + +#### AgentStatus + +Represents the data structure for detailed status information of an agent. + +**Attributes:** +- `id` (string, required): Unique identifier of the agent +- `name` (string, required): Name of the agent +- `type` (string, required): Type of the agent +- `status` (string, required): Current status of the agent +- `current_task` (object): Current task being executed (if any) + - `id` (string): ID of the task + - `name` (string): Name of the task + - `progress` (float, 0-100): Percentage of completion + - `started_at` (string, date-time format): Timestamp of start +- `last_error` (object): Last error (if any) + - `timestamp` (string, date-time format): Timestamp of error occurrence + - `message` (string): Error message + - `code` (string): Error code +- `created_at` (string, date-time format, required): Timestamp of creation +- `last_active` (string, date-time format): Timestamp of last activity +- `metrics` (object): Performance metrics of the agent +- `configuration` (object): Current configuration of the agent + +**Example:** +```json +{ + "id": "agent-123456", + "name": "Market Data Analysis Agent", + "type": "TRADING", + "status": "RUNNING", + "current_task": { + "id": "task-789012", + "name": "Market Data Analysis", + "progress": 75, + "started_at": "2023-01-02T14:30:00Z" + }, + "last_error": { + "timestamp": "2023-01-02T13:45:00Z", + "message": "Unable to connect to data source", + "code": "CONNECTION_ERROR" + }, + "created_at": "2023-01-01T12:00:00Z", + "last_active": "2023-01-02T15:30:00Z", + "metrics": { + "task_count": 42, + "success_rate": 0.95, + "avg_response_time": 1.25 + }, + "configuration": { + "abilities": ["MARKET_ANALYSIS", "SIGNAL_GENERATION"], + "parameters": { + "analysis_depth": "STANDARD", + "update_frequency": 300 + }, + "model_config": { + "model_name": "gpt-4o-mini", + "temperature": 0.7 + } + } +} +``` + +#### AgentUpdate + +Used to update the configuration data structure for an agent. + +**Attributes:** +- `name` (string): New name of the agent +- `description` (string): New description of the functionality +- `abilities` (string array): Updated list of abilities +- `model_config` (object): Updated model configuration +- `parameters` (object): Updated configuration parameters +- `metadata` (object): Updated metadata + +**Example:** +```json +{ + "name": "Enhanced Market Analysis Agent", + "description": "Provides advanced market data analysis and trading signal generation", + "abilities": ["ADVANCED_MARKET_ANALYSIS", "SIGNAL_GENERATION"], + "model_config": { + "provider": "openai", + "model_name": "gpt-4o", + "temperature": 0.8, + "max_tokens": 4096 + }, + "parameters": { + "analysis_depth": "ADVANCED", + "update_frequency": 180, + "indicator_list": ["MA", "RSI", "MACD", "Bollinger", "Ichimoku"] + }, + "metadata": { + "team": "Advanced Trading", + "purpose": "Advanced Market Analysis", + "priority": "critical" + } +} +``` + +#### AgentListResponse + +Represents the data structure for agent list responses. + +**Attributes:** +- `agents` (AgentInfo array): List of agent information +- `pagination` (object): Pagination information + - `total` (integer): Total number of records + - `limit` (integer): Number of records per page + - `offset` (integer): Offset + - `next_offset` (integer): Next page offset (if there is a next page) + +**Example:** +```json +{ + "agents": [ + { + "id": "agent-123456", + "name": "Market Data Analysis Agent", + "type": "TRADING", + "status": "RUNNING", + "created_at": "2023-01-01T12:00:00Z" + }, + { + "id": "agent-789012", + "name": "Notification Agent", + "type": "NOTIFICATION", + "status": "PAUSED", + "created_at": "2023-01-02T14:00:00Z" + } + ], + "pagination": { + "total": 42, + "limit": 20, + "offset": 0, + "next_offset": 20 + } +} +``` + +#### AgentDeleteResponse + +Represents the data structure for agent deletion responses. + +**Attributes:** +- `message` (string): Success message +- `agent_id` (string): ID of the deleted agent + +**Example:** +```json +{ + "message": "Agent deleted successfully", + "agent_id": "agent-123456" +} +``` + +#### AgentLifecycleResponse + +Represents the data structure for agent lifecycle operations (start, stop, pause, resume) responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `status` (string): New status of the agent +- `message` (string): Success message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "status": "RUNNING", + "message": "Agent started successfully" +} +``` + +### Task Related Schemas + +#### TaskRequest + +Represents the data structure for task requests. + +**Attributes:** +- `task_type` (string, required): Type of the task +- `input` (object, required): Task input data, supports arbitrary attributes +- `priority` (integer, 1-10): Task priority, 10 is highest, default 5 +- `timeout_seconds` (integer): Task timeout (seconds), default 300 +- `callback_url` (string): Callback URL after task completion + +**Example:** +```json +{ + "task_type": "price_analysis", + "input": { + "symbol": "BTC/USD", + "timeframe": "1h", + "indicators": ["MA", "RSI"] + }, + "priority": 7, + "timeout_seconds": 120, + "callback_url": "https://example.com/webhook/task-complete" +} +``` + +#### TaskSubmitted + +Represents the response data structure for a task that has been submitted. + +**Attributes:** +- `task_id` (string): ID of the task +- `agent_id` (string): ID of the agent +- `status` (string): Status of the task +- `estimated_completion` (string, date-time format): Estimated completion time +- `priority` (integer): Task priority +- `task_type` (string): Type of the task + +**Example:** +```json +{ + "task_id": "task-789012", + "agent_id": "agent-123456", + "status": "PENDING", + "estimated_completion": "2023-07-10T15:35:45Z", + "priority": 7, + "task_type": "price_analysis" +} +``` + +#### TaskInfo + +Represents the data structure for detailed information about a task. + +**Attributes:** +- `task_id` (string): ID of the task +- `agent_id` (string): ID of the agent +- `task_type` (string): Type of the task +- `status` (string): Status of the task, enum values are [PENDING, RUNNING, COMPLETED, FAILED, CANCELLED] +- `created_at` (string, date-time format): Timestamp of creation +- `started_at` (string, date-time format): Timestamp of start +- `completed_at` (string, date-time format): Timestamp of completion +- `progress_percent` (float, 0-100): Percentage of completion +- `error` (string): Error message if failed +- `priority` (integer, 1-10): Task priority +- `timeout_seconds` (integer): Task timeout (seconds) +- `input_summary` (string): Summary of task input + +**Example:** +```json +{ + "task_id": "task-789012", + "agent_id": "agent-123456", + "task_type": "price_analysis", + "status": "RUNNING", + "created_at": "2023-07-10T15:30:45Z", + "started_at": "2023-07-10T15:31:00Z", + "completed_at": null, + "progress_percent": 75, + "error": null, + "priority": 7, + "timeout_seconds": 120, + "input_summary": "Analysis for BTC/USD pair over 1h period" +} +``` + +#### AgentTaskRequest + +Represents the data structure for agent task execution requests. + +**Attributes:** +- `ability` (string, required): Name of the ability to execute +- `mode` (string): Execution mode (direct direct execution or queue queue mode), default "direct" +- `priority` (float): Task priority (only used in queue mode), default 0 +- Supports arbitrary additional attributes as parameters to be passed to the ability + +**Example:** +```json +{ + "ability": "ping", + "mode": "direct", + "priority": 5, + "param1": "value1", + "param2": 42 +} +``` + +#### AgentTaskResponse + +Represents the data structure for agent task execution responses. + +**Attributes:** +- `success` (boolean): Whether the task execution was successful +- `queued` (boolean): Whether the task is queued +- `agent_id` (string): ID of the agent +- `result` (object): Execution result of the task, supports arbitrary attributes + +**Example:** +```json +{ + "success": true, + "queued": false, + "agent_id": "agent-123456", + "result": { + "msg": "pong", + "agent_id": "agent-123456", + "agent_name": "Test Agent" + } +} +``` + +### Memory Related Schemas + +#### AgentMemoryRequest + +Represents the data structure for agent memory operations requests. + +**Attributes:** +- `key` (string, required): Memory key +- `value` (any type, required): Memory value + +**Example:** +```json +{ + "key": "last_greeting", + "value": "Hello!" +} +``` + +#### AgentMemoryResponse + +Represents the data structure for agent memory operations responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `memory` (object): Memory content, in key-value format + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "memory": { + "last_greeting": "Hello!", + "counter": 42, + "last_market_check": "2023-07-10T15:30:00Z" + } +} +``` + +#### AgentMemoryClearResponse + +Represents the data structure for agent memory clear operations responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `message` (string): Success message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "message": "Agent memory cleared" +} +``` + +### Monitoring Related Schemas + +#### AgentMetricsResponse + +Represents the data structure for agent metrics responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `data` (object): Metrics data + - Various metric names as keys + - Each metric contains: + - `current` (number): Current value + - `type` (string): Metric type (e.g., "GAUGE") + - `history` (array): Historical records, each item is [timestamp, value] pair + - `last_updated` (string, date-time format): Last update time + +**Example:** +```json +{ + "success": true, + "data": { + "task_count": { + "current": 42, + "type": "GAUGE", + "history": [ + ["2023-10-12T15:30:00Z", 41], + ["2023-10-12T15:31:00Z", 42] + ], + "last_updated": "2023-10-12T15:31:00Z" + }, + "response_time_ms": { + "current": 250, + "type": "GAUGE", + "history": [ + ["2023-10-12T15:30:00Z", 275], + ["2023-10-12T15:31:00Z", 250] + ], + "last_updated": "2023-10-12T15:31:00Z" + } + } +} +``` + +#### AgentHealthStatus + +Represents the data structure for agent health status. + +**Attributes:** +- `agent_id` (string): ID of the agent +- `status` (string): Health status, enum values are [HEALTHY, WARNING, CRITICAL, UNKNOWN] +- `message` (string): Status description +- `timestamp` (string, date-time format): Check time +- `details` (object): Detailed information, supports arbitrary attributes + +**Example:** +```json +{ + "agent_id": "agent-123456", + "status": "HEALTHY", + "message": "Agent running in good condition", + "timestamp": "2023-10-12T15:31:00Z", + "details": { + "memory_usage_percent": 45, + "cpu_usage_percent": 22, + "event_backlog": 0, + "response_time_ms": 250 + } +} +``` + +#### AgentHealthResponse + +Represents the data structure for agent health check responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `status` (string): Health status +- `message` (string): Status message +- `timestamp` (string, date-time format): Check time +- `details` (object): Detailed information, supports arbitrary attributes + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "status": "HEALTHY", + "message": "Agent running in good condition", + "timestamp": "2023-10-12T15:31:00Z", + "details": { + "memory_usage_percent": 45, + "cpu_usage_percent": 22, + "event_backlog": 0, + "response_time_ms": 250 + } +} +``` + +#### MonitorResponse + +Represents the data structure for agent monitoring system operations responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `message` (string): Operation message + +**Example:** +```json +{ + "success": true, + "message": "Agent monitoring system started" +} +``` + +### Swarm Related Schemas + +#### SwarmPublishRequest + +Represents the data structure for publishing messages to Swarm requests. + +**Attributes:** +- `topic` (string, required): Topic +- `message` (object, required): Message content, supports arbitrary attributes + +**Example:** +```json +{ + "topic": "market.update", + "message": { + "type": "price_update", + "symbol": "BTC/USD", + "price": 45000.25, + "timestamp": "2023-10-12T15:30:00Z" + } +} +``` + +#### SwarmSubscribeRequest + +Represents the data structure for subscribing to Swarm topic requests. + +**Attributes:** +- `topic` (string, required): Topic + +**Example:** +```json +{ + "topic": "market.update" +} +``` + +#### AgentSwarmOperationResponse + +Represents the data structure for Swarm operations responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `topic` (string): Topic + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "topic": "market.update" +} +``` + +#### SwarmConnectRequest + +Represents the data structure for connecting to Swarm requests. + +**Attributes:** +- `backend` (string): Swarm backend type, enum values are [NONE, MEMORY, REDIS, NATS, ZEROMQ], default "MEMORY" +- `connection_string`: Connection string + +**Example:** +```json +{ + "backend": "REDIS", + "connection_string": "redis://localhost:6379" +} +``` + +#### SwarmConnectResponse + +Represents the data structure for connecting to Swarm responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `backend` (string): Backend type +- `message` (string): Operation message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "backend": "REDIS", + "message": "Agent connected to swarm backend" +} +``` + +#### SwarmDisconnectResponse + +Represents the data structure for disconnecting from Swarm responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `message` (string): Operation message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "message": "Agent disconnected from swarm backend" +} +``` + +### Abilities & Skills Related Schemas + +#### AgentAbilityRequest + +Represents the data structure for registering agent abilities requests. + +**Attributes:** +- `name` (string, required): Name of the ability +- `function` (string, required): Function code representing the ability +- `description`: Description of the ability + +**Example:** +```json +{ + "name": "analyze_market", + "function": "function(agent, params) { return {result: 'Market analyzed'}; }", + "description": "Analyze market status and generate report" +} +``` + +#### AgentAbilityResponse + +Represents the data structure for registering agent abilities responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `ability_name` (string): Name of the ability +- `message` (string): Operation message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "ability_name": "analyze_market", + "message": "Ability registered successfully" +} +``` + +#### AgentSkillRequest + +Represents the data structure for registering agent skills requests. + +**Attributes:** +- `name` (string, required): Name of the skill +- `function` (string, required): Function code representing the skill +- `schedule` (number): Skill execution scheduling interval (seconds), 0 means execute on demand +- `description`: Description of the skill + +**Example:** +```json +{ + "name": "monitor_prices", + "function": "function(agent) { return {monitored: true}; }", + "schedule": 60, + "description": "Regularly monitor price changes" +} +``` + +#### AgentSkillResponse + +Represents the data structure for registering agent skills responses. + +**Attributes:** +- `success` (boolean): Whether the operation was successful +- `agent_id` (string): ID of the agent +- `skill_name` (string): Name of the skill +- `schedule` (number): Execution scheduling interval +- `message` (string): Operation message + +**Example:** +```json +{ + "success": true, + "agent_id": "agent-123456", + "skill_name": "monitor_prices", + "schedule": 60, + "message": "Skill registered successfully" +} +``` + +### Error Related Schemas + +#### ErrorResponse + +Represents the data structure for generic error responses. + +**Attributes:** +- `error` (string): Error message + +**Example:** +```json +{ + "error": "An unexpected error occurred" +} +``` + +#### InvalidRequestError + +Represents the data structure for invalid request errors. + +**Attributes:** +- `error` (string): Error message + +**Example:** +```json +{ + "error": "Invalid request format" +} +``` + +#### AgentNotFoundError + +Represents the data structure for agent not found errors. + +**Attributes:** +- `error` (string): Error message + +**Example:** +```json +{ + "error": "Agent not found" +} +``` + +#### AgentConflictError + +Represents the data structure for agent conflict errors. + +**Attributes:** +- `error` (string): Error message + +**Example:** +```json +{ + "error": "Agent with this name already exists" +} +``` + +#### AgentStateConflictError + +Represents the data structure for agent state conflict errors. + +**Attributes:** +- `error` (string): Error message + +**Example:** +```json +{ + "error": "Agent is already running" +} +``` + +## Best Practices + +### API Usage Recommendations + +```mermaid +flowchart TD + A[Best Practices] --> B[API Usage] + A --> C[Agent Configuration] + A --> D[Performance Considerations] + A --> E[Security Recommendations] + + B --> B1[Status Verification] + B1 --> B1a[Always check agent status\nbefore operations] + + B --> B2[Error Handling] + B2 --> B2a[400: Invalid request] + B2 --> B2b[404: Resource not found] + B2 --> B2c[409: Conflict] + B2 --> B2d[500: Internal error] + + B --> B3[Batch Operations] + B3 --> B3a[Use batch endpoints\nover individual calls] + + B --> B4[Pagination] + B4 --> B4a[Use for large datasets] + + B --> B5[Timeout Settings] + B5 --> B5a[Set appropriate timeouts\nfor long-running tasks] + + B --> B6[Task Priorities] + B6 --> B6a[Set based on\nurgency and importance] + + B --> B7[Regular Monitoring] + B7 --> B7a[Check health status\nand metrics regularly] + + C --> C1[Agent Naming] + C1 --> C1a[Use clear, descriptive names] + + C --> C2[Ability Allocation] + C2 --> C2a[Only allocate\nneeded abilities] + + C --> C3[Memory Configuration] + C3 --> C3a[Configure based on\nactual needs] + + C --> C4[Skill Scheduling] + C4 --> C4a[Set reasonable\nexecution frequency] + + C --> C5[Parameter Tuning] + C5 --> C5a[Optimize for\nspecific scenarios] + + C --> C6[Metadata Usage] + C6 --> C6a[Store additional info\nfor management] + + D --> D1[Task Queue Management] + D1 --> D1a[Monitor queue length\nin high-load systems] + + D --> D2[Swarm Communication] + D2 --> D2a[Choose appropriate backend\nfor large deployments] + + D --> D3[Monitoring Control] + D3 --> D3a[Control granularity\nto avoid overhead] + + D --> D4[Lifecycle Management] + D4 --> D4a[Stop/delete unused agents\nto free resources] + + D --> D5[Caching Strategy] + D5 --> D5a[Cache frequently accessed\nrarely changed data] + + E --> E1[API Authentication] + E1 --> E1a[Use API keys, OAuth, or JWT] + + E --> E2[Access Control] + E2 --> E2a[Implement fine-grained\npermissions] + + E --> E3[Sensitive Data] + E3 --> E3a[Avoid storing sensitive\ninfo in plaintext] + + E --> E4[Input Validation] + E4 --> E4a[Validate all inputs to\nprevent vulnerabilities] + + E --> E5[Audit Logging] + E5 --> E5a[Log critical operations\nfor traceability] +``` + +### Agent Lifecycle Management + +```mermaid +stateDiagram-v2 + [*] --> CREATED: createAgent() + CREATED --> INITIALIZING: startAgent() + INITIALIZING --> RUNNING + RUNNING --> PAUSED: pauseAgent() + PAUSED --> RUNNING: resumeAgent() + RUNNING --> STOPPED: stopAgent() + PAUSED --> STOPPED: stopAgent() + STOPPED --> INITIALIZING: startAgent() + + CREATED --> [*]: deleteAgent() + STOPPED --> [*]: deleteAgent() + + RUNNING --> ERROR: error occurs + INITIALIZING --> ERROR: error occurs + ERROR --> STOPPED: stopAgent() + + note right of CREATED: Agent exists but not started + note right of INITIALIZING: Loading config & connecting services + note right of RUNNING: Executing tasks & processing events + note right of PAUSED: Not accepting new tasks + note right of STOPPED: Resources released but config preserved + note right of ERROR: Exception state requiring intervention +``` + +### Task Execution Flow + +```mermaid +sequenceDiagram + participant Client + participant API as API Endpoint + participant Agent as Agent System + participant Queue as Task Queue + participant Executor as Task Executor + + Client->>API: POST /agents/{id}/execute + API->>Agent: executeAgentTask(id, payload) + + alt Direct Execution + Agent->>Executor: Execute task immediately + Executor-->>Agent: Task result + Agent-->>API: Return result (200 OK) + API-->>Client: Task result + else Queue Execution + Agent->>Queue: Add task to queue + Queue-->>Agent: Task queued confirmation + Agent-->>API: Task accepted (202 Accepted) + API-->>Client: Task ID for tracking + + Note over Queue,Executor: Asynchronous processing + Queue->>Executor: Process next task + Executor-->>Queue: Task completed + end +``` \ No newline at end of file From d7dddeb8b16f27cc963267d200c60f5e8b550e88 Mon Sep 17 00:00:00 2001 From: Euraxluo Date: Sun, 18 May 2025 08:21:04 +0800 Subject: [PATCH 3/3] remove table ic --- agent-design.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/agent-design.md b/agent-design.md index 58ba1ac1..aa3a0352 100644 --- a/agent-design.md +++ b/agent-design.md @@ -23,8 +23,7 @@ - [Swarm Related Schemas](#swarm-related-schemas) - [Abilities & Skills Related Schemas](#abilities--skills-related-schemas) - [Error Related Schemas](#error-related-schemas) -7. [Best Practices](#best-practices) -8. [Implementation Considerations](#implementation-considerations) +7. [Best Practices](#best-practices) ## Introduction