Skip to main content
Mortem integrates with LangChain through a callback handler. You attach the handler to your chain or agent, and Mortem automatically records each LLM call and tool invocation as a trace event. No changes to your prompt templates, chains, or tool definitions are required.

What gets captured

The MortemCallbackHandler intercepts LangChain lifecycle events and records:
  • LLM calls — model name, prompts passed to the LLM, and the full output
  • Tool calls — tool name, input string, and output string
  • Errors — failures on any LLM or tool step are recorded as failed events on the trace

Prerequisites

Install the SDK and create an agent in the dashboard before continuing. You need MORTEM_API_KEY and MORTEM_AGENT_ID set in your environment. LangChain (langchain and @langchain/core) must be installed separately — Mortem does not depend on them.

Integration

1

Initialize the Mortem client

Create a Mortem instance at module scope.
verifyToken is only needed during your first deployment. Once the dashboard shows the agent as verified, remove MORTEM_VERIFY_TOKEN from your environment and code.
2

Create the callback handler

Call mortem.langchainHandler() to get a MortemCallbackHandler instance. This is a synchronous call that returns the handler immediately.
Alternatively, import createLangChainHandlerAsync directly from the SDK if you want a handler that dynamically subclasses BaseCallbackHandler from @langchain/core. This is useful when you need the handler to satisfy strict instanceof checks in framework code:
Use createLangChainHandlerAsync when passing the handler to LangChain APIs that require an instance of BaseCallbackHandler. The synchronous mortem.langchainHandler() works for most use cases where duck-typing is sufficient.
3

Attach the handler to your chain or agent

Pass the handler in the callbacks array when invoking your chain. You can add it at the chain level, the model level, or at the point of invocation — LangChain propagates callbacks through the call tree.
4

Wrap the invocation in a Mortem session

Create a session with mortem.startSession and run the chain inside session.run. This links the callback handler’s events to the active trace.
Always call mortem.close() in a finally block. It flushes the trace buffer and ensures all events reach the ingest service before the process exits.

Complete example

Handler variants

The SDK exports three ways to create a LangChain callback handler:
You can import createLangChainHandler and createLangChainHandlerAsync directly from @mortemlabs/sdk without a Mortem client instance. This is useful if you manage the handler lifecycle separately from the client.

Agent callbacks

For LangChain agents, pass the handler in the callbacks array at the agent executor level. LangChain propagates the handler to all nested chains and tools automatically: