Skip to content

Support LangChain v1 middleware in the Python SDK #901

Description

@gouveags

Problem Statement

I maintain a Python LangChain/LangGraph codebase, and after working on the equivalent JavaScript integration in PostHog/posthog-js#4556, I checked whether the Python SDK supported the same LangChain v1 middleware flow.

The current CallbackHandler works fine with create_agent, so tooday, the only way to add PostHog is when the agent runs:

agent.invoke(
    {"messages": [...]},
    config={"callbacks": [CallbackHandler(...)]},
)

The things is that LangChain v1 also supports middleware as the main way to package integrations with an agent. PostHog does not currently support that option:

agent = create_agent(
    model=model,
    tools=tools,
    middleware=[PostHogMiddleware(...)],
)

The JavaScript SDK had the same gap, tracked in PostHog/posthog-js#2907 and implemented in PostHog/posthog-js#4556.

Solution Brainstorm

Add an optional LangChain v1 middleware alongside the existing callback integration. Both should produce the same PostHog traces, generations, and tool spans, while letting users choose the integration style that fits their agent.

Would this be useful on the Python side, or are callbacks and OpenTelemetry intentionally the preferred direction here? If middleware makes sense, I’m happy to work on it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions