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
2 changes: 1 addition & 1 deletion docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
flask \
"praisonai>=2.2.30" \
"praisonai>=2.2.31" \
"praisonai[api]" \
gunicorn \
markdown
Expand Down
2 changes: 1 addition & 1 deletion docker/Dockerfile.chat
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.30" \
"praisonai>=2.2.31" \
"praisonai[chat]" \
"embedchain[github,youtube]"

Expand Down
2 changes: 1 addition & 1 deletion docker/Dockerfile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.30" \
"praisonai>=2.2.31" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
Expand Down
2 changes: 1 addition & 1 deletion docker/Dockerfile.ui
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.30" \
"praisonai>=2.2.31" \
"praisonai[ui]" \
"praisonai[crewai]"

Expand Down
4 changes: 2 additions & 2 deletions docker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ healthcheck:
## 📦 Package Versions

All Docker images use consistent, up-to-date versions:
- PraisonAI: `>=2.2.30`
- PraisonAI: `>=2.2.31`
- PraisonAI Agents: `>=0.0.92`
- Python: `3.11-slim`

Expand Down Expand Up @@ -218,7 +218,7 @@ docker-compose up -d
### Version Pinning
To use specific versions, update the Dockerfile:
```dockerfile
RUN pip install "praisonai==2.2.30" "praisonaiagents==0.0.92"
RUN pip install "praisonai==2.2.31" "praisonaiagents==0.0.92"
```

## 🌐 Production Deployment
Expand Down
33 changes: 33 additions & 0 deletions src/praisonai-agents/TELEMETRY_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Telemetry Implementation Summary

## What Was Fixed

1. **PostHog initialization error** - Removed invalid `events_to_ignore` parameter
2. **Missing imports** - Added `MinimalTelemetry` and `TelemetryCollector` imports to telemetry `__init__.py`
3. **Wrong method instrumentation** - Changed from `agent.execute()` to `agent.chat()`
4. **Task tracking** - Added instrumentation for `workflow.execute_task()`
5. **Automatic setup** - Added `auto_instrument_all()` in main `__init__.py`
6. **Automatic flush** - Added `atexit` handler to send data on program exit

## Current Status

✅ **Telemetry is now working automatically!**

- Enabled by default (opt-out via environment variables)
- Tracks agent executions and task completions
- Sends anonymous data to PostHog on program exit
- No manual setup required

## Metrics Example
```
Telemetry metrics collected:
- Agent executions: 4
- Task completions: 2
- Errors: 0
- Session ID: 33873e62396d8b4c
```

## To Disable
Set any of these environment variables:
- `PRAISONAI_TELEMETRY_DISABLED=true`
- `DO_NOT_TRACK=true`
44 changes: 44 additions & 0 deletions src/praisonai-agents/debug_auto_instrument.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""
Debug auto-instrumentation.
"""

print("1. Import telemetry module...")
import praisonaiagents.telemetry
print(" Telemetry module imported")

print("\n2. Check if auto_instrument_all was called...")
print(f" _initialized: {praisonaiagents.telemetry._initialized}")

print("\n3. Import Agent and PraisonAIAgents...")
from praisonaiagents import Agent, PraisonAIAgents
print(" Classes imported")

print("\n4. Check if classes are instrumented...")
agent = Agent(name="Test", role="Test", goal="Test", instructions="Test")
print(f" Agent.__init__ name: {Agent.__init__.__name__}")
print(f" agent.execute exists: {hasattr(agent, 'execute')}")

print("\n5. Manually call auto_instrument_all...")
from praisonaiagents.telemetry.integration import auto_instrument_all
auto_instrument_all()
print(" auto_instrument_all() called")

print("\n6. Create new agent after instrumentation...")
agent2 = Agent(name="Test2", role="Test2", goal="Test2", instructions="Test2")
print(f" Agent.__init__ name after: {Agent.__init__.__name__}")
print(f" agent2.execute exists: {hasattr(agent2, 'execute')}")

print("\n7. Check if execute is wrapped...")
if hasattr(agent2, 'execute'):
print(f" agent2.execute name: {agent2.execute.__name__}")
print(f" agent2.execute wrapped: {hasattr(agent2.execute, '__wrapped__')}")

print("\n8. Import telemetry and check if it's working...")
from praisonaiagents.telemetry import get_telemetry
telemetry = get_telemetry()
print(f" Telemetry enabled: {telemetry.enabled}")
print(f" PostHog available: {telemetry._posthog is not None}")

# The key insight: auto_instrument_all needs to be called AFTER
# the Agent and PraisonAIAgents classes are imported!
69 changes: 69 additions & 0 deletions src/praisonai-agents/debug_telemetry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Debug telemetry instrumentation to see what's happening.
"""

import os
# Make sure telemetry is enabled
if 'PRAISONAI_TELEMETRY_DISABLED' in os.environ:
del os.environ['PRAISONAI_TELEMETRY_DISABLED']

print("1. Importing modules...")
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.telemetry import get_telemetry

print("\n2. Checking telemetry status...")
telemetry = get_telemetry()
print(f"Telemetry enabled: {telemetry.enabled}")
print(f"PostHog available: {telemetry._posthog is not None}")

print("\n3. Creating agent...")
agent = Agent(
name="TestAgent",
role="Test Role",
goal="Test Goal",
instructions="Test instructions"
)

# Check if agent.execute is instrumented
print(f"\n4. Checking agent instrumentation...")
print(f"Agent has execute method: {hasattr(agent, 'execute')}")
if hasattr(agent, 'execute'):
print(f"Execute method type: {type(agent.execute)}")
print(f"Execute method name: {agent.execute.__name__ if hasattr(agent.execute, '__name__') else 'No name'}")
print(f"Is wrapped: {'instrumented' in str(agent.execute.__name__) if hasattr(agent.execute, '__name__') else 'Unknown'}")

print("\n5. Creating task...")
task = Task(
description="Test task",
expected_output="Test output",
agent=agent
)

print("\n6. Creating workflow...")
workflow = PraisonAIAgents(
agents=[agent],
tasks=[task],
process="sequential"
)

# Check if workflow.start is instrumented
print(f"\n7. Checking workflow instrumentation...")
print(f"Workflow has start method: {hasattr(workflow, 'start')}")
if hasattr(workflow, 'start'):
print(f"Start method type: {type(workflow.start)}")
print(f"Start method name: {workflow.start.__name__ if hasattr(workflow.start, '__name__') else 'No name'}")
print(f"Is wrapped: {'instrumented' in str(workflow.start.__name__) if hasattr(workflow.start, '__name__') else 'Unknown'}")

print("\n8. Running workflow...")
result = workflow.start()

print("\n9. Checking metrics...")
metrics = telemetry.get_metrics()
print(f"Metrics: {metrics}")

print("\n10. Manually tracking to verify telemetry works...")
telemetry.track_agent_execution("ManualTest", success=True)
telemetry.track_task_completion("ManualTask", success=True)
manual_metrics = telemetry.get_metrics()
print(f"After manual tracking: {manual_metrics['metrics']}")
69 changes: 69 additions & 0 deletions src/praisonai-agents/debug_telemetry_double.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Debug double-counting in telemetry.
"""

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.telemetry import get_telemetry

# Get telemetry instance
telemetry = get_telemetry()

# Clear any existing metrics by flushing
telemetry.flush()

print("Starting fresh telemetry tracking...\n")

# Create ONE agent
print("Creating 1 agent...")
agent = Agent(
name="SingleAgent",
role="Test Role",
goal="Test Goal",
instructions="Test instructions"
)

# Create ONE task
print("Creating 1 task...")
task = Task(
description="Single test task",
expected_output="Test output",
agent=agent
)

# Create workflow with ONE agent and ONE task
print("Creating workflow with 1 agent and 1 task...")
workflow = PraisonAIAgents(
agents=[agent],
tasks=[task],
process="sequential"
)

# Check metrics before running
metrics_before = telemetry.get_metrics()
print(f"\nMetrics BEFORE running workflow:")
print(f" Agent executions: {metrics_before['metrics']['agent_executions']}")
print(f" Task completions: {metrics_before['metrics']['task_completions']}")

# Run the workflow
print("\nRunning workflow...")
result = workflow.start()

# Check metrics after running
metrics_after = telemetry.get_metrics()
print(f"\nMetrics AFTER running workflow:")
print(f" Agent executions: {metrics_after['metrics']['agent_executions']} (expected: 1)")
print(f" Task completions: {metrics_after['metrics']['task_completions']} (expected: 1)")

if metrics_after['metrics']['agent_executions'] > 1:
print("\n❌ ISSUE: Agent executions are being double-counted!")
print(" Possible causes:")
print(" - Agent method is being called multiple times")
print(" - Instrumentation is being applied twice")
print(" - Multiple tracking calls for same execution")

if metrics_after['metrics']['task_completions'] > 1:
print("\n❌ ISSUE: Task completions are being double-counted!")
print(" Possible causes:")
print(" - Task completion is tracked in multiple places")
print(" - Instrumentation is being applied twice")
48 changes: 47 additions & 1 deletion src/praisonai-agents/praisonaiagents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,50 @@
async_display_callbacks,
)

# Telemetry support (lazy loaded)
try:
from .telemetry import (
get_telemetry,
enable_telemetry,
disable_telemetry,
MinimalTelemetry,
TelemetryCollector
)
_telemetry_available = True
except ImportError:
# Telemetry not available - provide stub functions
_telemetry_available = False
def get_telemetry():
return None

def enable_telemetry(*args, **kwargs):
import logging
logging.warning(
"Telemetry not available. Install with: pip install praisonaiagents[telemetry]"
)
return None

def disable_telemetry():
pass

MinimalTelemetry = None
TelemetryCollector = None

# Add Agents as an alias for PraisonAIAgents
Agents = PraisonAIAgents

# Apply telemetry auto-instrumentation after all imports
if _telemetry_available:
try:
# Only instrument if telemetry is enabled
_telemetry = get_telemetry()
if _telemetry and _telemetry.enabled:
from .telemetry.integration import auto_instrument_all
auto_instrument_all(_telemetry)
except Exception:
# Silently fail if there are any issues
pass
Comment on lines +73 to +75
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Is it possible to catch more specific exceptions here instead of a general Exception? While the comment indicates that silent failure is intentional for auto-instrumentation, catching specific exceptions (e.g., ImportError, AttributeError, or custom exceptions from the telemetry module) could provide more targeted resilience. If a general catch is necessary, consider logging the exception at a DEBUG level. This could help diagnose issues during development or if telemetry setup becomes problematic in certain environments, without crashing the main application.


__all__ = [
'Agent',
'ImageAgent',
Expand Down Expand Up @@ -60,5 +101,10 @@
'Chunking',
'MCP',
'GuardrailResult',
'LLMGuardrail'
'LLMGuardrail',
'get_telemetry',
'enable_telemetry',
'disable_telemetry',
'MinimalTelemetry',
'TelemetryCollector'
]
11 changes: 11 additions & 0 deletions src/praisonai-agents/praisonaiagents/llm/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import logging
import warnings
import os

# Disable litellm telemetry before any imports
os.environ["LITELLM_TELEMETRY"] = "False"

# Suppress all relevant logs at module level
logging.getLogger("litellm").setLevel(logging.ERROR)
Expand All @@ -17,4 +21,11 @@
# Import after suppressing warnings
from .llm import LLM, LLMContextLengthExceededException

# Ensure telemetry is disabled after import as well
try:
import litellm
litellm.telemetry = False
except ImportError:
pass

__all__ = ["LLM", "LLMContextLengthExceededException"]
6 changes: 6 additions & 0 deletions src/praisonai-agents/praisonaiagents/llm/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
from rich.console import Console
from rich.live import Live

# Disable litellm telemetry before any imports
os.environ["LITELLM_TELEMETRY"] = "False"

# TODO: Include in-build tool calling in LLM class
# TODO: Restructure so that duplicate calls are not made (Sync with agent.py)
class LLMContextLengthExceededException(Exception):
Expand Down Expand Up @@ -108,6 +111,9 @@ def __init__(
):
try:
import litellm
# Disable telemetry
litellm.telemetry = False

# Set litellm options globally
litellm.set_verbose = False
litellm.success_callback = []
Expand Down
Loading
Loading