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
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
Queue & Detection
Activation is queued and processor detects agent execution pattern
Service Resolution
Dependencies are resolved and services are prepared for injection
Agent Execution
Agent is instantiated and executed with injected services and input data
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'
});