-
Notifications
You must be signed in to change notification settings - Fork 23
feat: python agent toolkit wrapper + langchain integration #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
74caf94
set path as typescript
joshsny 0916866
wip python package
joshsny 18cdcb5
feat(wip): python package
joshsny 4439114
update readme
joshsny 17c0254
Update examples/langchain/pyproject.toml
joshsny 0863dd6
updates
joshsny 77df8be
remove unnecessary langraph dep
joshsny 0720893
update README
joshsny File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,4 +17,6 @@ __pycache__/ | |
|
|
||
| .env | ||
|
|
||
| dist/ | ||
| dist/ | ||
|
|
||
| .venv/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| # PostHog Configuration | ||
| POSTHOG_PERSONAL_API_KEY=your_posthog_api_key_here | ||
| POSTHOG_MCP_URL=https://mcp.posthog.com/mcp # Optional | ||
|
|
||
| # OpenAI Configuration (for LangChain agent) | ||
| OPENAI_API_KEY=your_openai_api_key_here |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| # PostHog LangChain Python Integration Example | ||
|
|
||
| This example demonstrates how to use PostHog tools with LangChain using the local `posthog_agent_toolkit` package. | ||
|
|
||
| ## Setup | ||
|
|
||
| 1. Install dependencies: | ||
| ```bash | ||
| # Create and activate virtual environment | ||
| python -m venv .venv | ||
| source .venv/bin/activate # On Windows: .venv\Scripts\activate | ||
|
|
||
| # Install the local PostHog Agent Toolkit | ||
| pip install -e ../../python | ||
|
|
||
| # Install example dependencies | ||
| pip install langchain langchain-openai python-dotenv | ||
| ``` | ||
|
|
||
| 2. Copy the environment file and fill in your credentials: | ||
| ```bash | ||
| cp .env.example .env | ||
| ``` | ||
|
|
||
| 3. Update your `.env` file with: | ||
| - `POSTHOG_PERSONAL_API_KEY`: Your PostHog personal API key | ||
| - `OPENAI_API_KEY`: Your OpenAI API key | ||
|
|
||
| ## Usage | ||
|
|
||
| Run the example: | ||
| ```bash | ||
| python posthog_agent_example.py | ||
| ``` | ||
|
|
||
| The example will: | ||
| 1. Connect to PostHog using your API key | ||
| 2. Load all available PostHog tools | ||
| 3. Create a LangChain agent with GPT-4o-mini | ||
| 4. Analyze product usage by: | ||
| - Getting available insights | ||
| - Querying data for the most relevant ones | ||
| - Summarizing key findings | ||
|
|
||
| ## What It Does | ||
|
|
||
| The example demonstrates a product usage analysis workflow: | ||
| - Fetches up to 100 insights from your PostHog instance | ||
| - Identifies the 5 most relevant insights | ||
| - Queries the data for each insight | ||
| - Provides a data-driven summary of findings | ||
|
|
||
| ## Customization | ||
|
|
||
| You can modify the analysis query in `posthog_agent_example.py` to: | ||
| - Focus on specific metrics | ||
| - Analyze feature flags | ||
| - Review dashboards | ||
| - Query error tracking data | ||
| - Search PostHog documentation | ||
|
|
||
| ## Requirements | ||
|
|
||
| - Python 3.8+ | ||
| - PostHog personal API key with appropriate permissions | ||
| - OpenAI API key (or another LLM provider) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| """ | ||
| PostHog LangChain Integration Example | ||
|
|
||
| This example demonstrates how to use PostHog tools with LangChain using | ||
| the local posthog_agent_toolkit package. It shows how to analyze product | ||
| usage data similar to the TypeScript example. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import os | ||
| import sys | ||
|
|
||
| from dotenv import load_dotenv | ||
| from langchain_openai import ChatOpenAI | ||
| from langchain.agents import AgentExecutor, create_tool_calling_agent | ||
| from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder | ||
| from posthog_agent_toolkit.integrations.langchain.toolkit import PostHogAgentToolkit | ||
|
|
||
|
|
||
| async def analyze_product_usage(): | ||
| """Analyze product usage using PostHog data.""" | ||
|
|
||
| print("🚀 PostHog LangChain Agent - Product Usage Analysis\n") | ||
|
|
||
| # Initialize the PostHog toolkit with credentials | ||
| toolkit = PostHogAgentToolkit( | ||
| personal_api_key=os.getenv("POSTHOG_PERSONAL_API_KEY"), | ||
| url=os.getenv("POSTHOG_MCP_URL", "https://mcp.posthog.com/mcp") | ||
| ) | ||
|
|
||
| # Get the tools | ||
| tools = await toolkit.get_tools() | ||
|
|
||
| # Initialize the LLM | ||
| llm = ChatOpenAI( | ||
| model="gpt-4o-mini", | ||
| temperature=0, | ||
| api_key=os.getenv("OPENAI_API_KEY") | ||
| ) | ||
|
|
||
| # Create a system prompt for the agent | ||
| prompt = ChatPromptTemplate.from_messages([ | ||
| ( | ||
| "system", | ||
| "You are a data analyst. Your task is to do a deep dive into what's happening in our product. " | ||
| "Be concise and data-driven in your responses." | ||
| ), | ||
| ("human", "{input}"), | ||
| MessagesPlaceholder("agent_scratchpad"), | ||
| ]) | ||
|
|
||
| agent = create_tool_calling_agent( | ||
| llm=llm, | ||
| tools=tools, | ||
| prompt=prompt, | ||
| ) | ||
|
|
||
| agent_executor = AgentExecutor( | ||
| agent=agent, | ||
| tools=tools, | ||
| verbose=False, | ||
| max_iterations=5, | ||
| ) | ||
|
|
||
| # Invoke the agent with an analysis request | ||
| result = await agent_executor.ainvoke({ | ||
| "input": """Please analyze our product usage: | ||
|
|
||
| 1. Get all available insights (limit 100) | ||
| 2. Pick the 5 MOST INTERESTING and VALUABLE insights - prioritize: | ||
| - User behavior and engagement metrics | ||
| - Conversion funnels | ||
| - Retention and growth metrics | ||
| - Product adoption insights | ||
| - Revenue or business KPIs | ||
| AVOID picking feature flag insights unless they show significant business impact | ||
| 3. For each selected insight, query its data and explain why it's important | ||
| 4. Summarize the key findings in a brief report with actionable recommendations | ||
|
|
||
| Focus on insights that tell a story about user behavior and business performance.""" | ||
| }) | ||
|
|
||
| print("\n📊 Analysis Complete!\n") | ||
| print("=" * 50) | ||
| print(result["output"]) | ||
| print("=" * 50) | ||
|
|
||
|
|
||
| async def main(): | ||
| """Main function to run the product usage analysis.""" | ||
| try: | ||
| # Load environment variables | ||
| load_dotenv() | ||
|
|
||
| # Run the analysis | ||
| await analyze_product_usage() | ||
| except Exception as error: | ||
| print(f"Error: {error}") | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| [project] | ||
| name = "posthog-langchain-example" | ||
| version = "0.1.0" | ||
| description = "PostHog LangChain integration example" | ||
| readme = "README.md" | ||
| requires-python = ">=3.11" | ||
| dependencies = [ | ||
| "posthog-agent-toolkit", | ||
| "langchain>=0.3.0", | ||
| "langchain-openai>=0.2.0", | ||
| "langchain-core>=0.3.0", | ||
| "python-dotenv>=1.0.0", | ||
| ] | ||
|
|
||
| [tool.uv.sources] | ||
| posthog-agent-toolkit = { path = "../../python", editable = true } | ||
|
|
||
| [tool.ruff] | ||
| line-length = 120 | ||
| target-version = "py39" | ||
|
|
||
| [tool.black] | ||
| line-length = 120 | ||
| target-version = ['py39'] | ||
joshsny marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.