Skip to main content

prefactor-langchain

LangChain integration for Prefactor observability. This package provides automatic tracing for LangChain agents using LangChain-specific span types.

Installation

pip install prefactor-langchain

Usage

Factory pattern (quickest setup)

from prefactor_langchain import LangChainToolSchemaConfig, PrefactorMiddleware

middleware = PrefactorMiddleware.from_config(
    api_url="https://app.prefactorai.com",
    api_token="your-api-token",
    agent_id="my-agent",  # Optional for deployment-scoped tokens
    agent_name="My Agent",  # optional
    tool_schemas={
        "send_email": LangChainToolSchemaConfig(
            span_type="send-email",
            input_schema={
                "type": "object",
                "properties": {
                    "to": {"type": "string", "format": "email"},
                    "subject": {"type": "string"},
                },
                "required": ["to", "subject"],
            },
        )
    },
)

# Use with LangChain's create_agent()
# Your agent will automatically create spans for:
# - Agent execution (langchain:agent)
# - LLM calls (langchain:llm)
# - Tool executions (langchain:tool)
# - Tool-specific executions (for example langchain:tool:send-email)

result = agent.invoke({"messages": [...]})

# Middleware owns both client and instance; close when done
await middleware.close()

With a deployment-scoped token you can omit agent_id; the backend derives the agent and environment from the token during registration.

Pre-configured client

Pass a client you created yourself when you need full control over its configuration or when you want to share a client across multiple middlewares.

from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig
from prefactor_http.config import HttpClientConfig
from prefactor_langchain import PrefactorMiddleware

http_config = HttpClientConfig(
    api_url="https://app.prefactorai.com", api_token="your-api-token"
)
config = PrefactorCoreConfig(http_config=http_config)
client = PrefactorCoreClient(config)
await client.initialize()

middleware = PrefactorMiddleware(
    client=client,
    agent_id="my-agent",  # Optional for deployment-scoped tokens
    agent_name="My Agent",
)

result = agent.invoke({"messages": [...]})

# You own the client; close both separately
await middleware.close()  # closes the agent instance only
await client.close()

SchemaRegistry composition

Use a shared SchemaRegistry when you want custom workflow span types and LangChain tool schemas to be published together.

from prefactor_core import SchemaRegistry
from prefactor_langchain import (
    LangChainToolSchemaConfig,
    PrefactorMiddleware,
    register_langchain_schemas,
)

registry = SchemaRegistry()
registry.register_type(
    name="workflow:run",
    params_schema={"type": "object"},
    result_schema={"type": "object"},
)
register_langchain_schemas(
    registry,
    tool_schemas={
        "send_email": LangChainToolSchemaConfig(
            span_type="send-email",
            input_schema={
                "type": "object",
                "properties": {"to": {"type": "string"}},
                "required": ["to"],
            },
        )
    },
)

middleware = PrefactorMiddleware.from_config(
    api_url="https://app.prefactorai.com",
    api_token="your-api-token",
    agent_id="my-agent",  # Optional for deployment-scoped tokens
    schema_registry=registry,
)

Pre-configured instance (spans outside the agent)

Pass an AgentInstanceHandle you created yourself when you also need to instrument code that lives outside the LangChain agent — for example, pre-processing steps, post-processing, or any custom business logic that should appear as siblings of the agent spans in the same trace.

from prefactor_core import PrefactorCoreClient, PrefactorCoreConfig
from prefactor_http.config import HttpClientConfig
from prefactor_langchain import PrefactorMiddleware

http_config = HttpClientConfig(
    api_url="https://app.prefactorai.com", api_token="your-api-token"
)
config = PrefactorCoreConfig(http_config=http_config)
client = PrefactorCoreClient(config)
await client.initialize()

instance = await client.create_agent_instance(agent_id="my-agent")
await instance.start()

# Share the instance with the middleware
middleware = PrefactorMiddleware(instance=instance)

# Instrument your own code using the same instance
async with instance.span("custom:preprocessing") as ctx:
    ctx.set_payload({"step": "preprocess", "status": "ok"})

# Run your agent — the middleware traces it automatically under the same instance
result = agent.invoke({"messages": [...]})

async with instance.span("custom:postprocessing") as ctx:
    ctx.set_payload({"step": "postprocess", "result": str(result)})

# You own the instance and client; clean them up yourself
await instance.finish()
await client.close()

If you pass tool_schemas=... with a pre-created instance, the middleware uses those mappings to emit the right tool span types at runtime. The instance's already-registered schema version is not mutated, so you must register matching tool schemas before creating the instance if you want those per-tool span types to appear in the backend schema version.

LangGraph graphs

The middleware only sees agents built with create_agent. To trace a custom LangGraph StateGraph, pass PrefactorCallbackHandler in the run config instead. The handler records a langchain:agent span for the graph run, a langchain:node span for each node, and langchain:llm and langchain:tool spans for the model and tool calls inside each node. Model and tool calls made by a create_agent subagent inside a node appear under that node.

from prefactor_core import PrefactorCoreConfig, SchemaRegistry
from prefactor_http.config import HttpClientConfig
from prefactor_langchain import PrefactorCallbackHandler, register_langchain_schemas

registry = SchemaRegistry()
tool_span_types = register_langchain_schemas(registry)

config = PrefactorCoreConfig(
    http_config=HttpClientConfig(
        api_url="https://app.prefactorai.com", api_token="your-api-token"
    ),
    schema_registry=registry,
)
client = PrefactorCallbackHandler.create_client(config)
await client.initialize()

instance = await client.create_agent_instance(
    agent_id="my-agent",
    agent_version={"name": "My Graph", "external_identifier": "my-graph-v1"},
)
await instance.start()

handler = PrefactorCallbackHandler(instance=instance, tool_span_types=tool_span_types)
result = await graph.ainvoke(state, config={"callbacks": [handler]})

# You own the instance and client; clean them up yourself
await instance.finish()
await client.close()

Do not add PrefactorMiddleware to agents that run inside a traced graph; each model and tool call would be recorded twice. Each span is created with an HTTP request before the node, model or tool call continues, which adds a little latency to every step.

Span Types

This package creates LangChain-specific spans with the langchain:* namespace:

  • langchain:agent - Agent executions and LangGraph graph runs
  • langchain:node - LangGraph node executions (callback handler only)
  • langchain:llm - LLM calls with model metadata (name, provider, token usage)
  • langchain:tool - Tool executions including retrievers

Each span payload includes:

  • Timing information (start_time, end_time)
  • Inputs and outputs
  • Error information with stack traces
  • LangChain-specific metadata

Trace correlation (span_id, parent_span_id, trace_id) is handled automatically by the prefactor-core client.

Features

  • Automatic LLM call tracing - Captures model name, provider, token usage, temperature
  • Tool execution tracing - Records tool name, arguments, execution time
  • Agent/chain tracing - Tracks agent lifecycle and message history
  • Token usage capture - Automatically extracts prompt/completion/total tokens
  • Error tracking - Captures error type, message, and stack traces
  • Automatic parent-child relationships - Uses SpanContextStack for hierarchy
  • Bring your own instance - Share a single AgentInstanceHandle between the middleware and your own instrumentation

Architecture

This package follows the LangChain Adapter Redesign principles:

  1. Package Isolation: LangChain-specific span types and schemas live in this package
  2. Opaque Payloads: Span data is sent as payload to prefactor-core
  3. Type Namespacing: Uses langchain:agent, langchain:llm, langchain:tool prefixes
  4. Uses prefactor-core: All span/instance management via the prefactor-core client

The middleware:

  1. Accepts a PrefactorCoreClient, or a pre-created AgentInstanceHandle, or creates its own client via from_config()
  2. Registers or borrows an agent instance
  3. Creates spans with LangChain-specific payloads
  4. Leverages SpanContextStack for automatic parent detection

Development

Run tests:

pytest tests/

License

MIT

Metadata

Release files for prefactor-langchain 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for prefactor-langchain 0.3.0
File Size Uploaded Provenance Actions
prefactor_langchain-0.3.0.tar.gz 67.1 kB Without provenance Details for prefactor_langchain-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for prefactor-langchain 0.3.0
File Interpreter ABI Platform Actions
prefactor_langchain-0.3.0-py3-none-any.whl Python 3 none any Details for prefactor_langchain-0.3.0-py3-none-any.whl

Total release size: 94.0 kB

Release files / prefactor_langchain-0.3.0.tar.gz

Download URL prefactor_langchain-0.3.0.tar.gz
Size 67.1 kB
Tags Source
SHA-256 checksum
How to use checksums
94a5585124657c9f3040e09486187f8b99367fd668bce1b51dffb539fceb107e
BLAKE2b-256 checksum
How to use checksums
ab9d6e76508b0e01faaedf5c67d8e1854d8c4d0a134d544047fa85ad2e74d382
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / prefactor_langchain-0.3.0-py3-none-any.whl

Download URL prefactor_langchain-0.3.0-py3-none-any.whl
Size 27.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
280f2d3f3f91a01cdb36d6b10da12a3a95181e49e883c1afa60281140be3ba89
BLAKE2b-256 checksum
How to use checksums
096f753659f7707d993e5b0a072e412a43b01ce6a6f33b0c45b8a3058210b96a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for prefactor-langchain 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page