File size: 9,055 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc750c
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc750c
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
"""
Unified Knowledge Extraction Method (1-Task Approach)

Copied from core/agent_monitoring_unified.py and adapted for evaluation framework.
Uses the unified 1-task CrewAI approach with a single agent that performs all
knowledge extraction tasks in one step.
"""

# Import the LiteLLM fix FIRST, before any other imports that might use LiteLLM
import os
import sys

# Add the parent directory to the path to ensure imports work correctly
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
import json
import logging
import time
from datetime import datetime
from typing import Any, Dict

from crewai import Agent, Crew, Process, Task

from evaluation.knowledge_extraction.baselines.base_method import BaseKnowledgeExtractionMethod
from evaluation.knowledge_extraction.utils.models import KnowledgeGraph

# Import shared prompt templates
from evaluation.knowledge_extraction.utils.prompts import (
    ENTITY_EXTRACTION_INSTRUCTION_PROMPT,
    ENTITY_EXTRACTION_SYSTEM_PROMPT,
    GRAPH_BUILDER_SYSTEM_PROMPT,
    RELATION_EXTRACTION_INSTRUCTION_PROMPT,
    RELATION_EXTRACTION_SYSTEM_PROMPT,
)
from utils.fix_litellm_stop_param import *  # This applies the patches  # noqa: F403

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Set higher log levels for noisy libraries
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("litellm").setLevel(logging.WARNING)
logging.getLogger("chromadb").setLevel(logging.WARNING)

# Set default verbosity level
verbose_level = 0

# Set environment variables
os.environ["OPENAI_MODEL_NAME"] = "gpt-5-mini"

class UnifiedKnowledgeExtractionMethod(BaseKnowledgeExtractionMethod):
    """Unified 1-task knowledge extraction method using CrewAI."""
    
    def __init__(self, **kwargs):
        super().__init__("unified_method", **kwargs)
        self._setup_agent_and_task()
    
    def _setup_agent_and_task(self):
        """Set up the CrewAI agent and task."""
        
        # Create unified agent
        self.unified_knowledge_graph_agent = Agent(
            role="Unified Knowledge Graph Analyst",
            goal="Create comprehensive knowledge graphs from agent system data in a single analysis pass",
            backstory=f"""{ENTITY_EXTRACTION_SYSTEM_PROMPT}

{RELATION_EXTRACTION_SYSTEM_PROMPT}

{GRAPH_BUILDER_SYSTEM_PROMPT}.""",
            verbose=bool(verbose_level),
            llm=os.environ["OPENAI_MODEL_NAME"]
        )

        # Create unified task
        self.unified_knowledge_graph_task = Task(
            description=f"""
            Extract entities:
            {ENTITY_EXTRACTION_INSTRUCTION_PROMPT}
            
            Also extract relationships:
            {RELATION_EXTRACTION_INSTRUCTION_PROMPT}
            
            Finally, build the knowledge graph:
            """,
            agent=self.unified_knowledge_graph_agent,
            expected_output="A complete knowledge graph with entities, relations, and metadata",
            output_pydantic=KnowledgeGraph,
        )

        # Create crew
        self.unified_agent_monitoring_crew = Crew(
            agents=[self.unified_knowledge_graph_agent],
            tasks=[self.unified_knowledge_graph_task],
            verbose=bool(verbose_level),
            memory=False,
            planning=False,
            process=Process.sequential,
        )
    
    def process_text(self, text: str) -> Dict[str, Any]:
        """
        Process input text using the unified 1-task CrewAI approach.
        
        Args:
            text: Input text to process
            
        Returns:
            Dictionary with kg_data, metadata, success, and optional error
        """
        start_time = time.time()
        
        try:
            logger.info(f"process_text called with text length: {len(text)}")
            logger.info(f"text first 200 chars: {repr(text[:200])}")
            
            logger.info("Starting crew execution with input_data...")
            
            # Run the crew with proper input mechanism
            result = self.unified_agent_monitoring_crew.kickoff(inputs={"input_data": text})
            
            logger.info(f"Crew execution completed, result type: {type(result)}")
            
            processing_time = time.time() - start_time
            
            # Extract the knowledge graph from the result
            if hasattr(result, 'pydantic') and result.pydantic:
                kg_data = result.pydantic.dict()
            elif hasattr(result, 'raw'):
                # Try to parse as JSON
                try:
                    kg_data = json.loads(result.raw)
                except:  # noqa: E722
                    kg_data = {"entities": [], "relations": [], "error": "Failed to parse result"}
            else:
                kg_data = {"entities": [], "relations": [], "error": "Unknown result format"}
            
            # Validate kg_data structure
            if not isinstance(kg_data, dict):
                raise ValueError("kg_data is not a dict after parsing")
                
            if not ("entities" in kg_data and "relations" in kg_data):
                raise ValueError("kg_data missing 'entities' or 'relations'")
                
            # Add metadata
            if "metadata" not in kg_data:
                kg_data["metadata"] = {}
                
            kg_data["metadata"]["processing_info"] = {
                "method": "unified_single_task",
                "processing_time_seconds": processing_time,
                "processed_at": datetime.now().isoformat(),
                "agent_count": 1,
                "task_count": 1,
                "api_calls": 1
            }
            
            # Calculate statistics
            entity_count = len(kg_data.get("entities", []))
            relation_count = len(kg_data.get("relations", []))
            
            return {
                "success": True,
                "kg_data": kg_data,
                "metadata": {
                    "approach": "unified_1_task",
                    "tasks_executed": 1,
                    "agents_used": 1,
                    "method": self.method_name,
                    "processing_time_seconds": processing_time,
                    "entity_count": entity_count,
                    "relation_count": relation_count,
                    "entities_per_second": entity_count / processing_time if processing_time > 0 else 0,
                    "relations_per_second": relation_count / processing_time if processing_time > 0 else 0,
                    "api_calls": 1
                }
            }
            
        except Exception as e:
            processing_time = time.time() - start_time
            logger.error(f"Error in unified knowledge extraction method: {e}")
            logger.error(f"Error type: {type(e).__name__}")
            import traceback
            logger.error(f"Traceback: {traceback.format_exc()}")
            return {
                "success": False,
                "error": str(e),
                "kg_data": {"entities": [], "relations": []},
                "metadata": {
                    "approach": "unified_1_task",
                    "tasks_executed": 0,
                    "agents_used": 0,
                    "method": self.method_name,
                    "processing_time_seconds": processing_time,
                    "api_calls": 1
                }
            }
    
    def extract_knowledge_graph(self, trace_data: str) -> Dict[str, Any]:
        """
        Extract knowledge graph from trace data.
        
        Args:
            trace_data: Agent trace data as JSON string
            
        Returns:
            Dictionary with entities and relations
        """
        try:
            # Debug logging
            logger.info(f"extract_knowledge_graph called with trace_data type: {type(trace_data)}")
            if isinstance(trace_data, str):
                logger.info(f"trace_data length: {len(trace_data)}")
                logger.info(f"trace_data first 200 chars: {repr(trace_data[:200])}")
            
            # Pass the JSON string directly to process_text without re-encoding
            result = self.process_text(trace_data)
            
            # Return just the knowledge graph data
            if result.get("success", False):
                return result.get("kg_data", {"entities": [], "relations": []})
            else:
                # Return empty knowledge graph on failure
                return {"entities": [], "relations": []}
                
        except Exception as e:
            logger.error(f"Error in extract_knowledge_graph: {e}")
            logger.error(f"trace_data type: {type(trace_data)}")
            if isinstance(trace_data, str):
                logger.error(f"trace_data content (first 200 chars): {repr(trace_data[:200])}")
            return {"entities": [], "relations": []}