Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion src/praisonai-agents/praisonaiagents/telemetry/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ def __init__(self, enabled: bool = None):
self._posthog = Posthog(
project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
host='https://eu.i.posthog.com',
disable_geoip=True
disable_geoip=True,
on_error=lambda e: self.logger.debug(f"PostHog error: {e}"),
sync_mode=False # Use async mode to prevent blocking
)
except:
Comment on lines +90 to 93
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using a bare except: clause can mask unexpected errors. It's recommended to catch specific exceptions that Posthog() initialization might raise, or at least Exception.

            except Exception as e:
                self.logger.warning(f"Failed to initialize PostHog: {e}")

self._posthog = None
Expand Down Expand Up @@ -220,13 +222,33 @@ def flush(self):
'$geoip_disable': True
}
)
# Don't flush here - let PostHog handle it asynchronously
except:
pass

# Reset counters
for key in self._metrics:
if isinstance(self._metrics[key], int):
self._metrics[key] = 0

def shutdown(self):
"""
Shutdown telemetry and ensure all events are sent.
"""
if not self.enabled:
return

# Final flush
self.flush()

# Shutdown PostHog if available
if hasattr(self, '_posthog') and self._posthog:
try:
# Force a synchronous flush before shutdown
self._posthog.flush()
self._posthog.shutdown()
except:
pass
Comment on lines +249 to +251
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

A bare except: clause here can hide issues during the shutdown process. It's better to catch Exception or more specific exceptions that self._posthog.flush() or self._posthog.shutdown() might raise.

            except Exception as e:
                self.logger.warning(f"Error during PostHog shutdown: {e}")



# Global telemetry instance
Expand Down
1 change: 1 addition & 0 deletions src/praisonai-agents/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
pydantic
rich
openai>=1.30.0
posthog>=3.0.0

# Memory dependencies
chromadb>=0.5.23
Expand Down
67 changes: 67 additions & 0 deletions src/praisonai-agents/tests/test_posthog_fixed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""
Test PostHog integration after fix.
"""

import os
import time

# Ensure telemetry is enabled
for var in ['PRAISONAI_TELEMETRY_DISABLED', 'PRAISONAI_DISABLE_TELEMETRY', 'DO_NOT_TRACK']:
if var in os.environ:
del os.environ[var]

print("=== Testing PostHog Fix ===\n")

# Test PostHog directly first
print("1. Testing PostHog directly:")
try:
from posthog import Posthog

# Create PostHog client
ph = Posthog(
project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
host='https://eu.i.posthog.com'
)
Comment on lines +23 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Hardcoding API keys, even for testing, is generally discouraged. Consider using environment variables to supply the API key. This makes the test setup more flexible and secure.

Suggested change
project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
host='https://eu.i.posthog.com'
)
project_api_key=os.environ.get('POSTHOG_TEST_API_KEY', 'phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7'), # Default for convenience, but ideally require env var


# Send test event
ph.capture('test-user', 'direct_test', {'timestamp': time.time()})

# Flush and shutdown properly
ph.flush()
ph.shutdown()

print("✓ Direct PostHog test successful\n")
except Exception as e:
print(f"✗ Direct PostHog test failed: {e}\n")

# Test telemetry module
print("2. Testing telemetry module:")
from praisonaiagents.telemetry.telemetry import MinimalTelemetry

# Create telemetry instance
telemetry = MinimalTelemetry(enabled=True)

# Track events
telemetry.track_agent_execution("TestAgent", success=True)
telemetry.track_task_completion("TestTask", success=True)
telemetry.track_tool_usage("TestTool", success=True)

print(f"✓ Events tracked")
print(f"✓ PostHog client available: {telemetry._posthog is not None}")

# Flush
print("\n3. Flushing telemetry...")
telemetry.flush()
print("✓ Flush completed")

# Shutdown
print("\n4. Shutting down telemetry...")
telemetry.shutdown()
print("✓ Shutdown completed")

print("\n=== Test Complete ===")
print("\nPostHog should now be receiving data properly!")
print("The fix adds:")
print("1. posthog.flush() call in the flush() method")
print("2. shutdown() method that properly closes the connection")
Comment on lines +66 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This print statement seems to inaccurately describe one of the fixes. The MinimalTelemetry.flush() method was changed to not call posthog.flush() directly. Instead, posthog.flush() is now called synchronously within the new shutdown() method. The test output should reflect this accurately.

Suggested change
print("1. posthog.flush() call in the flush() method")
print("2. shutdown() method that properly closes the connection")
print("1. PostHog client operates asynchronously; `shutdown()` ensures final synchronous flush.")

Loading