Skip to content

Commit 01a3902

Browse files
committed
feat: add bot classification middleware/integration
Part of AI bot classification feature for Python SDK.
1 parent e42c8a9 commit 01a3902

2 files changed

Lines changed: 82 additions & 0 deletions

File tree

mixpanel/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@
3030
from .flags.remote_feature_flags import RemoteFeatureFlagsProvider
3131
from .flags.types import LocalFlagsConfig, RemoteFlagsConfig
3232

33+
from .ai_bot_classifier import classify_user_agent, create_classifier, get_bot_database
34+
from .ai_bot_consumer import BotClassifyingConsumer
35+
3336
__version__ = '5.1.0'
3437

3538
logger = logging.getLogger(__name__)

mixpanel/ai_bot_helpers.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# mixpanel/ai_bot_helpers.py
2+
"""Framework integration helpers for AI bot classification."""
3+
4+
from typing import Any, Dict, Optional
5+
6+
7+
def extract_request_context_django(request: Any) -> Dict[str, str]:
8+
"""
9+
Extract user-agent and IP from a Django HttpRequest.
10+
11+
Usage:
12+
from mixpanel.ai_bot_helpers import extract_request_context_django
13+
14+
mp.track('user_id', 'page_view', {
15+
**extract_request_context_django(request),
16+
'page_url': request.path,
17+
})
18+
"""
19+
ctx = {}
20+
ua = request.META.get('HTTP_USER_AGENT')
21+
if ua:
22+
ctx['$user_agent'] = ua
23+
24+
# Django's get_host() + REMOTE_ADDR
25+
ip = (
26+
request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')[0].strip()
27+
or request.META.get('REMOTE_ADDR')
28+
)
29+
if ip:
30+
ctx['$ip'] = ip
31+
32+
return ctx
33+
34+
35+
def extract_request_context_flask(request: Any) -> Dict[str, str]:
36+
"""
37+
Extract user-agent and IP from a Flask request.
38+
39+
Usage:
40+
from mixpanel.ai_bot_helpers import extract_request_context_flask
41+
42+
mp.track('user_id', 'page_view', {
43+
**extract_request_context_flask(request),
44+
'page_url': request.path,
45+
})
46+
"""
47+
ctx = {}
48+
ua = request.headers.get('User-Agent')
49+
if ua:
50+
ctx['$user_agent'] = ua
51+
52+
ip = request.remote_addr
53+
if ip:
54+
ctx['$ip'] = ip
55+
56+
return ctx
57+
58+
59+
def extract_request_context_fastapi(request: Any) -> Dict[str, str]:
60+
"""
61+
Extract user-agent and IP from a FastAPI/Starlette Request.
62+
63+
Usage:
64+
from mixpanel.ai_bot_helpers import extract_request_context_fastapi
65+
66+
mp.track('user_id', 'page_view', {
67+
**extract_request_context_fastapi(request),
68+
'page_url': str(request.url),
69+
})
70+
"""
71+
ctx = {}
72+
ua = request.headers.get('user-agent')
73+
if ua:
74+
ctx['$user_agent'] = ua
75+
76+
if request.client:
77+
ctx['$ip'] = request.client.host
78+
79+
return ctx

0 commit comments

Comments
 (0)