Skip to main content
Back to Integrations Directory
LangChain
FrameworkChain & Agent Integration

LLMSlim + LangChain

Compress document retrievers and chain contexts automatically in LangChain.

Integrate LLMSlim document compression transformers into LangChain pipelines and autonomous agents.

1. Package Installation

Install LLMSlim and the official LangChain SDK using your package manager:

terminal
pip install llmslim langchain-core

2. Architecture & Execution Flow

STEP 01

1. LangChain VectorStoreRetriever fetches matching document chunks.

STEP 02

2. LLMSlim DocumentTransformer prunes redundant prose across chunks.

STEP 03

3. Formatted dense prompt passed into LCEL chain runnable.

3. Production Code Pattern

Complete, runnable implementation wrapper for LangChain:

langchain_llmslim.py
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from llmslim import compress

def compress_input_runnable(input_dict: dict) -> dict:
    raw_context = input_dict["context"]
    slim = compress(raw_context, target_ratio=0.4).compressed_text
    return {"context": slim, "question": input_dict["question"]}

prompt = ChatPromptTemplate.from_template("Context:\n{context}\n\nQuestion: {question}")
model = ChatOpenAI(model="gpt-4o")

# Chain with pre-dispatch prompt compression
chain = compress_input_runnable | prompt | model
res = chain.invoke({"context": "... long text ...", "question": "What is the key takeaway?"})
print(res.content)

4. Production Deployment Best Practices

Use LLMSlim function wrappers as LCEL chain runnables or custom document post-processors.

5. Key Optimization Tips

  • 01.Place LLMSlim compression immediately after retriever steps in LCEL pipelines.

6. Performance Metrics & Benchmark Matrix

Metric DimensionUncompressed PayloadLLMSlim CompressedRecorded Impact
Retrieved Chain Context6,000 tokens2,400 tokens60% Billed Token Reduction

7. Frequently Asked Questions

Can I use LLMSlim in LCEL (LangChain Expression Language)?

Yes. You can pipe custom Python functions using RunnableLambda or standard composition.

8. Troubleshooting & Diagnostics

Issue: TypeError when piping dictionary output in LCEL chain.
Solution: Ensure custom runnable returns a clean dictionary mapping expected prompt variables.