Skip to content

Self-improving AI Employees for everyone

feat: Add centralized API cost tracking for Google Maps

trohitg91375b570166
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index eff07e17..b66e8485 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -64,7 +64,7 @@ interface CredentialItem {
Icon?: React.FC<{ size?: number }>;
CustomIcon?: React.FC;
isSpecial?: boolean;
- panelType?: 'whatsapp' | 'android' | 'twitter';
+ panelType?: 'whatsapp' | 'android' | 'twitter' | 'google_maps';
}
interface Category {
@@ -105,7 +105,7 @@ const CATEGORIES: Category[] = [
key: 'services',
label: 'Services',
items: [
- { id: 'google_maps', name: 'Google Maps', placeholder: 'AIza...', color: '#EA4335', desc: 'Geocoding, Places, Directions', CustomIcon: GoogleMapsIcon },
+ { id: 'google_maps', name: 'Google Maps', placeholder: 'AIza...', color: '#EA4335', desc: 'Geocoding, Places, Directions', CustomIcon: GoogleMapsIcon, panelType: 'google_maps' },
],
},
];
@@ -157,9 +157,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
const [usageLoading, setUsageLoading] = useState(false);
const [usageExpanded, setUsageExpanded] = useState(false);
- // Twitter API usage state
- const [twitterUsage, setTwitterUsage] = useState<APIUsageSummary | null>(null);
- const [twitterUsageLoading, setTwitterUsageLoading] = useState(false);
+ // API usage state (for Twitter, Google Maps, etc.)
+ const [apiUsage, setApiUsage] = useState<Record<string, APIUsageSummary | null>>({});
+ const [apiUsageLoading, setApiUsageLoading] = useState<Record<string, boolean>>({});
// Load stored keys and proxy URLs
const loadKeys = useCallback(async () => {
@@ -257,26 +257,29 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [usageExpanded, isConnected, loadUsageSummary]);
- // Load Twitter API usage when Twitter panel is selected
- const loadTwitterUsage = useCallback(async () => {
+ // Load API usage for services (Twitter, Google Maps, etc.)
+ const loadApiUsage = useCallback(async (service: string) => {
if (!isConnected) return;
- setTwitterUsageLoading(true);
+ setApiUsageLoading(l => ({ ...l, [service]: true }));
try {
- const services = await getAPIUsageSummary('twitter');
- const twitter = services.find(s => s.service === 'twitter') || null;
- setTwitterUsage(twitter);
+ const services = await getAPIUsageSummary(service);
+ const usage = services.find(s => s.service === service) || null;
+ setApiUsage(u => ({ ...u, [service]: usage }));
} catch (error) {
- console.warn('Error loading Twitter usage:', error);
+ console.warn(`Error loading ${service} usage:`, error);
} finally {
- setTwitterUsageLoading(false);
+ setApiUsageLoading(l => ({ ...l, [service]: false }));
}
}, [getAPIUsageSummary, isConnected]);
useEffect(() => {
- if (selectedItem?.panelType === 'twitter' && isConnected) {
- loadTwitterUsage();
+ const panelType = selectedItem?.panelType;
+ if (panelType === 'twitter' && isConnected) {
+ loadApiUsage('twitter');
+ } else if (panelType === 'google_maps' && isConnected) {
+ loadApiUsage('google_maps');
}
- }, [selectedItem, isConnected, loadTwitterUsage]);
+ }, [selectedItem, isConnected, loadApiUsage]);
const handleValidate = async (id: string) => {
const key = keys[id];
@@ -710,6 +713,112 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
}
}, [selectedItem, whatsappStatus.connected, rateLimitExpanded, loadRateLimits]);
+ // Render API usage panel for services (Twitter, Google Maps, etc.)
+ const renderApiUsagePanel = (service: string, serviceName: string) => (
+ <Collapse
+ style={{ marginBottom: theme.spacing.lg, background: 'transparent' }}
+ items={[{
+ key: `${service}-usage`,
+ label: (
+ <Space>
+ <DollarOutlined style={{ color: theme.dracula.yellow }} />
+ <span>API Usage & Costs</span>
+ {apiUsage[service] && (
+ <Tag style={{
+ backgroundColor: `${theme.dracula.green}25`,
+ borderColor: `${theme.dracula.green}60`,
+ color: theme.dracula.green,
+ }}>
+ ${apiUsage[service]!.total_cost.toFixed(4)}
+ </Tag>
+ )}
+ </Space>
+ ),
+ children: apiUsageLoading[service] ? (
+ <div style={{ textAlign: 'center', padding: 16 }}><Spin size="small" /></div>
+ ) : apiUsage[service] ? (
+ <div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: theme.spacing.md,
+ marginBottom: theme.spacing.md,
+ }}>
+ <Statistic
+ title="Total Cost"
+ value={apiUsage[service]!.total_cost}
+ precision={4}
+ prefix="$"
+ valueStyle={{ color: theme.dracula.green, fontSize: 18 }}
+ />
+ <Statistic
+ title="API Calls"
+ value={apiUsage[service]!.execution_count}
+ valueStyle={{ color: theme.dracula.cyan, fontSize: 18 }}
+ />
+ <Statistic
+ title="Resources"
+ value={apiUsage[service]!.total_resources}
+ valueStyle={{ color: theme.dracula.purple, fontSize: 18 }}
+ />
+ </div>
+ {apiUsage[service]!.operations?.length > 0 && (
+ <div style={{
+ borderTop: `1px solid ${theme.colors.border}`,
+ paddingTop: theme.spacing.md,
+ }}>
+ <div style={{
+ fontSize: theme.fontSize.xs,
+ color: theme.colors.textSecondary,
+ marginBottom: theme.spacing.sm,
+ }}>
+ Operations Breakdown
+ </div>
+ {apiUsage[service]!.operations.map(op => (
+ <div
+ key={op.operation}
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ padding: '4px 0',
+ borderBottom: `1px solid ${theme.colors.border}`,
+ }}
+ >
+ <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{op.operation}</span>
+ <Space size="small">
+ <Tag style={{ margin: 0 }}>{op.resource_count} resources</Tag>
+ <Tag style={{
+ margin: 0,
+ backgroundColor: `${theme.dracula.green}15`,
+ color: theme.dracula.green,
+ border: 'none',
+ }}>
+ ${op.total_cost.toFixed(4)}
+ </Tag>
+ </Space>
+ </div>
+ ))}
+ </div>
+ )}
+ <Button
+ size="small"
+ icon={<ReloadOutlined />}
+ onClick={() => loadApiUsage(service)}
+ style={{ marginTop: theme.spacing.md }}
+ >
+ Refresh
+ </Button>
+ </div>
+ ) : (
+ <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 16 }}>
+ No usage data yet. Use {serviceName} nodes in your workflows to track costs.
+ </div>
+ ),
+ }]}
+ />
+ );
+
// Render detail panel for selected item
const renderDetailPanel = () => {
if (!selectedItem) {
@@ -1348,110 +1457,7 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
)}
{/* API Usage Stats */}
- <Collapse
- style={{ marginBottom: theme.spacing.lg, background: 'transparent' }}
- items={[{
- key: 'twitter-usage',
- label: (
- <Space>
- <DollarOutlined style={{ color: theme.dracula.yellow }} />
- <span>API Usage & Costs</span>
- {twitterUsage && (
- <Tag style={{
- backgroundColor: `${theme.dracula.green}25`,
- borderColor: `${theme.dracula.green}60`,
- color: theme.dracula.green,
- }}>
- ${twitterUsage.total_cost.toFixed(4)}
- </Tag>
- )}
- </Space>
- ),
- children: twitterUsageLoading ? (
- <div style={{ textAlign: 'center', padding: 16 }}><Spin size="small" /></div>
- ) : twitterUsage ? (
- <div>
- {/* Summary stats */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(3, 1fr)',
- gap: theme.spacing.md,
- marginBottom: theme.spacing.md,
- }}>
- <Statistic
- title="Total Cost"
- value={twitterUsage.total_cost}
- precision={4}
- prefix="$"
- valueStyle={{ color: theme.dracula.green, fontSize: 18 }}
- />
- <Statistic
- title="API Calls"
- value={twitterUsage.execution_count}
- valueStyle={{ color: theme.dracula.cyan, fontSize: 18 }}
- />
- <Statistic
- title="Resources"
- value={twitterUsage.total_resources}
- valueStyle={{ color: theme.dracula.purple, fontSize: 18 }}
- />
- </div>
- {/* Operations breakdown */}
- {twitterUsage.operations && twitterUsage.operations.length > 0 && (
- <div style={{
- borderTop: `1px solid ${theme.colors.border}`,
- paddingTop: theme.spacing.md,
- }}>
- <div style={{
- fontSize: theme.fontSize.xs,
- color: theme.colors.textSecondary,
- marginBottom: theme.spacing.sm,
- }}>
- Operations Breakdown
- </div>
- {twitterUsage.operations.map(op => (
- <div
- key={op.operation}
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- padding: '4px 0',
- borderBottom: `1px solid ${theme.colors.border}`,
- }}
- >
- <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{op.operation}</span>
- <Space size="small">
- <Tag style={{ margin: 0 }}>{op.resource_count} resources</Tag>
- <Tag style={{
- margin: 0,
- backgroundColor: `${theme.dracula.green}15`,
- color: theme.dracula.green,
- border: 'none',
- }}>
- ${op.total_cost.toFixed(4)}
- </Tag>
- </Space>
- </div>
- ))}
- </div>
- )}
- <Button
- size="small"
- icon={<ReloadOutlined />}
- onClick={loadTwitterUsage}
- style={{ marginTop: theme.spacing.md }}
- >
- Refresh
- </Button>
- </div>
- ) : (
- <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 16 }}>
- No usage data yet. Use Twitter nodes in your workflows to track costs.
- </div>
- ),
- }]}
- />
+ {renderApiUsagePanel('twitter', 'Twitter')}
{/* Info box */}
<div style={{
@@ -1945,6 +1951,9 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {
</div>
)}
+ {/* Usage & Costs Section - For Google Maps */}
+ {item.id === 'google_maps' && renderApiUsagePanel('google_maps', 'Google Maps')}
+
{/* Models list */}
{models[item.id]?.length > 0 && (
<div style={{ marginBottom: theme.spacing.xl }}>
diff --git a/server/config/pricing.json b/server/config/pricing.json
index 2d40ade1..9981eb93 100644
--- a/server/config/pricing.json
+++ b/server/config/pricing.json
@@ -88,6 +88,21 @@
},
"api": {
+ "google_maps": {
+ "_description": "Google Maps Platform pricing per request (USD, Tier 1: 0-100K/month)",
+ "_source": "https://developers.google.com/maps/billing-and-pricing/pricing",
+ "_updated": "2026-02",
+ "geocode": 0.005,
+ "reverse_geocode": 0.005,
+ "nearby_search": 0.032,
+ "place_details": 0.005,
+ "autocomplete": 0.00283,
+ "text_search": 0.032,
+ "directions": 0.005,
+ "distance_matrix": 0.005,
+ "static_map": 0.002,
+ "_default": 0.005
+ },
"twitter": {
"_description": "X/Twitter Pay-Per-Use API pricing (per resource/request)",
"_source": "https://developer.x.com/#pricing",
@@ -120,6 +135,19 @@
},
"operation_map": {
+ "google_maps": {
+ "geocode": "geocode",
+ "reverse_geocode": "reverse_geocode",
+ "nearby_search": "nearby_search",
+ "nearby_places": "nearby_search",
+ "place_details": "place_details",
+ "autocomplete": "autocomplete",
+ "text_search": "text_search",
+ "directions": "directions",
+ "distance_matrix": "distance_matrix",
+ "static_map": "static_map",
+ "create_map": "static_map"
+ },
"twitter": {
"tweet": "content_create",
"reply": "content_create",
@@ -134,5 +162,21 @@
"followers": "followers_read",
"following": "following_read"
}
+ },
+
+ "url_patterns": {
+ "twitter": {
+ "base": "https?://api\\.(twitter|x)\\.com",
+ "actions": {
+ "/2/tweets$": {"action": "content_create", "method": "POST"},
+ "/2/tweets/search": {"action": "posts_read", "method": "GET", "count_path": "data.length"},
+ "/2/users/.*/following": {"action": "following_read", "method": "GET", "count_path": "data.length"},
+ "/2/users/.*/followers": {"action": "followers_read", "method": "GET", "count_path": "data.length"},
+ "/2/users/.*/likes$": {"action": "user_interaction_create", "method": "POST"},
+ "/2/users/by": {"action": "user_read", "method": "GET", "count_path": "data.length"},
+ "/2/users/me": {"action": "user_read", "method": "GET"},
+ "/2/users/\\d+$": {"action": "user_read", "method": "GET"}
+ }
+ }
}
}
diff --git a/server/services/handlers/utility.py b/server/services/handlers/utility.py
index 9d353a5d..e5c1e6f2 100644
--- a/server/services/handlers/utility.py
+++ b/server/services/handlers/utility.py
@@ -38,7 +38,7 @@ async def handle_create_map(
Execution result dict
"""
logger.info("[Maps Execution] Executing gmaps_create", node_id=node_id)
- result = await maps_service.create_map(node_id, parameters)
+ result = await maps_service.create_map(node_id, parameters, context)
logger.info("[Maps Execution] gmaps_create result", success=result.get('success'),
has_result='result' in result,
result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')
@@ -65,7 +65,7 @@ async def handle_add_locations(
Execution result dict
"""
logger.info("[Maps Execution] Executing gmaps_locations", node_id=node_id)
- result = await maps_service.geocode_location(node_id, parameters)
+ result = await maps_service.geocode_location(node_id, parameters, context)
logger.info("[Maps Execution] gmaps_locations result", success=result.get('success'),
has_result='result' in result,
result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')
@@ -92,7 +92,7 @@ async def handle_nearby_places(
Execution result dict
"""
logger.info("[Maps Execution] Executing gmaps_nearby_places", node_id=node_id)
- result = await maps_service.find_nearby_places(node_id, parameters)
+ result = await maps_service.find_nearby_places(node_id, parameters, context)
logger.info("[Maps Execution] gmaps_nearby_places result", success=result.get('success'),
has_result='result' in result,
result_keys=list(result.get('result', {}).keys()) if isinstance(result.get('result'), dict) else 'not_dict')
diff --git a/server/services/maps.py b/server/services/maps.py
index 6d21304f..3ac287dc 100644
--- a/server/services/maps.py
+++ b/server/services/maps.py
@@ -8,10 +8,52 @@ from typing import Dict, Any
from core.config import Settings
from core.logging import get_logger, log_execution_time
from services.auth import AuthService
+from services.pricing import get_pricing_service
logger = get_logger(__name__)
+async def _track_maps_usage(
+ node_id: str,
+ action: str,
+ resource_count: int = 1,
+ workflow_id: str = None,
+ session_id: str = "default"
+) -> Dict[str, float]:
+ """Track Google Maps API usage for cost calculation.
+
+ Args:
+ node_id: The node executing the Maps action
+ action: Action name (geocode, nearby_search, etc.)
+ resource_count: Number of resources (usually 1 per request)
+ workflow_id: Optional workflow context
+ session_id: Session for aggregation
+
+ Returns:
+ Cost breakdown dict with operation, unit_cost, resource_count, total_cost
+ """
+ from core.container import container
+
+ pricing = get_pricing_service()
+ cost_data = pricing.calculate_api_cost('google_maps', action, resource_count)
+
+ # Save to database
+ db = container.database()
+ await db.save_api_usage_metric({
+ 'session_id': session_id,
+ 'node_id': node_id,
+ 'workflow_id': workflow_id,
+ 'service': 'google_maps',
+ 'operation': cost_data.get('operation', action),
+ 'endpoint': action,
+ 'resource_count': resource_count,
+ 'cost': cost_data.get('total_cost', 0.0)
+ })
+
+ logger.debug(f"[Maps] Tracked usage: {action} x{resource_count} = ${cost_data.get('total_cost', 0):.6f}")
+ return cost_data
+
+
class MapsService:
"""Google Maps and Places API service."""
@@ -27,9 +69,10 @@ class MapsService:
"""Validate Google Maps zoom level."""
return 0 <= zoom <= 21
- async def create_map(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ async def create_map(self, node_id: str, parameters: Dict[str, Any], context: Dict[str, Any] = None) -> Dict[str, Any]:
"""Create Google Maps configuration."""
start_time = time.time()
+ context = context or {}
try:
api_key = parameters.get('api_key') or self.settings.google_maps_api_key
@@ -59,6 +102,12 @@ class MapsService:
"status": "OK"
}
+ # Track: static_map $0.002
+ await _track_maps_usage(
+ node_id, 'static_map', 1,
+ context.get('workflow_id'), context.get('session_id', 'default')
+ )
+
log_execution_time(logger, "create_map", start_time, time.time())
return {
@@ -82,9 +131,10 @@ class MapsService:
"timestamp": datetime.now().isoformat()
}
- async def geocode_location(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ async def geocode_location(self, node_id: str, parameters: Dict[str, Any], context: Dict[str, Any] = None) -> Dict[str, Any]:
"""Geocode addresses or reverse geocode coordinates."""
start_time = time.time()
+ context = context or {}
try:
api_key = parameters.get('api_key') or self.settings.google_maps_api_key
@@ -106,6 +156,11 @@ class MapsService:
"results": geocode_result,
"status": "OK" if geocode_result else "ZERO_RESULTS"
}
+ # Track: geocode $0.005
+ await _track_maps_usage(
+ node_id, 'geocode', 1,
+ context.get('workflow_id'), context.get('session_id', 'default')
+ )
elif service_type == 'reverse_geocode':
lat = float(parameters.get('lat', 0))
@@ -121,6 +176,11 @@ class MapsService:
"results": reverse_result,
"status": "OK" if reverse_result else "ZERO_RESULTS"
}
+ # Track: reverse_geocode $0.005
+ await _track_maps_usage(
+ node_id, 'reverse_geocode', 1,
+ context.get('workflow_id'), context.get('session_id', 'default')
+ )
else:
raise ValueError(f"Unsupported service type: {service_type}")
@@ -159,9 +219,10 @@ class MapsService:
"timestamp": datetime.now().isoformat()
}
- async def find_nearby_places(self, node_id: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
+ async def find_nearby_places(self, node_id: str, parameters: Dict[str, Any], context: Dict[str, Any] = None) -> Dict[str, Any]:
"""Find nearby places using Google Places API."""
start_time = time.time()
+ context = context or {}
try:
api_key = parameters.get('api_key') or self.settings.google_maps_api_key
@@ -235,6 +296,12 @@ class MapsService:
nearby_result = gmaps.places_nearby(**search_params)
results = nearby_result.get('results', [])[:page_size]
+ # Track: nearby_search $0.032
+ await _track_maps_usage(
+ node_id, 'nearby_search', 1,
+ context.get('workflow_id'), context.get('session_id', 'default')
+ )
+
result = {
"search_parameters": {
"location": {"lat": lat, "lng": lng},
diff --git a/server/services/tracked_http.py b/server/services/tracked_http.py
new file mode 100644
index 00000000..d45c0eee
--- /dev/null
+++ b/server/services/tracked_http.py
@@ -0,0 +1,287 @@
+"""
+API Call Tracking via HTTPX Event Hooks
+
+Uses HTTPX's built-in event hooks for transparent tracking.
+No wrapper class needed - just configure the shared client.
+
+Usage:
+ from services.tracked_http import get_tracked_client, set_tracking_context
+
+ # Set context for current request
+ set_tracking_context(node_id="twitter-1", session_id="user-123")
+
+ # Use tracked client - tracking happens automatically!
+ client = get_tracked_client()
+ response = await client.post("https://api.twitter.com/2/tweets", json={...})
+"""
+import re
+import asyncio
+import contextvars
+from typing import Dict, Any, Optional, Tuple
+import httpx
+
+from services.pricing import get_pricing_service
+from core.container import container
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# ============================================================================
+# Context Variables (thread-safe tracking metadata)
+# ============================================================================
+
+_tracking_ctx: contextvars.ContextVar[Dict[str, Any]] = contextvars.ContextVar(
+ 'api_tracking', default={}
+)
+
+
+def set_tracking_context(
+ node_id: str,
+ session_id: str = "default",
+ workflow_id: Optional[str] = None
+):
+ """Set tracking context for current async task."""
+ _tracking_ctx.set({
+ 'node_id': node_id,
+ 'session_id': session_id,
+ 'workflow_id': workflow_id
+ })
+
+
+def clear_tracking_context():
+ """Clear tracking context."""
+ _tracking_ctx.set({})
+
+
+def get_tracking_context() -> Dict[str, Any]:
+ """Get current tracking context."""
+ return _tracking_ctx.get()
+
+
+# ============================================================================
+# URL Pattern Matching (loaded from pricing.json)
+# ============================================================================
+
+_url_patterns: Dict[str, Any] = {}
+_patterns_loaded: bool = False
+
+
+def _load_url_patterns():
+ """Load URL patterns from pricing.json."""
+ global _url_patterns, _patterns_loaded
+ if _patterns_loaded:
+ return
+
+ try:
+ pricing = get_pricing_service()
+ _url_patterns = pricing.get_config().get('url_patterns', {})
+ _patterns_loaded = True
+ logger.debug(f"[APITracker] Loaded URL patterns for {len(_url_patterns)} services")
+ except Exception as e:
+ logger.error(f"[APITracker] Failed to load URL patterns: {e}")
+ _url_patterns = {}
+
+
+def reload_url_patterns():
+ """Force reload of URL patterns (e.g., after pricing.json update)."""
+ global _patterns_loaded
+ _patterns_loaded = False
+ _load_url_patterns()
+
+
+def _match_url(url: str, method: str) -> Optional[Tuple[str, str, Optional[str]]]:
+ """
+ Match URL to (service, action, count_path) or None.
+
+ Args:
+ url: The request URL
+ method: HTTP method (GET, POST, etc.)
+
+ Returns:
+ Tuple of (service_name, action, count_path) or None if no match
+ """
+ _load_url_patterns()
+
+ for service, config in _url_patterns.items():
+ base = config.get('base', '')
+ if not base or not re.search(base, url):
+ continue
+
+ for pattern, action_info in config.get('actions', {}).items():
+ if not re.search(pattern, url):
+ continue
+
+ # Simple string action (any method)
+ if isinstance(action_info, str):
+ return (service, action_info, None)
+
+ # Dict with action, method, count_path
+ expected_method = action_info.get('method', '*')
+ if expected_method == '*' or expected_method.upper() == method.upper():
+ return (
+ service,
+ action_info.get('action', 'unknown'),
+ action_info.get('count_path')
+ )
+
+ return None
+
+
+def _extract_count(data: Any, path: Optional[str]) -> int:
+ """
+ Extract resource count from response data using dot-notation path.
+
+ Args:
+ data: Response JSON data
+ path: Dot-notation path like "data.length" or "results.count"
+
+ Returns:
+ Resource count (defaults to 1)
+ """
+ if not path or not data:
+ return 1
+
+ try:
+ for part in path.split('.'):
+ if part == 'length' and isinstance(data, list):
+ return len(data)
+ elif isinstance(data, dict):
+ data = data.get(part)
+ else:
+ return 1
+
+ if isinstance(data, (int, float)):
+ return int(data)
+ elif isinstance(data, list):
+ return len(data)
+ return 1
+ except Exception:
+ return 1
+
+
+# ============================================================================
+# HTTPX Event Hook (the magic happens here)
+# ============================================================================
+
+async def _on_response(response: httpx.Response):
+ """
+ HTTPX response event hook - tracks API calls automatically.
+
+ This is called for EVERY response when using the tracked client.
+ """
+ try:
+ # Skip failed requests
+ if response.status_code >= 400:
+ return
+
+ # Match URL to service/action
+ url = str(response.request.url)
+ method = response.request.method
+ match = _match_url(url, method)
+
+ if not match:
+ return # Not a tracked endpoint
+
+ service, action, count_path = match
+
+ # Extract resource count from response
+ resource_count = 1
+ if count_path:
+ try:
+ # Ensure body is read (required for event hooks)
+ await response.aread()
+ resource_count = _extract_count(response.json(), count_path)
+ except Exception:
+ pass
+
+ # Get tracking context
+ ctx = get_tracking_context()
+
+ # Calculate cost and save (fire-and-forget)
+ asyncio.create_task(_save_metric(service, action, resource_count, ctx))
+
+ except Exception as e:
+ logger.error(f"[APITracker] Error in response hook: {e}")
+
+
+async def _save_metric(
+ service: str,
+ action: str,
+ count: int,
+ ctx: Dict[str, Any]
+):
+ """Save metric to database (non-blocking)."""
+ try:
+ pricing = get_pricing_service()
+ cost = pricing.calculate_api_cost(service, action, count)
+
+ db = container.database()
+ await db.save_api_usage_metric({
+ 'session_id': ctx.get('session_id', 'default'),
+ 'node_id': ctx.get('node_id', ''),
+ 'workflow_id': ctx.get('workflow_id'),
+ 'service': service,
+ 'operation': cost.get('operation', action),
+ 'endpoint': action,
+ 'resource_count': count,
+ 'cost': cost.get('total_cost', 0.0)
+ })
+
+ logger.debug(
+ f"[APITracker] Tracked {service}/{action}: "
+ f"{count} resources, ${cost.get('total_cost', 0):.6f}"
+ )
+
+ except Exception as e:
+ logger.error(f"[APITracker] Failed to save metric: {e}")
+
+
+# ============================================================================
+# Tracked Client Factory
+# ============================================================================
+
+def create_tracked_client(**kwargs) -> httpx.AsyncClient:
+ """
+ Create an httpx.AsyncClient with tracking enabled.
+
+ Usage:
+ client = create_tracked_client()
+ set_tracking_context(node_id="twitter-1", session_id="user-123")
+ response = await client.post("https://api.twitter.com/2/tweets", json={...})
+ # Automatically tracked!
+
+ Args:
+ **kwargs: Additional arguments passed to httpx.AsyncClient
+
+ Returns:
+ httpx.AsyncClient with tracking event hook
+ """
+ return httpx.AsyncClient(
+ event_hooks={'response': [_on_response]},
+ **kwargs
+ )
+
+
+# Shared singleton client (for performance)
+_shared_client: Optional[httpx.AsyncClient] = None
+
+
+def get_tracked_client() -> httpx.AsyncClient:
+ """
+ Get shared tracked client instance.
+
+ Returns a singleton httpx.AsyncClient with tracking enabled.
+ Reusing the client avoids connection overhead.
+ """
+ global _shared_client
+ if _shared_client is None:
+ _shared_client = create_tracked_client()
+ return _shared_client
+
+
+async def close_tracked_client():
+ """Close the shared tracked client (call on shutdown)."""
+ global _shared_client
+ if _shared_client is not None:
+ await _shared_client.aclose()
+ _shared_client = None