Skip to main content

AI Agentic Workflows API Documentation

Advanced Multi-Step Workflow Execution REST API

Complete API reference for the AI Agentic Workflows module, providing intelligent multi-step execution, dynamic decision making, real-time monitoring, and comprehensive AI provider integration.

Base URL​

https://your-site.com/ai-workflows/api

Authentication​

All API endpoints support standard Drupal authentication:

  • Session Cookie: Web interface authentication
  • Basic Auth: Username/password for integrations
  • OAuth2: Third-party application access
  • API Keys: Token-based authentication
Authorization: Bearer YOUR_API_TOKEN
Content-Type: application/json
Accept: application/json

Core Workflow Execution APIs​

Execute Multi-Step Workflow​

Execute a comprehensive workflow with advanced AI integration and real-time monitoring.

POST /execute-flow
Content-Type: application/json

{
"flow_id": "advanced_content_processing",
"context": {
"content": "Content to process through the workflow",
"user_context": {
"role": "editor",
"department": "marketing",
"permissions": ["edit", "publish"]
},
"processing_options": {
"priority": "high",
"quality_level": "premium",
"target_audience": "developers",
"seo_requirements": true
},
"metadata": {
"source": "cms",
"content_type": "blog_post",
"language": "en",
"deadline": "2025-01-25T10:00:00Z"
}
},
"options": {
"execution_mode": "synchronous",
"monitoring": {
"enable_detailed_logging": true,
"track_intermediate_results": true,
"send_progress_updates": true,
"capture_agent_decisions": true
},
"ai_options": {
"preferred_providers": ["ollama", "openai"],
"fallback_enabled": true,
"cost_limit": 0.50,
"quality_threshold": 0.8
},
"error_handling": {
"retry_attempts": 3,
"retry_delay": 5,
"fallback_strategy": "continue_without_failed_step",
"notification_on_failure": true
},
"callback_config": {
"webhook_url": "https://mysite.com/webhook/workflow-complete",
"notification_email": "admin@example.com",
"progress_callbacks": true
}
}
}

Response Schema:

{
"success": true,
"execution_id": "flow_advanced_content_processing_xyz789",
"status": "completed",
"execution_summary": {
"flow_id": "advanced_content_processing",
"steps_executed": 5,
"steps_skipped": 1,
"execution_time": 127.8,
"total_cost": 0.156,
"success_rate": 100.0,
"agent_decisions_made": 3
},
"step_results": {
"content_analysis": {
"step_type": "ai_prompt",
"execution_time": 18.5,
"tokens_used": 567,
"cost": 0.028,
"success": true,
"results": {
"quality_score": 8.4,
"readability": 7.8,
"sentiment": 0.87,
"technical_depth": "intermediate",
"seo_potential": 85,
"improvement_areas": ["structure", "keywords"]
},
"ai_provider": "ollama",
"model_used": "llama3.2:latest",
"confidence": 0.94
},
"conditional_routing": {
"step_type": "conditional",
"execution_time": 2.1,
"success": true,
"conditions_evaluated": [
{
"condition": "quality_score > 8.0",
"result": true,
"action_taken": "proceed_to_advanced_optimization"
}
],
"routing_decision": "advanced_optimization_path"
},
"seo_optimization": {
"step_type": "ai_prompt",
"execution_time": 25.3,
"tokens_used": 789,
"cost": 0.039,
"success": true,
"results": {
"optimized_title": "Advanced AI Development: A Comprehensive Guide for Developers",
"meta_description": "Explore cutting-edge AI development techniques...",
"keyword_density": 2.8,
"internal_links_suggested": 4,
"header_structure_improved": true
},
"optimization_improvements": [
"Enhanced semantic structure",
"Improved keyword distribution",
"Added relevant internal links"
]
},
"external_validation": {
"step_type": "external_api",
"execution_time": 12.7,
"api_response_time": 8.9,
"success": true,
"api_endpoint": "https://api.grammarly.com/check",
"results": {
"grammar_score": 98,
"issues_found": 2,
"issues_fixed": 2,
"overall_improvement": 15.2
}
},
"data_transformation": {
"step_type": "data_transform",
"execution_time": 1.8,
"success": true,
"transformations_applied": 3,
"results": {
"consolidated_analysis": {
"final_quality_score": 9.2,
"optimization_score": 88,
"readiness_level": "publish_ready",
"confidence": 0.96
}
}
}
},
"shared_memory": {
"content_analysis": {...},
"seo_optimization": {...},
"final_analysis": {...}
},
"agent_decisions": [
{
"step": "content_analysis",
"agent": "content_quality_analyzer",
"decision": "high_quality_content_detected",
"confidence": 0.94,
"reasoning": "Content exceeds quality thresholds across all metrics",
"context_used": ["readability_score", "technical_accuracy", "structure"],
"alternative_paths_considered": ["basic_optimization", "quality_improvement"],
"timestamp": 1640995320
},
{
"step": "conditional_routing",
"decision": "advanced_optimization_path",
"confidence": 0.91,
"reasoning": "Quality score qualifies for advanced processing",
"workflow_modifications": {
"steps_added": ["advanced_seo_optimization"],
"steps_skipped": ["basic_content_fixes"]
}
},
{
"step": "seo_optimization",
"agent": "seo_specialist",
"decision": "comprehensive_optimization",
"confidence": 0.88,
"reasoning": "High potential for significant SEO improvements detected"
}
],
"performance_metrics": {
"total_execution_time": 127.8,
"ai_processing_time": 95.4,
"api_call_time": 18.2,
"data_processing_time": 14.2,
"total_ai_calls": 4,
"total_tokens_used": 2145,
"total_cost": 0.156,
"cache_hits": 2,
"provider_distribution": {
"ollama": 3,
"openai": 1
}
},
"resource_utilization": {
"peak_memory_usage": "89MB",
"cpu_time": "23.7s",
"network_requests": 6,
"cache_operations": 8
},
"quality_metrics": {
"overall_success_rate": 100.0,
"step_success_rate": 100.0,
"agent_confidence_avg": 0.91,
"output_quality_score": 9.2
},
"execution_timeline": [
{
"step": "content_analysis",
"started_at": 1640995200,
"completed_at": 1640995218,
"duration": 18.5
},
{
"step": "conditional_routing",
"started_at": 1640995219,
"completed_at": 1640995221,
"duration": 2.1
}
],
"warnings": [],
"recommendations": [
"Consider caching content analysis results for similar content",
"SEO optimization showed high impact - consider similar workflows"
],
"timestamp": 1640995800
}

Get Flow Execution Status​

Monitor real-time execution progress with comprehensive status information.

GET /execution-status/{execution_id}?include_details={boolean}&include_predictions={boolean}

Path Parameters:

  • execution_id (string): Unique execution identifier

Query Parameters:

  • include_details (boolean): Include detailed step information
  • include_predictions (boolean): Include completion time predictions
  • include_memory (boolean): Include shared memory state

Response Schema:

{
"execution_id": "flow_advanced_content_processing_xyz789",
"flow_id": "advanced_content_processing",
"status": "running",
"current_phase": "execution",
"progress": {
"overall_percentage": 68.0,
"current_step": "seo_optimization",
"current_step_progress": 75.0,
"steps_completed": 3,
"steps_remaining": 2,
"steps_total": 5
},
"timing": {
"started_at": 1640995200,
"current_time": 1640995287,
"elapsed_time": 87.3,
"estimated_completion": 1640995345,
"estimated_remaining": 58.2,
"last_activity": 1640995285
},
"current_step_details": {
"step_id": "seo_optimization",
"step_type": "ai_prompt",
"status": "processing",
"started_at": 1640995245,
"elapsed_time": 42.1,
"ai_provider": "ollama",
"model": "llama3.2:latest",
"progress_indicators": {
"prompt_processed": true,
"ai_response_streaming": true,
"response_processing": false,
"validation": false
},
"intermediate_output": {
"partial_results": "Optimizing title structure...",
"confidence_building": 0.78,
"tokens_processed": 456
}
},
"completed_steps": [
{
"step_id": "content_analysis",
"status": "completed",
"duration": 18.5,
"success": true,
"key_outputs": {
"quality_score": 8.4,
"readability": 7.8,
"sentiment": 0.87
}
},
{
"step_id": "conditional_routing",
"status": "completed",
"duration": 2.1,
"success": true,
"routing_decision": "advanced_optimization_path"
},
{
"step_id": "quality_validation",
"status": "completed",
"duration": 15.2,
"success": true,
"validation_score": 9.1
}
],
"upcoming_steps": [
{
"step_id": "final_review",
"step_type": "ai_prompt",
"estimated_duration": 12.0,
"dependencies": ["seo_optimization"]
},
{
"step_id": "data_export",
"step_type": "data_transform",
"estimated_duration": 3.5,
"dependencies": ["final_review"]
}
],
"shared_memory_state": {
"content_analysis": {
"quality_score": 8.4,
"technical_depth": "intermediate",
"target_keywords": ["ai", "development", "machine learning"]
},
"optimization_context": {
"seo_focus": "technical_content",
"audience": "developers",
"content_length": 2450
}
},
"agent_activity": [
{
"step": "seo_optimization",
"agent": "seo_specialist",
"activity": "analyzing_keyword_density",
"progress": 75.0,
"last_update": 1640995285,
"processing_tokens": 234
}
],
"resource_usage": {
"current_memory": "67MB",
"peak_memory": "89MB",
"cpu_usage": 45.2,
"active_connections": 2,
"queue_position": null
},
"cost_tracking": {
"current_cost": 0.089,
"estimated_total_cost": 0.156,
"cost_by_provider": {
"ollama": 0.000,
"openai": 0.089
},
"budget_remaining": 0.411
},
"performance_indicators": {
"execution_health": "excellent",
"step_success_rate": 100.0,
"average_step_time": 16.8,
"provider_response_times": {
"ollama": 1.2,
"openai": 2.8
}
},
"predictions": {
"completion_confidence": 0.94,
"estimated_final_cost": 0.156,
"potential_issues": [],
"optimization_opportunities": [
"Step 'final_review' could benefit from caching"
]
},
"real_time_logs": [
{
"timestamp": 1640995285,
"level": "info",
"message": "SEO optimization 75% complete",
"step": "seo_optimization",
"details": {"keywords_processed": 15, "suggestions_generated": 8}
},
{
"timestamp": 1640995280,
"level": "debug",
"message": "AI provider response received",
"step": "seo_optimization",
"response_time": 2.1
}
],
"warnings": [
{
"type": "performance",
"message": "Current step taking longer than average",
"threshold": 35.0,
"current": 42.1,
"impact": "low"
}
]
}

Execute Flow Asynchronously​

Execute workflows in background with comprehensive monitoring and callback support.

POST /execute-flow-async
Content-Type: application/json

{
"flow_id": "large_content_processing",
"context": {
"content_batch": ["article1", "article2", "article3"],
"processing_rules": {
"batch_size": 10,
"parallel_processing": true,
"quality_threshold": 0.8
}
},
"options": {
"priority": "high",
"max_execution_time": 1800,
"resource_limits": {
"max_memory": "512MB",
"max_concurrent_ai_calls": 3
},
"notifications": {
"progress_interval": 300,
"webhook_url": "https://mysite.com/webhook/progress",
"email_on_completion": "admin@example.com",
"slack_channel": "#ai-workflows"
},
"retry_config": {
"max_attempts": 3,
"exponential_backoff": true,
"retry_on_provider_error": true
}
}
}

Response Schema:

{
"success": true,
"execution_id": "async_large_content_processing_def456",
"status": "queued",
"queue_position": 3,
"estimated_start_time": 1640995890,
"estimated_completion_time": 1640997690,
"monitoring": {
"status_url": "/execution-status/async_large_content_processing_def456",
"webhook_configured": true,
"progress_notifications": true
},
"execution_config": {
"priority": "high",
"estimated_cost": 2.45,
"resource_allocation": {
"memory_reserved": "512MB",
"cpu_priority": "high",
"ai_call_slots": 3
}
},
"callback_info": {
"webhook_url": "https://mysite.com/webhook/progress",
"webhook_secret": "wh_secret_abc123",
"supported_events": [
"execution.started",
"execution.progress",
"execution.completed",
"execution.failed"
]
},
"timestamp": 1640995800
}

Get Flow Recommendations​

AI-powered workflow recommendations based on context analysis and historical performance.

POST /recommend-flows
Content-Type: application/json

{
"context": {
"content_type": "technical_documentation",
"content_characteristics": {
"length": 5000,
"complexity": "high",
"technical_level": "expert",
"target_audience": "developers",
"language": "en",
"domain": "machine_learning"
},
"current_quality_metrics": {
"readability_score": 6.2,
"seo_score": 45,
"technical_accuracy": 8.9,
"structure_score": 7.1
},
"business_requirements": {
"target_seo_score": 85,
"required_quality_level": "premium",
"compliance_requirements": ["gdpr", "accessibility"],
"publication_deadline": "2025-01-30T10:00:00Z"
},
"user_context": {
"role": "technical_writer",
"experience_level": "expert",
"department": "engineering",
"previous_workflows": ["technical_content_enhancement", "api_documentation"]
}
},
"preferences": {
"max_cost": 1.00,
"max_duration": 300,
"min_confidence": 0.85,
"preferred_providers": ["ollama", "openai"],
"exclude_experimental": true,
"prioritize": "quality_over_speed",
"explain_recommendations": true
},
"constraints": {
"available_time_window": "2025-01-25T09:00:00Z/2025-01-25T17:00:00Z",
"resource_limits": {
"max_memory": "1GB",
"max_concurrent_flows": 2
},
"compliance_requirements": ["data_retention", "audit_logging"]
}
}

Response Schema:

{
"recommendations": [
{
"flow_id": "expert_technical_content_enhancement",
"confidence": 0.96,
"match_score": 9.4,
"recommendation_strength": "highly_recommended",
"reasoning": {
"primary_factors": [
"Perfect match for technical documentation processing",
"Excellent track record with similar content complexity",
"Optimal provider selection for technical content",
"Strong historical performance for ML domain content"
],
"context_alignment": {
"content_type_match": 0.98,
"complexity_handling": 0.94,
"domain_expertise": 0.92,
"audience_targeting": 0.89
},
"performance_indicators": {
"success_rate_similar_content": 0.96,
"avg_quality_improvement": 2.8,
"user_satisfaction": 4.7
}
},
"estimated_outcomes": {
"quality_improvement": {
"readability_score": 8.5,
"seo_score": 87,
"technical_accuracy": 9.4,
"structure_score": 9.1,
"overall_improvement": 35.2
},
"execution_estimates": {
"duration": 185,
"cost": 0.78,
"success_probability": 0.96,
"completion_confidence": 0.94
}
},
"flow_composition": {
"total_steps": 7,
"ai_steps": 5,
"conditional_steps": 2,
"api_steps": 1,
"transform_steps": 2,
"critical_steps": ["technical_analysis", "domain_validation", "expert_review"]
},
"provider_strategy": {
"primary_provider": "ollama",
"fallback_provider": "openai",
"provider_distribution": {
"ollama": ["technical_analysis", "structure_optimization"],
"openai": ["domain_validation", "expert_review"]
},
"cost_optimization": "balanced"
},
"risk_assessment": {
"risk_level": "low",
"potential_issues": [
{
"risk": "high_complexity_timeout",
"probability": 0.05,
"mitigation": "Extended timeout configuration available"
}
],
"mitigation_strategies": [
"Automatic step retry on timeout",
"Progressive complexity handling",
"Fallback to simplified processing"
]
},
"customization_options": [
{
"variant": "speed_optimized",
"duration": 120,
"cost": 0.65,
"quality_tradeoff": -0.3,
"description": "Faster execution with slightly reduced analysis depth"
},
{
"variant": "premium_quality",
"duration": 245,
"cost": 1.25,
"quality_improvement": +0.5,
"description": "Maximum quality with additional validation steps"
}
]
},
{
"flow_id": "comprehensive_documentation_processor",
"confidence": 0.89,
"match_score": 8.7,
"recommendation_strength": "recommended",
"reasoning": {
"primary_factors": [
"Good fit for comprehensive documentation processing",
"Strong SEO optimization capabilities",
"Effective compliance handling"
]
},
"estimated_outcomes": {
"quality_improvement": {
"readability_score": 8.2,
"seo_score": 92,
"technical_accuracy": 9.1,
"structure_score": 8.8
},
"execution_estimates": {
"duration": 215,
"cost": 0.92,
"success_probability": 0.91
}
}
}
],
"context_analysis": {
"complexity_assessment": {
"content_complexity": "high",
"processing_difficulty": "moderate",
"domain_specialization_required": true,
"estimated_processing_time": 180
},
"optimization_opportunities": [
{
"area": "seo_improvement",
"current_score": 45,
"potential_score": 87,
"improvement_potential": 93.3,
"priority": "high"
},
{
"area": "readability_enhancement",
"current_score": 6.2,
"potential_score": 8.5,
"improvement_potential": 37.1,
"priority": "medium"
}
],
"domain_insights": {
"domain": "machine_learning",
"specialized_processing_required": true,
"domain_specific_validators": ["ml_terminology", "technical_accuracy", "code_examples"],
"expert_review_recommended": true
}
},
"workflow_comparison": {
"comparison_matrix": [
{
"criterion": "quality_potential",
"expert_technical_content_enhancement": 9.4,
"comprehensive_documentation_processor": 8.7,
"basic_content_processor": 6.2
},
{
"criterion": "cost_efficiency",
"expert_technical_content_enhancement": 8.9,
"comprehensive_documentation_processor": 7.8,
"basic_content_processor": 9.5
},
{
"criterion": "speed",
"expert_technical_content_enhancement": 7.8,
"comprehensive_documentation_processor": 7.2,
"basic_content_processor": 9.1
}
],
"recommendation_summary": "expert_technical_content_enhancement offers the best balance of quality and efficiency for your specific requirements"
},
"alternative_strategies": [
{
"strategy": "sequential_processing",
"description": "Process in multiple stages for better quality control",
"flows": ["basic_content_analysis", "expert_technical_enhancement", "final_review"],
"total_cost": 1.15,
"total_duration": 285,
"quality_potential": 9.6
},
{
"strategy": "parallel_processing",
"description": "Process different aspects simultaneously for speed",
"flows": ["technical_analysis", "seo_optimization", "structure_enhancement"],
"total_cost": 0.95,
"total_duration": 145,
"coordination_complexity": "moderate"
}
],
"success_predictors": {
"high_success_indicators": [
"Content complexity matches flow capabilities",
"Strong historical performance in ML domain",
"User expertise level aligns with flow sophistication"
],
"potential_challenges": [
"High technical complexity may require extended processing",
"Domain-specific validation needed for accuracy"
],
"success_optimization_tips": [
"Provide comprehensive context for better analysis",
"Consider premium quality variant for critical content",
"Enable expert review for technical accuracy"
]
},
"cost_breakdown": {
"base_processing": 0.45,
"ai_provider_costs": 0.28,
"premium_features": 0.05,
"estimated_total": 0.78,
"cost_comparison": {
"vs_manual_processing": "-85%",
"vs_basic_automation": "+23%",
"vs_external_service": "-62%"
}
},
"recommendation_metadata": {
"analysis_version": "2.1.0",
"model_confidence": 0.94,
"recommendations_generated": 2,
"analysis_duration": 3.2,
"data_sources": [
"historical_performance",
"user_preferences",
"content_analysis",
"domain_expertise"
],
"last_updated": 1640995800
}
}

Advanced Flow Configuration APIs​

Create Custom Flow Definition​

Define complex multi-step workflows with AI integration and dynamic routing.

POST /flows
Content-Type: application/json

{
"flow_definition": {
"id": "custom_research_workflow",
"label": "Custom Research & Analysis Workflow",
"description": "Advanced research workflow with AI-powered analysis and dynamic routing",
"version": "1.0.0",
"category": "research",
"tags": ["research", "analysis", "ai", "dynamic"],
"steps": [
{
"id": "initial_research",
"type": "ai_prompt",
"label": "Initial Research Phase",
"prompt": "Conduct comprehensive research on: {{research_topic}}. Focus on {{focus_areas}} and provide detailed analysis including current trends, key players, and future outlook.",
"ai_options": {
"model": "llama3.2:latest",
"temperature": 0.4,
"max_tokens": 2000,
"system_prompt": "You are an expert researcher with deep knowledge across multiple domains. Provide comprehensive, factual, and well-structured research."
},
"output_to_memory": "initial_research_results",
"validation": {
"min_length": 500,
"required_sections": ["overview", "trends", "key_players"],
"quality_threshold": 0.8
},
"retry_config": {
"max_attempts": 3,
"retry_on_validation_failure": true
}
},
{
"id": "quality_assessment",
"type": "conditional",
"label": "Research Quality Assessment",
"conditions": [
{
"field": "initial_research_results.quality_score",
"operator": ">=",
"value": 0.8,
"action": {
"type": "continue",
"next_step": "competitive_analysis"
}
},
{
"field": "initial_research_results.quality_score",
"operator": "<",
"value": 0.8,
"action": {
"type": "jump_to_step",
"target_step": "research_enhancement",
"reason": "Initial research quality below threshold"
}
}
],
"default_action": {
"type": "continue",
"next_step": "competitive_analysis"
}
},
{
"id": "competitive_analysis",
"type": "ai_prompt",
"label": "Competitive Analysis",
"prompt": "Based on the initial research: {{initial_research_results}}, conduct a detailed competitive analysis. Identify main competitors, their strengths/weaknesses, market positioning, and opportunities.",
"ai_options": {
"model": "gpt-4",
"temperature": 0.3,
"max_tokens": 1500
},
"dependencies": ["initial_research"],
"output_to_memory": "competitive_analysis_results",
"parallel_execution": false
},
{
"id": "market_data_fetch",
"type": "external_api",
"label": "Market Data Collection",
"api": {
"url": "https://api.marketdata.com/v1/research",
"method": "POST",
"headers": {
"Authorization": "Bearer {{market_data_api_key}}",
"Content-Type": "application/json"
},
"body": {
"query": "{{research_topic}}",
"data_types": ["market_size", "growth_rate", "trends"],
"time_period": "5_years",
"regions": "{{target_regions}}"
},
"timeout": 45,
"retry_attempts": 2
},
"output_to_memory": "market_data",
"error_handling": {
"on_failure": "continue_without_data",
"fallback_message": "Market data unavailable - continuing with available research"
}
},
{
"id": "data_synthesis",
"type": "data_transform",
"label": "Data Synthesis & Integration",
"dependencies": ["competitive_analysis", "market_data_fetch"],
"transformations": [
{
"operation": "merge",
"sources": [
"initial_research_results",
"competitive_analysis_results",
"market_data"
],
"merge_strategy": "comprehensive"
},
{
"operation": "calculate_metrics",
"fields": [
"market_opportunity_score",
"competitive_threat_level",
"research_confidence_score"
],
"calculation_method": "weighted_average"
},
{
"operation": "generate_summary",
"template": "research_report_template",
"include_visualizations": true
}
],
"output_to_memory": "synthesized_report",
"validation": {
"required_fields": ["market_opportunity_score", "executive_summary"],
"min_confidence": 0.7
}
},
{
"id": "ai_insights_generation",
"type": "ai_prompt",
"label": "AI-Powered Insights Generation",
"prompt": "Based on the comprehensive research data: {{synthesized_report}}, generate strategic insights, recommendations, and actionable next steps. Include risk assessment and opportunity prioritization.",
"ai_options": {
"model": "gpt-4-turbo",
"temperature": 0.6,
"max_tokens": 2500,
"system_prompt": "You are a strategic business analyst. Provide actionable insights with specific recommendations and clear reasoning."
},
"dependencies": ["data_synthesis"],
"output_to_memory": "strategic_insights",
"agent_routing": true,
"routing_prompt": "Should this analysis include detailed financial projections? Consider the research depth and available market data.",
"routing_options": {
"include_financial_analysis": {
"add_steps": ["financial_projections", "roi_analysis"],
"condition": "market_data_quality >= 0.8"
},
"skip_financial_analysis": {
"continue_to": "final_report_generation",
"reason": "Insufficient financial data for accurate projections"
}
}
},
{
"id": "final_report_generation",
"type": "ai_prompt",
"label": "Comprehensive Report Generation",
"prompt": "Create a comprehensive research report combining all findings: {{initial_research_results}}, {{competitive_analysis_results}}, {{market_data}}, and {{strategic_insights}}. Format as a professional business report with executive summary, detailed findings, and recommendations.",
"ai_options": {
"model": "gpt-4",
"temperature": 0.2,
"max_tokens": 4000,
"system_prompt": "You are a professional report writer. Create well-structured, executive-level reports with clear sections and actionable recommendations."
},
"dependencies": ["ai_insights_generation"],
"output_to_memory": "final_report",
"post_processing": [
{
"operation": "format_document",
"format": "markdown",
"include_toc": true,
"add_charts": true
},
{
"operation": "quality_check",
"checks": ["grammar", "structure", "completeness"],
"min_quality_score": 0.9
}
]
}
],
"global_configuration": {
"agent_routing_enabled": true,
"shared_memory_persistent": true,
"error_handling": {
"global_retry_attempts": 2,
"fallback_strategy": "graceful_degradation",
"notification_on_failure": true
},
"monitoring": {
"enable_detailed_logging": true,
"track_performance_metrics": true,
"capture_intermediate_results": true
},
"resource_limits": {
"max_execution_time": 1800,
"max_memory_usage": "1GB",
"max_concurrent_ai_calls": 3
},
"cost_controls": {
"max_total_cost": 5.00,
"cost_alerts": [1.00, 2.50, 4.00],
"auto_abort_on_budget_exceeded": false
}
}
},
"metadata": {
"created_by": "research_team",
"department": "business_intelligence",
"use_cases": ["market_research", "competitive_analysis", "strategic_planning"],
"estimated_duration": 450,
"estimated_cost": 2.50,
"complexity_level": "high",
"approval_required": false
}
}

Response Schema:

{
"success": true,
"flow_id": "custom_research_workflow",
"status": "created",
"validation_results": {
"is_valid": true,
"steps_validated": 7,
"dependencies_resolved": true,
"resource_requirements_feasible": true,
"estimated_performance": {
"avg_execution_time": 425,
"success_probability": 0.94,
"estimated_cost": 2.35
}
},
"flow_summary": {
"total_steps": 7,
"ai_steps": 4,
"conditional_steps": 1,
"api_steps": 1,
"transform_steps": 1,
"dynamic_routing_enabled": true,
"parallel_execution_steps": 0
},
"deployment_info": {
"environment": "production",
"version": "1.0.0",
"deployment_timestamp": 1640995800,
"testing_recommended": true,
"approval_status": "auto_approved"
},
"next_steps": [
"Test flow with sample data",
"Configure monitoring alerts",
"Set up user permissions",
"Schedule regular reviews"
]
}

Monitoring & Analytics APIs​

Get Flow Analytics​

Comprehensive analytics for flow performance, costs, and optimization opportunities.

GET /analytics/flows?timeframe={timeframe}&flow_ids={flow_ids}&include_predictions={boolean}

Query Parameters:

  • timeframe (string): Analysis period (1h, 24h, 7d, 30d)
  • flow_ids (array): Specific flows to analyze
  • include_predictions (boolean): Include performance predictions
  • group_by (string): Group results (flow, step_type, provider)
  • include_cost_breakdown (boolean): Detailed cost analysis

Response Schema:

{
"analytics_summary": {
"timeframe": "24h",
"flows_analyzed": 8,
"total_executions": 234,
"success_rate": 94.3,
"avg_execution_time": 87.5,
"total_cost": 15.67,
"unique_users": 23,
"data_freshness": "real-time"
},
"flow_performance": {
"advanced_content_processing": {
"executions": 89,
"success_rate": 96.6,
"avg_duration": 127.8,
"avg_cost": 0.156,
"user_satisfaction": 4.8,
"performance_trend": "+12%",
"step_breakdown": {
"content_analysis": {"avg_time": 18.5, "success_rate": 98.9},
"seo_optimization": {"avg_time": 25.3, "success_rate": 94.4},
"final_review": {"avg_time": 12.7, "success_rate": 97.8}
},
"cost_breakdown": {
"ai_processing": 0.089,
"api_calls": 0.023,
"data_processing": 0.044,
"total": 0.156
},
"optimization_opportunities": [
{
"area": "step_caching",
"potential_savings": "15% cost reduction",
"implementation_effort": "low"
},
{
"area": "provider_optimization",
"potential_savings": "8% speed improvement",
"implementation_effort": "medium"
}
]
}
},
"step_type_analysis": {
"ai_prompt": {
"total_executions": 445,
"avg_duration": 22.3,
"success_rate": 95.8,
"cost_per_execution": 0.045,
"token_efficiency": 0.78,
"top_models": ["llama3.2:latest", "gpt-4", "claude-3"]
},
"external_api": {
"total_executions": 123,
"avg_duration": 8.7,
"success_rate": 92.7,
"timeout_rate": 4.1,
"retry_rate": 7.3
},
"data_transform": {
"total_executions": 234,
"avg_duration": 2.1,
"success_rate": 99.1,
"memory_efficiency": 0.91
}
},
"provider_analysis": {
"ollama": {
"usage_percentage": 67.2,
"avg_response_time": 1.8,
"success_rate": 97.2,
"cost_per_request": 0.000,
"availability": "99.8%",
"models_used": ["llama3.2:latest", "nomic-embed-text"]
},
"openai": {
"usage_percentage": 28.1,
"avg_response_time": 2.9,
"success_rate": 94.6,
"cost_per_request": 0.023,
"rate_limit_hits": 3,
"models_used": ["gpt-4", "gpt-3.5-turbo"]
},
"anthropic": {
"usage_percentage": 4.7,
"avg_response_time": "N/A",
"success_rate": 0.0,
"status": "offline",
"last_successful_request": "2025-01-23T14:30:00Z"
}
},
"user_behavior_insights": {
"most_popular_flows": [
{"flow_id": "content_processing", "usage": 89},
{"flow_id": "seo_optimization", "usage": 67},
{"flow_id": "data_analysis", "usage": 45}
],
"peak_usage_times": ["09:00-11:00", "14:00-16:00"],
"avg_session_length": 245,
"user_retention_rate": 0.87,
"feature_adoption": {
"async_execution": 34.2,
"custom_workflows": 12.8,
"ai_routing": 67.3
}
},
"cost_analysis": {
"total_cost_24h": 15.67,
"cost_per_execution": 0.067,
"cost_trends": {
"vs_yesterday": "-8.2%",
"vs_week_ago": "+15.3%",
"vs_month_ago": "-23.1%"
},
"cost_distribution": {
"ai_processing": 67.2,
"api_calls": 18.4,
"data_storage": 8.9,
"compute_resources": 5.5
},
"cost_optimization_recommendations": [
{
"strategy": "increase_caching",
"potential_savings": "$2.34/day",
"implementation": "Enable result caching for repeated queries"
},
{
"strategy": "provider_rebalancing",
"potential_savings": "$1.89/day",
"implementation": "Route more requests to Ollama for cost efficiency"
}
]
},
"quality_metrics": {
"output_quality_avg": 8.7,
"user_satisfaction_avg": 4.6,
"error_rate_by_category": {
"validation_errors": 2.1,
"timeout_errors": 1.8,
"provider_errors": 1.4,
"system_errors": 0.3
},
"quality_trends": {
"improvement_rate": "+5.2% per week",
"consistency_score": 0.91,
"reliability_index": 0.94
}
},
"predictions": {
"next_24h": {
"expected_executions": 267,
"predicted_success_rate": 0.95,
"estimated_cost": 17.89,
"confidence": 0.88
},
"weekly_forecast": {
"execution_trend": "+18%",
"cost_trend": "+12%",
"performance_trend": "+3%",
"capacity_alerts": [
{
"metric": "concurrent_executions",
"predicted_peak": "2025-01-26T15:00:00Z",
"threshold_risk": "medium"
}
]
},
"optimization_impact": {
"cache_implementation": {
"cost_reduction": "12-18%",
"performance_improvement": "8-15%",
"implementation_timeline": "1-2 weeks"
},
"provider_optimization": {
"cost_reduction": "5-12%",
"performance_improvement": "3-8%",
"implementation_timeline": "3-5 days"
}
}
},
"benchmark_comparisons": {
"industry_averages": {
"success_rate": 0.89,
"avg_cost_per_execution": 0.089,
"user_satisfaction": 4.2
},
"performance_vs_benchmark": {
"success_rate": "+5.3%",
"cost_efficiency": "+24.7%",
"user_satisfaction": "+9.5%"
}
},
"alert_recommendations": [
{
"type": "performance",
"threshold": "success_rate < 90%",
"current_value": 94.3,
"recommended_action": "Monitor for degradation trends"
},
{
"type": "cost",
"threshold": "daily_cost > $20.00",
"current_value": 15.67,
"recommended_action": "Consider cost optimization strategies"
}
]
}

Integration & Webhook APIs​

Configure Webhooks​

Set up webhooks for real-time workflow event notifications.

POST /webhooks
Content-Type: application/json

{
"webhook_config": {
"url": "https://your-app.com/webhooks/ai-workflows",
"secret": "your-webhook-secret-key",
"events": [
"flow.execution.started",
"flow.execution.completed",
"flow.execution.failed",
"flow.step.completed",
"agent.decision.made",
"cost.threshold.exceeded",
"performance.degradation.detected"
],
"filters": {
"flow_ids": ["advanced_content_processing", "research_workflow"],
"min_cost": 0.10,
"priority": ["high", "critical"]
},
"retry_policy": {
"max_attempts": 5,
"retry_delay": 30,
"exponential_backoff": true,
"timeout": 10
},
"format": {
"content_type": "application/json",
"include_full_context": false,
"include_intermediate_results": true,
"compression": "gzip"
}
}
}

Response Schema:

{
"success": true,
"webhook_id": "wh_ai_workflows_abc123",
"webhook_url": "https://your-app.com/webhooks/ai-workflows",
"events_subscribed": 7,
"verification": {
"verification_required": true,
"verification_token": "verify_abc123def456",
"verification_url": "https://your-app.com/webhooks/ai-workflows?verify=verify_abc123def456",
"expires_at": 1640999400
},
"status": "pending_verification",
"created_at": 1640995800
}

Webhook Event Examples​

Flow Execution Started:

{
"event": "flow.execution.started",
"timestamp": 1640995800,
"webhook_id": "wh_ai_workflows_abc123",
"data": {
"execution_id": "flow_content_processing_xyz789",
"flow_id": "advanced_content_processing",
"initiated_by": "user_123",
"estimated_duration": 127,
"estimated_cost": 0.156,
"priority": "high",
"context_summary": {
"content_type": "blog_post",
"content_length": 2450,
"target_quality": "premium"
}
},
"signature": "sha256=abc123def456789..."
}

Agent Decision Made:

{
"event": "agent.decision.made",
"timestamp": 1640995850,
"data": {
"execution_id": "flow_content_processing_xyz789",
"step_id": "quality_assessment",
"agent_id": "content_quality_analyzer",
"decision": {
"action": "proceed_to_advanced_optimization",
"confidence": 0.94,
"reasoning": "Content quality score (8.4) exceeds threshold for advanced processing",
"alternatives_considered": ["basic_optimization", "quality_improvement"],
"workflow_modifications": {
"steps_added": ["advanced_seo_optimization"],
"estimated_additional_cost": 0.023,
"estimated_additional_time": 18
}
}
}
}

Flow Execution Completed:

{
"event": "flow.execution.completed",
"timestamp": 1640995927,
"data": {
"execution_id": "flow_content_processing_xyz789",
"flow_id": "advanced_content_processing",
"status": "completed",
"execution_summary": {
"duration": 127.8,
"steps_executed": 5,
"success_rate": 100.0,
"total_cost": 0.156,
"agent_decisions": 3
},
"results": {
"final_quality_score": 9.2,
"optimization_improvements": 35.2,
"seo_score": 87,
"readiness_level": "publish_ready"
},
"performance_metrics": {
"avg_step_time": 25.6,
"cache_hit_rate": 0.4,
"provider_distribution": {"ollama": 3, "openai": 2}
}
}
}

Error Handling and Status Codes​

HTTP Status Codes​

  • 200 OK: Request successful
  • 201 Created: Resource created successfully
  • 202 Accepted: Request accepted for async processing
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 409 Conflict: Resource conflict (e.g., duplicate flow ID)
  • 422 Unprocessable Entity: Valid request but logical errors
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error
  • 502 Bad Gateway: AI provider unavailable
  • 503 Service Unavailable: System overloaded
  • 504 Gateway Timeout: Request timeout

Error Response Format​

{
"error": {
"code": "FLOW_EXECUTION_FAILED",
"message": "Workflow execution failed due to AI provider timeout",
"details": {
"execution_id": "flow_content_processing_xyz789",
"failed_step": "seo_optimization",
"provider": "openai",
"timeout_duration": 30,
"retry_attempts": 3,
"partial_results": {
"completed_steps": ["content_analysis", "quality_assessment"],
"available_data": {...}
}
},
"recovery_options": [
{
"action": "retry_with_different_provider",
"description": "Retry the failed step with Ollama provider",
"estimated_cost": 0.000,
"estimated_time": 15
},
{
"action": "continue_without_failed_step",
"description": "Skip SEO optimization and proceed to final review",
"impact": "Reduced optimization quality"
},
{
"action": "restart_from_checkpoint",
"description": "Restart from the last successful checkpoint",
"estimated_cost": 0.067,
"estimated_time": 45
}
],
"timestamp": 1640995800,
"request_id": "req_abc123def456",
"support_reference": "sr_2025_0124_001",
"documentation_url": "https://docs.example.com/errors/flow-execution-failed"
}
}

Common Error Codes​

CodeDescriptionRecovery Actions
INVALID_FLOW_DEFINITIONFlow configuration is invalidValidate and fix flow definition
FLOW_NOT_FOUNDSpecified flow doesn't existCheck flow ID, create flow if needed
EXECUTION_TIMEOUTWorkflow execution timed outIncrease timeout, optimize flow steps
PROVIDER_UNAVAILABLEAI provider is offlineUse fallback provider, retry later
INSUFFICIENT_CREDITSAccount credit limit reachedAdd credits, upgrade plan
VALIDATION_FAILEDInput validation failedFix input data, check requirements
CONCURRENT_LIMIT_EXCEEDEDToo many concurrent executionsWait for completion, upgrade limits
STEP_DEPENDENCY_FAILEDRequired step dependency failedCheck dependencies, fix prerequisites
AGENT_DECISION_ERRORAI agent decision logic failedReview agent configuration
MEMORY_LIMIT_EXCEEDEDWorkflow exceeded memory limitsOptimize data processing, increase limits

SDKs and Client Libraries​

PHP/Drupal SDK​

<?php

use Drupal\ai_agentic_workflows\Client\WorkflowClient;

// Initialize client
$client = new WorkflowClient([
'base_url' => 'https://your-site.com/ai-workflows/api',
'api_token' => 'your-api-token',
'timeout' => 300,
'retry_attempts' => 3
]);

// Execute workflow synchronously
$result = $client->executeFlow('advanced_content_processing', [
'content' => $content,
'user_context' => ['role' => 'editor'],
'options' => ['quality_level' => 'premium']
]);

// Execute asynchronously with monitoring
$execution_id = $client->executeFlowAsync('large_batch_processing', [
'batch_data' => $batch_items,
'processing_options' => ['parallel' => true]
], [
'webhook_url' => 'https://mysite.com/webhook/progress',
'email_notifications' => true
]);

// Monitor execution
$status = $client->getExecutionStatus($execution_id);
while ($status['status'] === 'running') {
sleep(10);
$status = $client->getExecutionStatus($execution_id);
echo "Progress: {$status['progress']['overall_percentage']}%\n";
}

// Get recommendations
$recommendations = $client->getFlowRecommendations([
'content_type' => 'technical_article',
'complexity' => 'high',
'target_audience' => 'developers'
], [
'max_cost' => 1.00,
'min_confidence' => 0.85
]);

foreach ($recommendations['recommendations'] as $rec) {
echo "Recommended: {$rec['flow_id']} (confidence: {$rec['confidence']})\n";
}

JavaScript/Node.js SDK​

const { WorkflowClient } = require('@ai-workflows/client');

// Initialize client
const client = new WorkflowClient({
baseUrl: 'https://your-site.com/ai-workflows/api',
apiToken: process.env.AI_WORKFLOWS_TOKEN,
timeout: 300000,
retryAttempts: 3
});

// Execute workflow with comprehensive monitoring
async function processContent(content, options = {}) {
try {
// Get recommendations first
const recommendations = await client.getFlowRecommendations({
content_type: 'blog_post',
content_length: content.length,
target_audience: options.audience || 'general'
}, {
max_cost: options.budget || 0.50,
min_confidence: 0.8
});

const bestFlow = recommendations.recommendations[0];
console.log(`Using recommended flow: ${bestFlow.flow_id}`);

// Execute the recommended workflow
const execution = await client.executeFlow(bestFlow.flow_id, {
content: content,
user_context: options.userContext,
processing_options: options.processing
}, {
monitoring: {
enable_detailed_logging: true,
track_intermediate_results: true
},
callback_config: {
webhook_url: options.webhookUrl
}
});

return {
success: true,
execution_id: execution.execution_id,
results: execution.step_results,
metrics: execution.performance_metrics
};

} catch (error) {
console.error('Workflow execution failed:', error);

// Handle specific error types
if (error.code === 'PROVIDER_UNAVAILABLE') {
// Retry with fallback provider
return await client.executeFlow(bestFlow.flow_id, {
content: content,
// ... context
}, {
ai_options: {
preferred_providers: ['ollama'], // Use local provider
fallback_enabled: true
}
});
}

throw error;
}
}

// Real-time monitoring with Server-Sent Events
function monitorExecution(executionId, onUpdate) {
const eventSource = new EventSource(
`${client.baseUrl}/execution-stream/${executionId}`,
{
headers: {
'Authorization': `Bearer ${client.apiToken}`
}
}
);

eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
onUpdate(data);
};

eventSource.addEventListener('step_completed', (event) => {
const stepData = JSON.parse(event.data);
console.log(`Step completed: ${stepData.step_id}`);
});

eventSource.addEventListener('execution_completed', (event) => {
const results = JSON.parse(event.data);
console.log('Execution completed:', results);
eventSource.close();
});

return eventSource;
}

// Usage example
(async () => {
const content = "Your content to process...";

const result = await processContent(content, {
audience: 'developers',
budget: 1.00,
userContext: { role: 'editor', department: 'engineering' },
webhookUrl: 'https://myapp.com/webhook/workflow-complete'
});

if (result.success) {
console.log('Processing completed successfully');
console.log('Final quality score:', result.results.final_analysis?.quality_score);
console.log('Total cost:', result.metrics.total_cost);
}
})();

Python SDK​

import asyncio
import json
from ai_workflows import WorkflowClient, WebhookHandler
from typing import Dict, List, Optional

class WorkflowManager:
def __init__(self, api_token: str, base_url: str):
self.client = WorkflowClient(
base_url=base_url,
api_token=api_token,
timeout=300,
retry_attempts=3
)

async def process_content_batch(self,
content_items: List[Dict],
flow_preferences: Dict = None) -> List[Dict]:
"""Process multiple content items with optimal flow selection."""

results = []

for item in content_items:
# Get personalized recommendations
recommendations = await self.client.get_flow_recommendations(
context={
'content_type': item.get('type', 'article'),
'content_length': len(item['content']),
'target_audience': item.get('audience', 'general'),
'current_quality_metrics': item.get('quality_metrics', {})
},
preferences={
'max_cost': flow_preferences.get('budget_per_item', 0.50),
'max_duration': flow_preferences.get('max_duration', 300),
'min_confidence': 0.85,
'prioritize': 'quality_over_speed'
}
)

if not recommendations['recommendations']:
results.append({
'item_id': item['id'],
'success': False,
'error': 'No suitable workflows found'
})
continue

best_flow = recommendations['recommendations'][0]

try:
# Execute workflow asynchronously
execution_id = await self.client.execute_flow_async(
flow_id=best_flow['flow_id'],
context={
'content': item['content'],
'user_context': item.get('user_context', {}),
'processing_options': {
'priority': 'high',
'quality_level': 'premium'
}
},
options={
'monitoring': {
'enable_detailed_logging': True,
'send_progress_updates': True
},
'ai_options': {
'preferred_providers': ['ollama', 'openai'],
'cost_limit': best_flow['estimated_cost'] * 1.5
}
}
)

results.append({
'item_id': item['id'],
'execution_id': execution_id,
'estimated_completion': best_flow['estimated_duration'],
'status': 'processing'
})

except Exception as e:
results.append({
'item_id': item['id'],
'success': False,
'error': str(e)
})

return results

async def monitor_executions(self, execution_ids: List[str]) -> Dict[str, Dict]:
"""Monitor multiple workflow executions concurrently."""

async def get_status(execution_id):
return execution_id, await self.client.get_execution_status(
execution_id,
include_details=True,
include_predictions=True
)

# Get status for all executions concurrently
tasks = [get_status(eid) for eid in execution_ids]
status_results = await asyncio.gather(*tasks, return_exceptions=True)

statuses = {}
for result in status_results:
if isinstance(result, Exception):
continue
execution_id, status = result
statuses[execution_id] = status

return statuses

async def wait_for_completion(self,
execution_ids: List[str],
timeout: int = 1800,
progress_callback: Optional[callable] = None) -> Dict[str, Dict]:
"""Wait for multiple workflows to complete with progress monitoring."""

completed_results = {}
start_time = asyncio.get_event_loop().time()

while len(completed_results) < len(execution_ids):
current_time = asyncio.get_event_loop().time()
if current_time - start_time > timeout:
break

# Check status of pending executions
pending_ids = [eid for eid in execution_ids if eid not in completed_results]
statuses = await self.monitor_executions(pending_ids)

for execution_id, status in statuses.items():
if status['status'] in ['completed', 'failed', 'cancelled']:
completed_results[execution_id] = status
elif progress_callback:
progress_callback(execution_id, status)

# Wait before next check
await asyncio.sleep(10)

return completed_results

# Usage example
async def main():
manager = WorkflowManager(
api_token="your-api-token",
base_url="https://your-site.com/ai-workflows/api"
)

# Content batch for processing
content_items = [
{
'id': 'article_1',
'content': 'Technical article content...',
'type': 'technical_documentation',
'audience': 'developers',
'quality_metrics': {'readability': 6.2, 'seo_score': 45}
},
{
'id': 'article_2',
'content': 'Blog post content...',
'type': 'blog_post',
'audience': 'general',
'quality_metrics': {'readability': 7.8, 'seo_score': 62}
}
]

# Process content batch
results = await manager.process_content_batch(
content_items,
flow_preferences={
'budget_per_item': 0.75,
'max_duration': 240
}
)

# Extract execution IDs for monitoring
execution_ids = [r['execution_id'] for r in results if 'execution_id' in r]

# Monitor progress
def progress_update(execution_id, status):
print(f"Execution {execution_id}: {status['progress']['overall_percentage']:.1f}% complete")

# Wait for completion
final_results = await manager.wait_for_completion(
execution_ids,
timeout=1800,
progress_callback=progress_update
)

# Process results
for execution_id, result in final_results.items():
if result['status'] == 'completed':
print(f"βœ… Execution {execution_id} completed successfully")
print(f" Quality improvement: {result.get('quality_improvement', 'N/A')}")
print(f" Total cost: ${result.get('cost_tracking', {}).get('current_cost', 'N/A')}")
else:
print(f"❌ Execution {execution_id} failed: {result.get('error', 'Unknown error')}")

if __name__ == "__main__":
asyncio.run(main())

Support and Resources​

Developer Tools​

Support Channels​

Service Level Agreements​

  • Uptime: 99.9% availability guarantee
  • Response Time: < 200ms average for API calls
  • Support Response: < 4 hours for technical issues
  • Data Retention: 90 days for execution logs and results

Last Updated: 2025-01-24
API Version: 2.0.0
Documentation Version: 1.0.0