Skip to content

Commit c793ad1

Browse files
joshsnyCopilot
andauthored
feat: python agent toolkit wrapper + langchain integration (#109)
Co-authored-by: Copilot <[email protected]>
1 parent e4bb6d6 commit c793ad1

File tree

13 files changed

+2059
-9
lines changed

13 files changed

+2059
-9
lines changed

examples/langchain/.env.example

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# PostHog Configuration
2+
POSTHOG_PERSONAL_API_KEY=your_posthog_api_key_here
3+
POSTHOG_MCP_URL=https://mcp.posthog.com/mcp # Optional
4+
5+
# OpenAI Configuration (for LangChain agent)
6+
OPENAI_API_KEY=your_openai_api_key_here

examples/langchain/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# PostHog LangChain Python Integration Example
2+
3+
This example demonstrates how to use PostHog tools with LangChain using the `posthog_agent_toolkit` package.
4+
5+
## Setup
6+
7+
1. Install dependencies:
8+
```bash
9+
# Reinstall the local PostHog Agent Toolkit to ensure latest changes
10+
uv sync --reinstall-package posthog-agent-toolkit
11+
```
12+
13+
2. Copy the environment file and fill in your credentials:
14+
```bash
15+
cp .env.example .env
16+
```
17+
18+
3. Update your `.env` file with:
19+
- `POSTHOG_PERSONAL_API_KEY`: Your PostHog personal API key
20+
- `OPENAI_API_KEY`: Your OpenAI API key
21+
22+
## Usage
23+
24+
Run the example:
25+
```bash
26+
uv run python posthog_agent_example.py
27+
```
28+
29+
The example will:
30+
1. Connect to the PostHog MCP server using your personal API key
31+
2. Load all available PostHog tools from the MCP server
32+
3. Create a LangChain agent
33+
4. Analyze product usage by:
34+
- Getting available insights
35+
- Querying data for the most relevant ones
36+
- Summarizing key findings
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
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())

examples/langchain/pyproject.toml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
[project]
2+
name = "posthog-langchain-example"
3+
version = "0.1.0"
4+
description = "PostHog LangChain integration example"
5+
readme = "README.md"
6+
requires-python = ">=3.11"
7+
dependencies = [
8+
"posthog-agent-toolkit",
9+
"langchain>=0.3.0",
10+
"langchain-openai>=0.2.0",
11+
"langchain-core>=0.3.0",
12+
"python-dotenv>=1.0.0",
13+
]
14+
15+
[tool.uv.sources]
16+
posthog-agent-toolkit = { path = "../../python", editable = true }
17+
18+
[tool.ruff]
19+
line-length = 120
20+
target-version = "py311"
21+
22+
[tool.black]
23+
line-length = 120
24+
target-version = ['py311']

0 commit comments

Comments
 (0)