wu981526092 commited on
Commit
edf083b
·
1 Parent(s): 7e807a3
agentgraph/shared/models/reference_based/failure.py CHANGED
@@ -20,4 +20,4 @@ class Failure(BaseModel):
20
  description: str = Field(..., description="One-sentence explanation of the failure")
21
  raw_text: str = Field("", description="Exact snippet of trace text that evidences the failure (can be left blank and recovered via raw_text_ref)")
22
  raw_text_ref: List[ContentReference] = Field(..., description="List of references to every occurrence of the failure evidence in the trace")
23
- affected_id: Optional[str] = Field(None, description="ID of related Entity or Relation responsible for or impacted by the failure")
 
20
  description: str = Field(..., description="One-sentence explanation of the failure")
21
  raw_text: str = Field("", description="Exact snippet of trace text that evidences the failure (can be left blank and recovered via raw_text_ref)")
22
  raw_text_ref: List[ContentReference] = Field(..., description="List of references to every occurrence of the failure evidence in the trace")
23
+ affected_id: str = Field(..., description="ID of related Entity or Relation responsible for or impacted by the failure")
agentgraph/shared/models/reference_based/optimization_recommendation.py CHANGED
@@ -19,4 +19,4 @@ class OptimizationRecommendation(BaseModel):
19
  recommendation_type: RecommendationType = Field(..., description="The category of optimization being suggested")
20
  description: str = Field(..., description="A detailed, human-readable explanation of the recommendation, including the observed pattern and the justification for the change.")
21
  affected_ids: List[str] = Field(default_factory=list, description="A list of Entity or Relation IDs that are the focus of this recommendation")
22
- raw_text_ref: Optional[List[ContentReference]] = Field(default=None, description="Optional list of references to the exact trace locations related to this recommendation")
 
19
  recommendation_type: RecommendationType = Field(..., description="The category of optimization being suggested")
20
  description: str = Field(..., description="A detailed, human-readable explanation of the recommendation, including the observed pattern and the justification for the change.")
21
  affected_ids: List[str] = Field(default_factory=list, description="A list of Entity or Relation IDs that are the focus of this recommendation")
22
+ raw_text_ref: List[ContentReference] = Field(default_factory=list, description="List of references to the exact trace locations related to this recommendation")
agentgraph/shared/models/reference_based/report.py CHANGED
@@ -12,5 +12,5 @@ class KnowledgeGraph(BaseModel):
12
  system_summary: str = Field("", description="A short 2-3 sentence summary of the agent system's purpose and structure")
13
  entities: List[Entity] = Field(default_factory=list, description="List of entities in the knowledge graph")
14
  relations: List[Relation] = Field(default_factory=list, description="List of relations in the knowledge graph")
15
- failures: Optional[List['Failure']] = Field(default=None, description="Optional list of detected risk or failure events across the trace")
16
- optimizations: Optional[List[OptimizationRecommendation]] = Field(default=None, description="Optional list of recommendations for optimizing the agent system")
 
12
  system_summary: str = Field("", description="A short 2-3 sentence summary of the agent system's purpose and structure")
13
  entities: List[Entity] = Field(default_factory=list, description="List of entities in the knowledge graph")
14
  relations: List[Relation] = Field(default_factory=list, description="List of relations in the knowledge graph")
15
+ failures: List[Failure] = Field(default_factory=list, description="List of detected risk or failure events across the trace")
16
+ optimizations: List[OptimizationRecommendation] = Field(default_factory=list, description="List of recommendations for optimizing the agent system")
simple_test.py DELETED
@@ -1,72 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Simple test to verify OpenAI structured outputs functionality
4
- """
5
-
6
- import os
7
- from dotenv import load_dotenv
8
- from openai import OpenAI
9
- from pydantic import BaseModel
10
- from typing import List
11
-
12
- # Load environment variables
13
- load_dotenv('/Users/zekunwu/Desktop/agent_monitoring/.env')
14
-
15
- class SimpleEntity(BaseModel):
16
- name: str
17
- type: str
18
-
19
- class SimpleKG(BaseModel):
20
- entities: List[SimpleEntity]
21
- system_name: str
22
-
23
- def test_basic_openai():
24
- """Test basic OpenAI structured outputs"""
25
-
26
- # Check if API key exists
27
- api_key = os.getenv("OPENAI_API_KEY")
28
- if not api_key:
29
- print("❌ OPENAI_API_KEY not found in environment")
30
- return False
31
-
32
- if api_key == "your_openai_api_key_here":
33
- print("❌ Please set a real OpenAI API key in .env file")
34
- return False
35
-
36
- print(f"✅ API key found: {api_key[:10]}...")
37
-
38
- try:
39
- client = OpenAI(api_key=api_key)
40
-
41
- response = client.responses.parse(
42
- model="gpt-4o-2024-08-06",
43
- input=[
44
- {"role": "system", "content": "Extract entities from text."},
45
- {"role": "user", "content": "Alice the manager uses Excel tool to analyze data."}
46
- ],
47
- text_format=SimpleKG,
48
- )
49
-
50
- result = response.output_parsed
51
- print(f"✅ OpenAI API call successful!")
52
- print(f"System: {result.system_name}")
53
- print(f"Entities: {len(result.entities)}")
54
- for entity in result.entities:
55
- print(f" - {entity.type}: {entity.name}")
56
-
57
- return True
58
-
59
- except Exception as e:
60
- print(f"❌ OpenAI API call failed: {e}")
61
- return False
62
-
63
- if __name__ == "__main__":
64
- print("🧪 Testing Basic OpenAI Structured Outputs")
65
- print("=" * 50)
66
-
67
- success = test_basic_openai()
68
-
69
- if success:
70
- print("\n🎉 Basic test passed! Ready to use OpenAI structured outputs.")
71
- else:
72
- print("\n💥 Basic test failed. Please check your OpenAI API key.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_simple_kg.py DELETED
@@ -1,110 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Test with simplified KnowledgeGraph model
4
- """
5
-
6
- import os
7
- import sys
8
- from dotenv import load_dotenv
9
- from openai import OpenAI
10
- from pydantic import BaseModel, Field
11
- from typing import List, Optional
12
-
13
- # Load environment variables
14
- load_dotenv('/Users/zekunwu/Desktop/agent_monitoring/.env')
15
-
16
- # Simplified models
17
- class SimpleEntity(BaseModel):
18
- id: str
19
- type: str # Agent, Task, Tool, Input, Output, Human
20
- name: str
21
- importance: str # HIGH, MEDIUM, LOW
22
-
23
- class SimpleRelation(BaseModel):
24
- id: str
25
- source: str
26
- target: str
27
- type: str # PERFORMS, USES, etc.
28
- importance: str
29
-
30
- class SimpleKnowledgeGraph(BaseModel):
31
- system_name: str = Field("", description="Name of the system")
32
- system_summary: str = Field("", description="Summary of the system")
33
- entities: List[SimpleEntity] = Field(default_factory=list)
34
- relations: List[SimpleRelation] = Field(default_factory=list)
35
-
36
- def test_simple_kg():
37
- """Test with simplified KG model"""
38
-
39
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
40
-
41
- test_input = """
42
- Assistant: I'll help you analyze the customer data to find purchasing patterns.
43
-
44
- Action: load_data
45
- Action Input: {"dataset": "customer_purchases.csv"}
46
- Observation: Data loaded successfully. Found 10,000 customer records.
47
-
48
- Action: analyze_patterns
49
- Action Input: {"columns": ["purchase_amount", "product_category", "customer_age"]}
50
- Observation: Analysis complete. Found strong correlation between age and product preferences.
51
-
52
- Final Answer: Based on the analysis, customers aged 25-35 prefer electronics.
53
- """
54
-
55
- system_prompt = """Extract a knowledge graph with these entity types:
56
- - Agent: AI agents
57
- - Task: Specific tasks
58
- - Tool: Tools or functions
59
- - Input: Data inputs
60
- - Output: Data outputs
61
- - Human: Human users
62
-
63
- Use these relationship types:
64
- - PERFORMS: Agent→Task
65
- - USES: Agent→Tool
66
- - PRODUCES: Task→Output
67
-
68
- Create entities with IDs like agent_001, task_001, etc."""
69
-
70
- try:
71
- print("🧪 Testing Simplified Knowledge Graph Extraction")
72
- print("=" * 60)
73
-
74
- response = client.responses.parse(
75
- model="gpt-4o-2024-08-06",
76
- input=[
77
- {"role": "system", "content": system_prompt},
78
- {"role": "user", "content": f"Extract knowledge graph from: {test_input}"}
79
- ],
80
- text_format=SimpleKnowledgeGraph,
81
- )
82
-
83
- kg = response.output_parsed
84
-
85
- print(f"✅ Extraction successful!")
86
- print(f"📊 System: {kg.system_name}")
87
- print(f"📝 Summary: {kg.system_summary}")
88
- print(f"🔢 Entities: {len(kg.entities)}")
89
- print(f"🔗 Relations: {len(kg.relations)}")
90
-
91
- print("\n📋 Entities:")
92
- for entity in kg.entities:
93
- print(f" - {entity.id}: {entity.type} - {entity.name} ({entity.importance})")
94
-
95
- print("\n🔗 Relations:")
96
- for relation in kg.relations:
97
- print(f" - {relation.id}: {relation.source} → {relation.target} ({relation.type})")
98
-
99
- return True
100
-
101
- except Exception as e:
102
- print(f"❌ Test failed: {e}")
103
- return False
104
-
105
- if __name__ == "__main__":
106
- success = test_simple_kg()
107
- if success:
108
- print("\n🎉 Simplified KG test passed!")
109
- else:
110
- print("\n💥 Simplified KG test failed.")