Skip to content
Zurück zur Startseite

§ INTEGRATION · LANGCHAIN

LangChain-Callback-Handler

Installieren Sie das optionale Extra, hängen Sie den Handler an die Callbacks Ihrer Chain an, und jeder LLM-Aufruf, Tool-Aufruf, Retriever-Lookup und Agent-Schritt wird gesteuert und nachverfolgt — Python und TypeScript.

§ 01

Voraussetzungen

  • Execlave-Konto mit aktivem API-Schlüssel — Einstellungen → API-Schlüssel.
  • Ein registrierter Agent in Execlave. Verwenden Sie die lowercase-kebab agentId des Agents im Handler.
  • LangChain >=0.3 (Python) oder @langchain/core >=0.3 (JS).
§ 02

Installation

Der Handler ist über ein optionales Extra verfügbar, sodass die Standardinstallation des SDK LangChain nicht als transitive Abhängigkeit mitzieht.

Python

pip install 'execlave-sdk[langchain]'

JavaScript / TypeScript

npm install @execlave/sdk @langchain/core
§ 03

Sofort-Einrichtung mit einem Copilot

Fügen Sie diesen Prompt in Ihren KI-Coding-Assistenten ein (Cursor, Claude Code, ChatGPT, Copilot). Er verbindet Execlave mit Ihrem bestehenden LangChain-Code, ohne Ihre Chains umzuschreiben.

§ Copy prompt · paste into your AI coding assistant
You are adding Execlave (an AI agent governance platform) to an existing LangChain application. Do not rewrite existing chains — only wire the callback handler. Rules you MUST follow:1. Install the correct extra. Python: `pip install 'execlave-sdk[langchain]'`. JS/TS: `npm install @execlave/sdk @langchain/core`.2. Read `EXECLAVE_API_KEY` from environment variables. Never hardcode keys.3. Create exactly ONE Execlave client per process and reuse it. Python: `exe = Execlave(api_key=os.environ["EXECLAVE_API_KEY"])`. JS: `const exe = new Execlave({ apiKey: process.env.EXECLAVE_API_KEY! })`.4. Create an `ExeclaveCallbackHandler` per logical agent (stable `agent_id`/`agentId` string, lowercase-kebab). Do NOT create a new handler per request.5. Attach the handler via the `callbacks` field on the invoke/stream config — do not replace the user's existing callbacks, append to them.6. Import path: Python `from execlave.integrations.langchain import ExeclaveCallbackHandler`. JS `import { ExeclaveCallbackHandler } from '@execlave/sdk/integrations/langchain'`.7. Wrap `chain.invoke` / `chain.stream` in try/except for `execlave.errors.PolicyBlockedError` (Python) or `PolicyBlockedError` from `@execlave/sdk` (JS). On block, return a structured 4xx response containing `exc.violations` (list of { policyId, message, severity }). Do NOT swallow the error silently.8. Do NOT call `exe.enforce_policy` manually before invoking the chain — the handler already runs enforcement on chain start and every tool call.9. Do NOT use the deprecated `run_langchain()` helper. It still ships today but emits a DeprecationWarning and will be removed in execlave-sdk 2.0 — use `ExeclaveCallbackHandler` instead.10. On process shutdown, call `exe.flush()` (sync) or `await exe.shutdown()` (JS) so in-flight spans are not dropped. Deliverables:- Add the install command to the project's package manifest (requirements.txt / pyproject / package.json).- Add env vars `EXECLAVE_API_KEY` and optional `EXECLAVE_BASE_URL` to `.env.example`.- Show me a single diff per file. Do not modify unrelated code. Reference: https://www.execlave.com/docs/integrations/langchainAPI reference: https://www.execlave.com/docs/sdk-reference
§ 04

Schnellstart

Ein Handler verbindet Durchsetzung und Tracing mit jedem Callback, den LangChain auslöst. Keine Decorators, keine Wrapper-Funktionen.

Python

from execlave import Execlavefrom execlave.integrations.langchain import ExeclaveCallbackHandlerfrom langchain_openai import ChatOpenAIfrom langchain_core.prompts import ChatPromptTemplate exe = Execlave(api_key="exe_prod_...")handler = ExeclaveCallbackHandler(exe, agent_id="support-bot") prompt = ChatPromptTemplate.from_messages([("user", "{question}")])llm = ChatOpenAI(model="gpt-4o-mini")chain = prompt | llm # Enforcement fires on the chain's top-level input and on every tool call.# A PolicyBlockedError short-circuits the chain before the LLM is called.answer = chain.invoke(    {"question": "Summarize our Q3 pipeline"},    config={"callbacks": [handler]},)

JavaScript / TypeScript

import { Execlave } from '@execlave/sdk';import { ExeclaveCallbackHandler } from '@execlave/sdk/integrations/langchain';import { ChatOpenAI } from '@langchain/openai';import { ChatPromptTemplate } from '@langchain/core/prompts'; const exe = new Execlave({ apiKey: process.env.EXECLAVE_API_KEY! });const handler = new ExeclaveCallbackHandler(exe, { agentId: 'support-bot' }); const prompt = ChatPromptTemplate.fromMessages([['user', '{question}']]);const chain = prompt.pipe(new ChatOpenAI({ model: 'gpt-4o-mini' })); const answer = await chain.invoke(  { question: 'Summarize our Q3 pipeline' },  { callbacks: [handler] },);
§ 05

Was instrumentiert wird

Jeder LangChain-Callback wird einem Span unter derselben Trace-ID zugeordnet, sodass Sie den vollständigen Chain-Baum in einer Ansicht sehen.

CallbackSpan-ArtHinweise
on_chain_start / handleChainStartchainTop-Level-Chain-Inputs werden durch die Pre-Execution-Durchsetzung geleitet.
on_llm_start / handleLLMStartllmErfasst Modellnamen und Completion-Input.
on_chat_model_start / handleChatModelStartllmErfasst strukturierte Chat-Nachrichten und behält Rollen-Metadaten bei.
on_tool_start / handleToolStarttoolJeder Tool-Aufruf wird durchgesetzt, wobei der Tool-Name in die Allowlist-Prüfung einfließt.
on_agent_action / handleAgentActionagentErfasst einen Planungsschritt eines AgentExecutor.
on_retriever_start / handleRetrieverStartretrieverErfasst einen RAG-Lookup. Der Seiteninhalt wird niemals weiterleitet.
*_errorDer Span wird als Fehler geschlossen, der Status des übergeordneten Trace wird auf Fehler gesetzt.
§ 06

Umgang mit Blockierungen

Die Durchsetzung läuft beim Top-Level-Input der Chain und bei jedem Tool-Aufruf. Ein blockierter Aufruf löst PolicyBlockedError mit der genauen Liste der Verstöße aus; vorübergehende Durchsetzungsfehler werden protokolliert und die Chain läuft weiter (fail-open).

Python

from execlave.errors import PolicyBlockedError try:    chain.invoke({"question": user_input}, config={"callbacks": [handler]})except PolicyBlockedError as exc:    # Policy blocked the request before the LLM was called.    # exc.violations contains the matched policies.    return {"error": "blocked", "violations": exc.violations}

JavaScript / TypeScript

import { PolicyBlockedError } from '@execlave/sdk'; try {  await chain.invoke({ question: userInput }, { callbacks: [handler] });} catch (err) {  if (err instanceof PolicyBlockedError) {    return { error: 'blocked', violations: err.violations };  }  throw err;}
§ 07

Migration von run_langchain()

run_langchain() ist veraltet. Für agentenförmige Workflows verwenden Sie den Callback-Handler — er erfasst Tool-Aufrufe, Retriever-Treffer und verschachtelte Chain-Spans, die der Helper nicht sehen kann.

Wann was verwenden

  • ExeclaveCallbackHandler — Agents, Tool-Nutzung, Retrievers, LCEL-Chains mit Verzweigungen, alles mit Child-Runs.
  • run_langchain() — einzelner Invoke, keine Tools, kein Retriever. Gibt eine DeprecationWarning aus; wird in execlave-sdk 2.0 entfernt.
§ 08

Wie geht es weiter?

LangChain-Integration — Execlave Docs