File size: 17,465 Bytes
5374a2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
"""
Business logic for agents, workflows, and executions.
"""
import logging
# import asyncio
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
from bson import ObjectId
from evoagentx.app.db import (
Database, # Agent, Workflow, WorkflowExecution, ExecutionLog,
AgentStatus, WorkflowStatus, ExecutionStatus
)
from evoagentx.app.schemas import (
AgentCreate, AgentUpdate, WorkflowCreate, WorkflowUpdate,
ExecutionCreate, PaginationParams, SearchParams
)
logger = logging.getLogger(__name__)
# Agent Service
class AgentService:
@staticmethod
async def create_agent(agent_data: AgentCreate, user_id: Optional[str] = None) -> Dict[str, Any]:
"""Create a new agent."""
agent_dict = agent_data.dict()
agent_dict["created_by"] = user_id
agent_dict["created_at"] = datetime.utcnow()
agent_dict["updated_at"] = agent_dict["created_at"]
agent_dict["status"] = AgentStatus.CREATED
# Validate agent exists with the same name
existing_agent = await Database.agents.find_one({"name": agent_dict["name"]})
if existing_agent:
raise ValueError(f"Agent with name '{agent_dict['name']}' already exists")
result = await Database.agents.insert_one(agent_dict)
agent_dict["_id"] = result.inserted_id
logger.info(f"Created agent {agent_dict['name']} with ID {result.inserted_id}")
return agent_dict
@staticmethod
async def get_agent(agent_id: str) -> Optional[Dict[str, Any]]:
"""Get an agent by ID."""
if not ObjectId.is_valid(agent_id):
raise ValueError(f"Invalid agent ID: {agent_id}")
agent = await Database.agents.find_one({"_id": ObjectId(agent_id)})
return agent
@staticmethod
async def get_agent_by_name(name: str) -> Optional[Dict[str, Any]]:
"""Get an agent by name."""
return await Database.agents.find_one({"name": name})
@staticmethod
async def update_agent(agent_id: str, agent_data: AgentUpdate) -> Optional[Dict[str, Any]]:
"""Update an agent."""
if not ObjectId.is_valid(agent_id):
raise ValueError(f"Invalid agent ID: {agent_id}")
agent = await Database.agents.find_one({"_id": ObjectId(agent_id)})
if not agent:
return None
update_data = agent_data.dict(exclude_unset=True)
update_data["updated_at"] = datetime.utcnow()
if "name" in update_data:
# Check if the new name already exists
existing = await Database.agents.find_one({
"name": update_data["name"],
"_id": {"$ne": ObjectId(agent_id)}
})
if existing:
raise ValueError(f"Agent with name '{update_data['name']}' already exists")
await Database.agents.update_one(
{"_id": ObjectId(agent_id)},
{"$set": update_data}
)
updated_agent = await Database.agents.find_one({"_id": ObjectId(agent_id)})
logger.info(f"Updated agent {agent_id}")
return updated_agent
@staticmethod
async def delete_agent(agent_id: str) -> bool:
"""Delete an agent."""
if not ObjectId.is_valid(agent_id):
raise ValueError(f"Invalid agent ID: {agent_id}")
# Check if agent is used in any workflows
workflow_count = await Database.workflows.count_documents({"agent_ids": agent_id})
if workflow_count > 0:
raise ValueError(f"Cannot delete agent {agent_id} as it is used in {workflow_count} workflows")
result = await Database.agents.delete_one({"_id": ObjectId(agent_id)})
if result.deleted_count:
logger.info(f"Deleted agent {agent_id}")
return True
return False
@staticmethod
async def list_agents(
params: PaginationParams,
search: Optional[SearchParams] = None
) -> Tuple[List[Dict[str, Any]], int]:
"""List agents with pagination and search."""
query = {}
if search:
if search.query:
query["$text"] = {"$search": search.query}
if search.tags:
query["tags"] = {"$all": search.tags}
if search.status:
query["status"] = search.status
if search.start_date and search.end_date:
query["created_at"] = {
"$gte": search.start_date,
"$lte": search.end_date
}
elif search.start_date:
query["created_at"] = {"$gte": search.start_date}
elif search.end_date:
query["created_at"] = {"$lte": search.end_date}
total = await Database.agents.count_documents(query)
cursor = Database.agents.find(query)\
.sort("created_at", -1)\
.skip(params.skip)\
.limit(params.limit)
agents = await cursor.to_list(length=params.limit)
return agents, total
# Workflow Service
class WorkflowService:
@staticmethod
async def create_workflow(workflow_data: WorkflowCreate, user_id: Optional[str] = None) -> Dict[str, Any]:
"""Create a new workflow."""
workflow_dict = workflow_data.dict()
workflow_dict["created_by"] = user_id
workflow_dict["created_at"] = datetime.utcnow()
workflow_dict["updated_at"] = workflow_dict["created_at"]
workflow_dict["status"] = WorkflowStatus.CREATED
workflow_dict["version"] = 1
# Extract agent IDs from the workflow definition
agent_ids = set()
# Extract agent IDs from steps
steps = workflow_dict["definition"].get("steps", [])
for step in steps:
if "agent_id" in step:
agent_id = step["agent_id"]
# Validate agent exists
agent = await AgentService.get_agent(agent_id)
if not agent:
raise ValueError(f"Agent with ID {agent_id} does not exist")
agent_ids.add(agent_id)
workflow_dict["agent_ids"] = list(agent_ids)
# Check for existing workflow with the same name
existing = await Database.workflows.find_one({"name": workflow_dict["name"]})
if existing:
raise ValueError(f"Workflow with name '{workflow_dict['name']}' already exists")
result = await Database.workflows.insert_one(workflow_dict)
workflow_dict["_id"] = result.inserted_id
logger.info(f"Created workflow {workflow_dict['name']} with ID {result.inserted_id}")
return workflow_dict
@staticmethod
async def get_workflow(workflow_id: str) -> Optional[Dict[str, Any]]:
"""Get a workflow by ID."""
if not ObjectId.is_valid(workflow_id):
raise ValueError(f"Invalid workflow ID: {workflow_id}")
workflow = await Database.workflows.find_one({"_id": ObjectId(workflow_id)})
return workflow
@staticmethod
async def get_workflow_by_name(name: str) -> Optional[Dict[str, Any]]:
"""Get a workflow by name."""
return await Database.workflows.find_one({"name": name})
@staticmethod
async def update_workflow(workflow_id: str, workflow_data: WorkflowUpdate) -> Optional[Dict[str, Any]]:
"""Update a workflow."""
if not ObjectId.is_valid(workflow_id):
raise ValueError(f"Invalid workflow ID: {workflow_id}")
workflow = await Database.workflows.find_one({"_id": ObjectId(workflow_id)})
if not workflow:
return None
update_data = workflow_data.dict(exclude_unset=True)
update_data["updated_at"] = datetime.utcnow()
# Update version if definition changes
if "definition" in update_data:
update_data["version"] = workflow.get("version", 1) + 1
# Extract agent IDs from the updated workflow definition
agent_ids = set()
steps = update_data["definition"].get("steps", [])
for step in steps:
if "agent_id" in step:
agent_id = step["agent_id"]
# Validate agent exists
agent = await AgentService.get_agent(agent_id)
if not agent:
raise ValueError(f"Agent with ID {agent_id} does not exist")
agent_ids.add(agent_id)
update_data["agent_ids"] = list(agent_ids)
# Check for name conflict if name is being updated
if "name" in update_data:
existing = await Database.workflows.find_one({
"name": update_data["name"],
"_id": {"$ne": ObjectId(workflow_id)}
})
if existing:
raise ValueError(f"Workflow with name '{update_data['name']}' already exists")
await Database.workflows.update_one(
{"_id": ObjectId(workflow_id)},
{"$set": update_data}
)
updated_workflow = await Database.workflows.find_one({"_id": ObjectId(workflow_id)})
logger.info(f"Updated workflow {workflow_id}")
return updated_workflow
@staticmethod
async def delete_workflow(workflow_id: str) -> bool:
"""Delete a workflow."""
if not ObjectId.is_valid(workflow_id):
raise ValueError(f"Invalid workflow ID: {workflow_id}")
# Check if workflow has any ongoing or recent executions
recent_executions = await Database.executions.count_documents({
"workflow_id": workflow_id,
"status": {"$in": [
ExecutionStatus.PENDING,
ExecutionStatus.RUNNING
]}
})
if recent_executions > 0:
raise ValueError(f"Cannot delete workflow {workflow_id} with {recent_executions} active executions")
result = await Database.workflows.delete_one({"_id": ObjectId(workflow_id)})
if result.deleted_count:
# Delete associated execution logs
await Database.logs.delete_many({"workflow_id": workflow_id})
await Database.executions.delete_many({"workflow_id": workflow_id})
logger.info(f"Deleted workflow {workflow_id}")
return True
return False
@staticmethod
async def list_workflows(
params: PaginationParams,
search: Optional[SearchParams] = None
) -> Tuple[List[Dict[str, Any]], int]:
"""List workflows with pagination and search."""
query = {}
if search:
if search.query:
query["$text"] = {"$search": search.query}
if search.tags:
query["tags"] = {"$all": search.tags}
if search.status:
query["status"] = search.status
if search.start_date and search.end_date:
query["created_at"] = {
"$gte": search.start_date,
"$lte": search.end_date
}
elif search.start_date:
query["created_at"] = {"$gte": search.start_date}
elif search.end_date:
query["created_at"] = {"$lte": search.end_date}
total = await Database.workflows.count_documents(query)
cursor = Database.workflows.find(query)\
.sort("created_at", -1)\
.skip(params.skip)\
.limit(params.limit)
workflows = await cursor.to_list(length=params.limit)
return workflows, total
# Workflow Execution Service
class WorkflowExecutionService:
@staticmethod
async def create_execution(execution_data: ExecutionCreate, user_id: Optional[str] = None) -> Dict[str, Any]:
"""Create a new workflow execution."""
# Validate workflow exists
workflow = await WorkflowService.get_workflow(execution_data.workflow_id)
if not workflow:
raise ValueError(f"Workflow {execution_data.workflow_id} not found")
# Prepare execution document
execution_dict = {
"workflow_id": execution_data.workflow_id,
"status": ExecutionStatus.PENDING,
"start_time": datetime.utcnow(),
"input_params": execution_data.input_params,
"created_by": user_id,
"created_at": datetime.utcnow(),
"step_results": {},
"current_step": None,
"results": {},
"error_message": None
}
# Insert execution record
result = await Database.executions.insert_one(execution_dict)
execution_dict["_id"] = result.inserted_id
logger.info(f"Created workflow execution {result.inserted_id}")
# Optional: Queue execution for async processing
# This would typically use a task queue like Celery
# await execute_workflow_async.delay(execution_dict)
return execution_dict
@staticmethod
async def get_execution(execution_id: str) -> Optional[Dict[str, Any]]:
"""Get a workflow execution by ID."""
if not ObjectId.is_valid(execution_id):
raise ValueError(f"Invalid execution ID: {execution_id}")
execution = await Database.executions.find_one({"_id": ObjectId(execution_id)})
return execution
@staticmethod
async def update_execution_status(execution_id: str, status: ExecutionStatus, error_message: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""Update execution status."""
if not ObjectId.is_valid(execution_id):
raise ValueError(f"Invalid execution ID: {execution_id}")
update_data = {
"status": status,
"updated_at": datetime.utcnow()
}
if status in [ExecutionStatus.COMPLETED, ExecutionStatus.FAILED, ExecutionStatus.CANCELLED]:
update_data["end_time"] = datetime.utcnow()
if error_message:
update_data["error_message"] = error_message
result = await Database.executions.find_one_and_update(
{"_id": ObjectId(execution_id)},
{"$set": update_data},
return_document=True
)
return result
@staticmethod
async def list_executions(
workflow_id: Optional[str] = None,
params: PaginationParams = PaginationParams(),
search: Optional[SearchParams] = None
) -> Tuple[List[Dict[str, Any]], int]:
"""List workflow executions with pagination and search."""
query = {}
if workflow_id:
query["workflow_id"] = workflow_id
if search:
if search.status:
query["status"] = search.status
if search.start_date and search.end_date:
query["created_at"] = {
"$gte": search.start_date,
"$lte": search.end_date
}
elif search.start_date:
query["created_at"] = {"$gte": search.start_date}
elif search.end_date:
query["created_at"] = {"$lte": search.end_date}
total = await Database.executions.count_documents(query)
cursor = Database.executions.find(query)\
.sort("created_at", -1)\
.skip(params.skip)\
.limit(params.limit)
executions = await cursor.to_list(length=params.limit)
return executions, total
@staticmethod
async def log_execution_event(
workflow_id: str,
execution_id: str,
message: str,
step_id: Optional[str] = None,
agent_id: Optional[str] = None,
level: str = "INFO",
details: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""Log an event in a workflow execution."""
log_entry = {
"workflow_id": workflow_id,
"execution_id": execution_id,
"step_id": step_id,
"agent_id": agent_id,
"timestamp": datetime.utcnow(),
"level": level,
"message": message,
"details": details or {}
}
result = await Database.logs.insert_one(log_entry)
log_entry["_id"] = result.inserted_id
return log_entry
@staticmethod
async def get_execution_logs(
execution_id: str,
params: PaginationParams = PaginationParams()
) -> Tuple[List[Dict[str, Any]], int]:
"""Retrieve logs for a specific execution."""
query = {"execution_id": execution_id}
total = await Database.logs.count_documents(query)
cursor = Database.logs.find(query)\
.sort("timestamp", 1)\
.skip(params.skip)\
.limit(params.limit)
logs = await cursor.to_list(length=params.limit)
return logs, total |