Agents

Agents are intelligent, autonomous components that form the core of the Fiberwise platform. They process input data, execute business logic, and integrate with external services using advanced dependency injection and activation patterns.

What are Agents?

Fiberwiseagents are Python classes that inherit from the FiberAgent base class, providing a powerful foundation for building AI-powered applications. They combine dependency injection, schema validation, and lifecycle management into a cohesive development experience.

Agent Architecture Flow

๐Ÿ”
Detection
Activation processor scans agent files
โ†’
โšก
Instantiation
Agent class created with config
โ†’
๐Ÿ’‰
Injection
Services injected via signatures
โ†’
๐Ÿš€
Execution
Agent processes input data

Core Agent Capabilities:

  • Advanced Dependency Injection: Automatic service injection based on method signatures and type hints
  • Schema Validation: Pydantic models for input/output validation and documentation
  • Activation Processor: Sophisticated execution engine with pattern detection and lifecycle management
  • Multi-Pattern Support: Function-based, class-based, and async execution patterns
  • Service Integration: Built-in access to LLM providers, storage, OAuth, and platform services
  • Error Handling: Comprehensive error tracking and graceful degradation
  • Performance Monitoring: Real-time execution metrics and logging
  • Multi-language SDKs: Python and Node.js support with unified API

Agent Development Patterns

Fiberwisesupports multiple agent development patterns to accommodate different use cases and complexity levels.

1. Function-Based Agent (Simple)

Perfect for simple data processing tasks with minimal dependencies.

async def run_agent(input_data, fiber, llm_service):
    """Simple function-based agent with automatic dependency injection"""
    # Process input data
    response = await llm_service.generate(
        prompt=input_data.get('message', ''),
        max_tokens=150
    )
    
    return {
        "status": "success",
        "response": response.text,
        "model_used": response.model
    }

Dependency Injection System

Fiberwisefeatures a sophisticated dependency injection system that automatically provides agents with required services based on method signatures and declared dependencies.

๐Ÿ” Automatic Detection

The activation processor scans agent methods and automatically injects services based on parameter names and type hints.

๐Ÿท๏ธ Type Hint Resolution

Services are automatically injected based on type hints and parameter names, eliminating manual configuration.

๐Ÿ”Œ Service Registry

Services are managed through a centralized registry with lifecycle management and configuration.

โšก Performance Optimized

Service instances are cached and reused across agent activations for optimal performance.

Available Services

LLMProviderService Access to configured LLM providers (OpenAI, Anthropic, etc.)
StorageService Multi-cloud storage with unified API
OAuthService OAuth integration for external services
FiberApp Platform SDK for accessing activations, agents, and platform features
DatabaseService Direct database access for complex queries

Dependency Injection Patterns

๐ŸŽฏ Pattern 1: Parameter Name Matching

The activation processor automatically matches parameter names to registered services:

def run_agent(self, input_data, llm_service, storage_service):
    # Services automatically injected based on parameter names:
    # - llm_service โ†’ LLMProviderService
    # - storage_service โ†’ StorageService
    # - fiber โ†’ FiberApp SDK instance
    pass
๐Ÿท๏ธ Pattern 2: Type Hint Resolution

Use type hints for precise service injection and better IDE support:

from fiberwise_sdk.services import LLMProviderService, StorageService

class DocumentProcessor(FiberAgent):
    def run_agent(self, 
                  input_data: dict, 
                  llm_service: LLMProviderService, 
                  storage_service: StorageService):
        # Services injected based on type hints
        # Provides autocomplete and type checking
        pass
๐Ÿ”Œ Pattern 3: Service Variable Declaration

Declare services as class variables with type hints for explicit dependencies:

class ContentAnalyzer(FiberAgent):
    # Explicit service declarations
    llm_service: LLMProviderService
    storage_service: StorageService
    oauth_service: OAuthService
    
    def run_agent(self, input_data: dict):
        # Services available as self.llm_service, etc.
        analysis = self.llm_service.analyze(input_data['text'])
        self.storage_service.save_analysis(analysis)
        return analysis
โšก Pattern 4: Dynamic Service Resolution

Access any registered service dynamically at runtime:

class FlexibleAgent(FiberAgent):
    def run_agent(self, input_data: dict, fiber):
        # Get services dynamically from the service registry
        service_name = input_data.get('provider', 'LLMProviderService')
        llm_service = fiber.services.get(service_name)
        
        # Handle different service types
        if hasattr(llm_service, 'generate'):
            return llm_service.generate(input_data['prompt'])
        else:
            return {"error": f"Service {service_name} not available"}

Service Registry & Lifecycle

๐Ÿ—๏ธ Automatic Registration

Services are automatically registered when the platform starts:

  • LLMProviderService - Configured LLM providers (OpenAI, Anthropic, etc.)
  • StorageService - Cloud storage with unified API
  • OAuthService - OAuth integrations for external services
  • DatabaseService - Direct database access
  • FiberApp - Platform SDK for activations and app features
โšก Performance & Caching

The service registry optimizes performance through:

  • Singleton Pattern - Services are instantiated once and reused
  • Lazy Loading - Services are created only when first accessed
  • Context Isolation - Each activation gets its own service context
  • Resource Cleanup - Automatic cleanup after activation completion
๐Ÿ”ง Configuration & Customization

Services can be configured and customized:

  • Environment Variables - Service-specific configuration
  • Runtime Configuration - Dynamic service parameters
  • Custom Services - Register your own services
  • Service Overrides - Replace default services with custom implementations

Activation Processor System

The Activation Processor is the sophisticated execution engine that manages agent lifecycle, dependency injection, and performance monitoring.

๐ŸŽฏ Pattern Detection

Automatically detects agent execution patterns:

  • Function-based agents (async def run_agent)
  • Class-based agents with run_agent method
  • FiberAgent subclasses with execute method

๐Ÿ’‰ Smart Injection

Advanced dependency injection capabilities:

  • Parameter name matching (llm_service โ†’ LLMProviderService)
  • Type hint resolution for complex dependencies
  • Service configuration and lifecycle management
  • Error handling for missing dependencies

๐Ÿ“Š Execution Context

Rich execution environment:

  • Context isolation between activations
  • Performance metrics and timing
  • Detailed logging and error tracking
  • Resource usage monitoring

Activation Lifecycle

1
Queue & Detection

Activation is queued and processor detects agent execution pattern

2
Service Resolution

Dependencies are resolved and services are prepared for injection

3
Agent Execution

Agent is instantiated and executed with injected services and input data

4
Result Processing

Output is validated, stored, and made available via WebSocket notifications

Activation Methods

๐Ÿ–ฅ๏ธ CLI Activation
# Activate with simple input
fiber activate --input '{"text": "Hello world"}' my_agent.py

# Activate with file input
fiber activate --input-file input.json my_agent.py

# Activate with specific LLM provider
fiber activate --provider openai --input '{"message": "Hi"}' chat_agent.py
๐ŸŒ Web API
POST /api/v1/agents/my_agent/activate
{
    "input_data": {
        "text": "Hello world",
        "temperature": 0.7
    },
    "agent_config": {
        "max_retries": 3,
        "timeout": 300
    }
}
๐Ÿ–ฑ๏ธ Web Interface

Interactive agent activation through the Fiberwiseweb dashboard with:

  • Form-based input validation
  • Real-time execution monitoring
  • WebSocket result streaming
  • Execution history and analytics

Common Application Patterns

Learn proven patterns for building different types of applications with Fiberwiseagents.

๐Ÿ—จ๏ธ Chat Applications

Build conversational interfaces with context management and message persistence:

class ChatApp {
  async sendMessage(message, sessionId) {
    // Store user message
    await fiber.data.create('messages', {
      session_id: sessionId,
      role: 'user',
      content: message,
      timestamp: new Date()
    });

    // Get agent response
    const response = await fiber.agents.activate('chat-agent', {
      message,
      context: { session_id: sessionId }
    });

    // Store agent response  
    await fiber.data.create('messages', {
      session_id: sessionId,
      role: 'assistant', 
      content: response.text,
      timestamp: new Date()
    });

    return response;
  }
}

๐Ÿ“Š Data Processing Applications

Process files and data with functions and store results:

class DataProcessor {
  async processFile(file, processingType) {
    // Upload file
    const fileRef = await fiber.files.upload(file);
    
    // Process with function
    const result = await fiber.functions.activate('file-processor', {
      file_ref: fileRef,
      processing_type: processingType
    });

    // Store results
    await fiber.data.create('processing_results', {
      file_ref: fileRef,
      result: result,
      processed_at: new Date()
    });

    return result;
  }
}

๐Ÿ”„ Workflow Applications

Create multi-step workflows with state management:

class WorkflowApp {
  async startWorkflow(workflowId, initialData) {
    // Create workflow instance
    const instance = await fiber.data.create('workflow_instances', {
      workflow_id: workflowId,
      status: 'running',
      data: initialData,
      started_at: new Date()
    });

    // Execute first step
    await this.executeWorkflowStep(instance.id, 0);
    
    return instance;
  }

  async executeWorkflowStep(instanceId, stepIndex) {
    // Get workflow definition and current data
    const instance = await fiber.data.get('workflow_instances', instanceId);
    
    // Execute step with agent or function
    const stepResult = await fiber.agents.activate('workflow-agent', {
      step_index: stepIndex,
      instance_data: instance.data
    });

    // Update instance with results
    await fiber.data.update('workflow_instances', instanceId, {
      data: { ...instance.data, ...stepResult.data },
      current_step: stepIndex + 1,
      updated_at: new Date()
    });

    return stepResult;
  }
}

Security & Authentication

Fiberwiseprovides comprehensive security features for enterprise applications:

๐Ÿ”‘ API Key Management

Secure API access for both app-level and user-level credentials:

// App-level API access (configured in dashboard)
const response = await fiber.agents.activate('agent-id', data);

// User-level API access (OAuth or user-provided keys)
const userResponse = await fiber.agents.activate('agent-id', data, {
  user_credentials: 'user-specific-token'
});

๐Ÿ” OAuth Integration

Connect to third-party services securely:

// Get OAuth authorization URL
const authUrl = await fiber.auth.getAuthUrl('google', {
  scopes: ['profile', 'email'],
  redirect_uri: 'https://yourapp.com/callback'
});

// Handle OAuth callback
const tokens = await fiber.auth.handleCallback('google', {
  code: 'auth-code-from-callback',
  state: 'csrf-protection-state'
});

// Use OAuth tokens in agents
const emailData = await fiber.agents.activate('email-agent', {
  action: 'list_emails',
  oauth_provider: 'google'
});

Best Practices

๐ŸŽฏ Agent Design

Single Responsibility: Each agent should have one clear purpose. Create multiple agents rather than one complex agent.
Clear Documentation: Document your agent's purpose, inputs, outputs, and dependencies.
Error Handling: Always handle errors gracefully and return meaningful error messages.

โšก Performance

Streaming: Use streaming for long-running agent tasks to improve user experience.
Error Handling: Implement proper error handling and retries for robust applications.
Caching: Cache frequently accessed data to reduce latency.
Real-time Updates: Use real-time updates only when necessary to avoid unnecessary overhead.

๐Ÿ”’ Security

API Keys: Never expose API keys in frontend code. Use environment variables or secure storage.
OAuth: Use OAuth for user-specific external service access rather than storing credentials.
Input Validation: Validate all user input before processing to prevent security vulnerabilities.
Access Controls: Implement proper access controls and user permissions.

๐Ÿ‘ค User Experience

Loading States: Provide loading states for async operations to keep users informed.
Optimistic Updates: Use optimistic updates where possible to make applications feel faster.
Offline Handling: Handle offline scenarios gracefully with appropriate messaging.
Error Messaging: Implement proper error messaging that helps users understand what went wrong.

๐Ÿ—๏ธ Code Organization

Web Components: Use Web Components for modularity and reusability.
Separation of Concerns: Separate concerns between UI, logic, and data layers.
Reusable Functions: Create reusable functions for common operations.
Documentation: Document your components and APIs thoroughly.

๐Ÿงช Testing

Unit Testing: Write tests for your agents using mock dependencies.
Integration Testing: Test agent interactions with the platform services.
Error Scenarios: Test error scenarios and edge cases.

Next Steps