1
+ """
2
+ PostHog LangChain Integration Example
3
+
4
+ This example demonstrates how to use PostHog tools with LangChain using
5
+ the local posthog_agent_toolkit package. It shows how to analyze product
6
+ usage data similar to the TypeScript example.
7
+ """
8
+
9
+ import asyncio
10
+ import os
11
+ import sys
12
+
13
+ from dotenv import load_dotenv
14
+ from langchain_openai import ChatOpenAI
15
+ from langchain .agents import AgentExecutor , create_tool_calling_agent
16
+ from langchain_core .prompts import ChatPromptTemplate , MessagesPlaceholder
17
+ from posthog_agent_toolkit .integrations .langchain .toolkit import PostHogAgentToolkit
18
+
19
+
20
+ async def analyze_product_usage ():
21
+ """Analyze product usage using PostHog data."""
22
+
23
+ print ("🚀 PostHog LangChain Agent - Product Usage Analysis\n " )
24
+
25
+ # Initialize the PostHog toolkit with credentials
26
+ toolkit = PostHogAgentToolkit (
27
+ personal_api_key = os .getenv ("POSTHOG_PERSONAL_API_KEY" ),
28
+ url = os .getenv ("POSTHOG_MCP_URL" , "https://mcp.posthog.com/mcp" )
29
+ )
30
+
31
+ # Get the tools
32
+ tools = await toolkit .get_tools ()
33
+
34
+ # Initialize the LLM
35
+ llm = ChatOpenAI (
36
+ model = "gpt-4o-mini" ,
37
+ temperature = 0 ,
38
+ api_key = os .getenv ("OPENAI_API_KEY" )
39
+ )
40
+
41
+ # Create a system prompt for the agent
42
+ prompt = ChatPromptTemplate .from_messages ([
43
+ (
44
+ "system" ,
45
+ "You are a data analyst. Your task is to do a deep dive into what's happening in our product. "
46
+ "Be concise and data-driven in your responses."
47
+ ),
48
+ ("human" , "{input}" ),
49
+ MessagesPlaceholder ("agent_scratchpad" ),
50
+ ])
51
+
52
+ agent = create_tool_calling_agent (
53
+ llm = llm ,
54
+ tools = tools ,
55
+ prompt = prompt ,
56
+ )
57
+
58
+ agent_executor = AgentExecutor (
59
+ agent = agent ,
60
+ tools = tools ,
61
+ verbose = False ,
62
+ max_iterations = 5 ,
63
+ )
64
+
65
+ # Invoke the agent with an analysis request
66
+ result = await agent_executor .ainvoke ({
67
+ "input" : """Please analyze our product usage:
68
+
69
+ 1. Get all available insights (limit 100)
70
+ 2. Pick the 5 MOST INTERESTING and VALUABLE insights - prioritize:
71
+ - User behavior and engagement metrics
72
+ - Conversion funnels
73
+ - Retention and growth metrics
74
+ - Product adoption insights
75
+ - Revenue or business KPIs
76
+ AVOID picking feature flag insights unless they show significant business impact
77
+ 3. For each selected insight, query its data and explain why it's important
78
+ 4. Summarize the key findings in a brief report with actionable recommendations
79
+
80
+ Focus on insights that tell a story about user behavior and business performance."""
81
+ })
82
+
83
+ print ("\n 📊 Analysis Complete!\n " )
84
+ print ("=" * 50 )
85
+ print (result ["output" ])
86
+ print ("=" * 50 )
87
+
88
+
89
+ async def main ():
90
+ """Main function to run the product usage analysis."""
91
+ try :
92
+ # Load environment variables
93
+ load_dotenv ()
94
+
95
+ # Run the analysis
96
+ await analyze_product_usage ()
97
+ except Exception as error :
98
+ print (f"Error: { error } " )
99
+ sys .exit (1 )
100
+
101
+
102
+ if __name__ == "__main__" :
103
+ asyncio .run (main ())
0 commit comments