Skip to content
Open
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
5 changes: 5 additions & 0 deletions .sampo/changesets/langchain-agent-middleware.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

Add LangChain v1 agent middleware for AI observability.
6 changes: 6 additions & 0 deletions examples/example-ai-langchain/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@ uv sync
## Examples

- **callback_handler.py** - PostHog callback handler with tool calling
- **agent_middleware.py** - LangChain v1 agent middleware with model and tool tracking
- **otel.py** - OpenTelemetry instrumentation exporting to PostHog

## Run

```bash
source .env
uv run python callback_handler.py
uv run python agent_middleware.py
uv run python otel.py
```

Use either `PostHogMiddleware` or `CallbackHandler` for an agent invocation, not
both, to avoid recording duplicate events. Put `PostHogMiddleware` last in the
middleware list so it records the final model selection and each retry attempt.
34 changes: 34 additions & 0 deletions examples/example-ai-langchain/agent_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Track a LangChain v1 agent with PostHog middleware."""

import os

from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

from posthog import Posthog
from posthog.ai.langchain.middleware import PostHogMiddleware


@tool
def get_weather(city: str) -> str:
"""Get the weather for a city."""
return f"It is sunny in {city}."


client = Posthog(
os.environ["POSTHOG_API_KEY"],
host=os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com"),
)
agent = create_agent(
model=ChatOpenAI(model="gpt-4.1-mini"),
tools=[get_weather],
middleware=[PostHogMiddleware(client, distinct_id="example-user")],
)

result = agent.invoke(
{"messages": [HumanMessage(content="What is the weather in Berlin?")]}
)
print(result["messages"][-1].content)
client.shutdown()
9 changes: 7 additions & 2 deletions posthog/ai/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,11 @@ def _capture_trace_or_span(
run: SpanMetadata,
outputs: Any,
parent_run_id: Optional[UUID],
event_name_override: Optional[str] = None,
):
event_name = "$ai_trace" if parent_run_id is None else "$ai_span"
event_name = event_name_override or (
"$ai_trace" if parent_run_id is None else "$ai_span"
)
event_properties = {
"$ai_trace_id": trace_id,
"$ai_input_state": with_privacy_mode(
Expand Down Expand Up @@ -616,6 +619,7 @@ def _capture_generation(
run: GenerationMetadata,
output: Union[LLMResult, BaseException],
parent_run_id: Optional[UUID] = None,
include_parent_id: bool = True,
):
# The served tier comes from the response, because a requested tier can be refused.
model_params = run.model_params
Expand All @@ -629,7 +633,6 @@ def _capture_generation(
"$ai_trace_id": trace_id,
"$ai_span_id": run_id,
"$ai_span_name": run.name,
"$ai_parent_id": parent_run_id,
"$ai_provider": run.provider,
"$ai_model": run.model,
"$ai_model_parameters": model_params,
Expand All @@ -645,6 +648,8 @@ def _capture_generation(
"$ai_base_url": run.base_url,
"$ai_framework": "langchain",
}
if include_parent_id:
event_properties["$ai_parent_id"] = parent_run_id

warn_if_posthog_ai_gateway(run.base_url)

Expand Down
Loading