import requests
from typing import Dict, Any, Optional, Union
def update_graph_rag_configuration(
flow_name: str,
node_id: str,
config: Dict[str, Any],
api_token: str
) -> Dict[str, Any]:
"""Update graph RAG node configuration"""
url = f"https://{flow_name}.flows.graphorlm.com/graph-rag/{node_id}"
headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
payload = {"config": config}
response = requests.patch(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()
class GraphRagConfigurationManager:
"""Advanced Graph RAG configuration management with knowledge graph optimization"""
def __init__(self, flow_name: str, api_token: str):
self.flow_name = flow_name
self.api_token = api_token
self.strategies = {
'precision': {
'topK': 8,
'description': 'High-precision entity matching',
'use_cases': ['Expert systems', 'Critical decisions', 'Real-time applications'],
'resource_level': 'low',
'entity_coverage': 'focused'
},
'balanced': {
'topK': 15,
'description': 'Balanced entity coverage and performance',
'use_cases': ['General knowledge', 'Business intelligence', 'Education'],
'resource_level': 'medium',
'entity_coverage': 'moderate'
},
'comprehensive': {
'topK': 30,
'description': 'Thorough knowledge graph exploration',
'use_cases': ['Research', 'Complex analysis', 'Investigation'],
'resource_level': 'high',
'entity_coverage': 'extensive'
},
'unlimited': {
'topK': None,
'description': 'Complete knowledge graph analysis',
'use_cases': ['Exhaustive research', 'Complete analysis', 'Discovery'],
'resource_level': 'maximum',
'entity_coverage': 'complete'
}
}
def update_strategy(self, node_id: str, strategy: str) -> Dict[str, Any]:
"""Update Graph RAG node to a specific strategy"""
if strategy not in self.strategies:
available = ', '.join(self.strategies.keys())
raise ValueError(f"Invalid strategy '{strategy}'. Available: {available}")
strategy_config = self.strategies[strategy]
config = {'topK': strategy_config['topK']}
print(f"🧠 Updating Graph RAG node {node_id}")
print(f" Strategy: {strategy}")
print(f" Top K: {strategy_config['topK'] or 'unlimited'}")
print(f" Description: {strategy_config['description']}")
print(f" Resource Level: {strategy_config['resource_level']}")
print(f" Entity Coverage: {strategy_config['entity_coverage']}")
try:
result = update_graph_rag_configuration(
self.flow_name, node_id, config, self.api_token
)
print(f"✅ {result['message']}")
return result
except requests.exceptions.HTTPError as e:
print(f"❌ Update failed: {e}")
raise
def analyze_strategy_impact(self, current_top_k: Optional[int], target_strategy: str) -> Dict[str, Any]:
"""Analyze the impact of changing to a target strategy"""
target_config = self.strategies[target_strategy]
target_top_k = target_config['topK']
# Determine current strategy
current_strategy = 'unknown'
for name, config in self.strategies.items():
if config['topK'] == current_top_k:
current_strategy = name
break
# Calculate impact
impact_analysis = {
'current_strategy': current_strategy,
'current_top_k': current_top_k,
'target_strategy': target_strategy,
'target_top_k': target_top_k,
'changes': [],
'recommendations': []
}
# Analyze changes
if current_top_k is None and target_top_k is not None:
impact_analysis['changes'].append("Switching from unlimited to limited processing")
impact_analysis['recommendations'].append("Monitor knowledge coverage after change")
elif current_top_k is not None and target_top_k is None:
impact_analysis['changes'].append("Switching to unlimited processing")
impact_analysis['recommendations'].append("Ensure adequate system resources")
elif current_top_k and target_top_k:
if target_top_k > current_top_k:
increase = target_top_k - current_top_k
impact_analysis['changes'].append(f"Increasing Top K by {increase} (+{(increase/current_top_k)*100:.1f}%)")
impact_analysis['recommendations'].append("Expect increased resource usage and processing time")
elif target_top_k < current_top_k:
decrease = current_top_k - target_top_k
impact_analysis['changes'].append(f"Decreasing Top K by {decrease} (-{(decrease/current_top_k)*100:.1f}%)")
impact_analysis['recommendations'].append("Monitor for potential knowledge coverage reduction")
# Resource impact analysis
current_level = next((config['resource_level'] for config in self.strategies.values()
if config['topK'] == current_top_k), 'unknown')
target_level = target_config['resource_level']
if current_level != target_level:
impact_analysis['changes'].append(f"Resource usage changing from {current_level} to {target_level}")
return impact_analysis
def print_strategy_comparison(self):
"""Print a comparison table of all available strategies"""
print("🎯 Graph RAG Configuration Strategies Comparison")
print("=" * 80)
print(f"{'Strategy':<15} {'Top K':<10} {'Resource':<10} {'Coverage':<12} {'Best For'}")
print("-" * 80)
for name, config in self.strategies.items():
top_k_str = str(config['topK']) if config['topK'] is not None else 'unlimited'
use_case = config['use_cases'][0] if config['use_cases'] else ''
print(f"{name:<15} {top_k_str:<10} {config['resource_level']:<10} "
f"{config['entity_coverage']:<12} {use_case}")
def recommend_strategy(self,
entity_density: float = None,
relationship_ratio: float = None,
processing_time_constraint: bool = False,
resource_constraint: bool = False) -> str:
"""Recommend a strategy based on knowledge graph metrics and constraints"""
print("🔍 Analyzing Graph RAG requirements for strategy recommendation...")
# Start with balanced as default
recommended = 'balanced'
reasoning = []
# Analyze entity density if provided
if entity_density is not None:
if entity_density > 5.0:
recommended = 'precision'
reasoning.append("High entity density suggests precision strategy")
elif entity_density < 1.5:
recommended = 'comprehensive'
reasoning.append("Low entity density suggests comprehensive strategy")
# Analyze relationship ratio if provided
if relationship_ratio is not None:
if relationship_ratio > 2.0:
# Rich relationships suggest comprehensive approach might be beneficial
if recommended != 'precision': # Don't override precision if already set
recommended = 'comprehensive'
reasoning.append("High relationship ratio suggests comprehensive exploration")
# Apply constraints
if processing_time_constraint:
if recommended in ['comprehensive', 'unlimited']:
recommended = 'balanced'
reasoning.append("Processing time constraint limits strategy to balanced or precision")
if resource_constraint:
if recommended in ['comprehensive', 'unlimited']:
recommended = 'precision'
reasoning.append("Resource constraint requires precision strategy")
print(f"💡 Recommended strategy: {recommended}")
if reasoning:
print(" Reasoning:")
for reason in reasoning:
print(f" • {reason}")
strategy_info = self.strategies[recommended]
print(f" Top K: {strategy_info['topK'] or 'unlimited'}")
print(f" Description: {strategy_info['description']}")
return recommended
# Usage examples
manager = GraphRagConfigurationManager("my-rag-pipeline", "YOUR_API_TOKEN")
# Print strategy comparison
manager.print_strategy_comparison()
# Update to a specific strategy
try:
result = manager.update_strategy("graph-rag-1748287628685", "comprehensive")
print(f"Configuration updated: {result}")
except Exception as e:
print(f"Error updating configuration: {e}")
# Analyze strategy impact
impact = manager.analyze_strategy_impact(15, "comprehensive")
print("\n📊 Strategy Impact Analysis:")
for change in impact['changes']:
print(f" • {change}")
for rec in impact['recommendations']:
print(f" 💡 {rec}")
# Get strategy recommendation
recommended = manager.recommend_strategy(
entity_density=2.5,
relationship_ratio=1.8,
processing_time_constraint=False,
resource_constraint=False
)