Spaces:
Build error
Build error
File size: 5,822 Bytes
e20bd8e | 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 | import logging
from pathlib import Path
import json
import redis
from datetime import datetime
from typing import Dict, Any, List
import os
logger = logging.getLogger(__name__)
class LangGraphNode:
"""Centralized node for task orchestration and state management"""
def __init__(self, redis_url: str = None):
self.redis_url = redis_url or os.getenv('REDIS_URL', 'redis://localhost:6379/0')
self.redis = redis.from_url(self.redis_url)
self.base_path = Path(__file__).parent.parent
# Initialize storage
self._init_storage()
def _init_storage(self):
"""Initialize Redis storage with required keys"""
if not self.redis.exists('tasks'):
self.redis.set('tasks', json.dumps({}))
if not self.redis.exists('tools'):
self.redis.set('tools', json.dumps({}))
if not self.redis.exists('agent_states'):
self.redis.set('agent_states', json.dumps({}))
def register_task(self, task_id: str, description: str, assigned_agent: str) -> Dict:
"""Register a new task in the system"""
try:
tasks = json.loads(self.redis.get('tasks'))
tasks[task_id] = {
'description': description,
'assigned_agent': assigned_agent,
'status': 'pending',
'created_at': datetime.now().isoformat(),
'updated_at': datetime.now().isoformat(),
'dependencies': [],
'outputs': {}
}
self.redis.set('tasks', json.dumps(tasks))
return tasks[task_id]
except Exception as e:
logger.error(f"Error registering task: {str(e)}")
raise
def update_task_status(self, task_id: str, status: str, output: Dict = None) -> Dict:
"""Update task status and optional output"""
try:
tasks = json.loads(self.redis.get('tasks'))
if task_id not in tasks:
raise ValueError(f"Task {task_id} not found")
tasks[task_id]['status'] = status
tasks[task_id]['updated_at'] = datetime.now().isoformat()
if output:
tasks[task_id]['outputs'] = output
self.redis.set('tasks', json.dumps(tasks))
return tasks[task_id]
except Exception as e:
logger.error(f"Error updating task: {str(e)}")
raise
def get_task_state(self, task_id: str) -> Dict:
"""Get current state of a task"""
try:
tasks = json.loads(self.redis.get('tasks'))
if task_id not in tasks:
raise ValueError(f"Task {task_id} not found")
return tasks[task_id]
except Exception as e:
logger.error(f"Error getting task state: {str(e)}")
raise
def register_tool(self, tool_name: str, tool_config: Dict) -> Dict:
"""Register a new tool in the registry"""
try:
tools = json.loads(self.redis.get('tools'))
tools[tool_name] = {
**tool_config,
'registered_at': datetime.now().isoformat()
}
self.redis.set('tools', json.dumps(tools))
return tools[tool_name]
except Exception as e:
logger.error(f"Error registering tool: {str(e)}")
raise
def get_tool(self, tool_name: str) -> Dict:
"""Get tool configuration from registry"""
try:
tools = json.loads(self.redis.get('tools'))
if tool_name not in tools:
raise ValueError(f"Tool {tool_name} not found")
return tools[tool_name]
except Exception as e:
logger.error(f"Error getting tool: {str(e)}")
raise
def log_tool_usage(self, agent_id: str, tool_name: str, input_data: Dict, output_data: Dict) -> Dict:
"""Log tool usage for monitoring"""
try:
log_entry = {
'agent_id': agent_id,
'tool_name': tool_name,
'input_data': input_data,
'output_data': output_data,
'timestamp': datetime.now().isoformat()
}
# Store in Redis list with TTL (30 days)
key = f"tool_logs:{tool_name}"
self.redis.lpush(key, json.dumps(log_entry))
self.redis.expire(key, 2592000) # 30 days in seconds
return log_entry
except Exception as e:
logger.error(f"Error logging tool usage: {str(e)}")
raise
def update_agent_state(self, agent_id: str, state: Dict) -> Dict:
"""Update agent's persistent state"""
try:
states = json.loads(self.redis.get('agent_states'))
states[agent_id] = {
**state,
'updated_at': datetime.now().isoformat()
}
self.redis.set('agent_states', json.dumps(states))
return states[agent_id]
except Exception as e:
logger.error(f"Error updating agent state: {str(e)}")
raise
def get_agent_state(self, agent_id: str) -> Dict:
"""Get agent's persistent state"""
try:
states = json.loads(self.redis.get('agent_states'))
return states.get(agent_id, {})
except Exception as e:
logger.error(f"Error getting agent state: {str(e)}")
raise
_instance = None
def get_langgraph_node():
"""Get or create singleton instance of LangGraphNode"""
global _instance
if _instance is None:
_instance = LangGraphNode()
return _instance |