Compress document retrievers and chain contexts automatically in LangChain.
Integrate LLMSlim document compression transformers into LangChain pipelines and autonomous agents.
Install LLMSlim and the official LangChain SDK using your package manager:
pip install llmslim langchain-core1. LangChain VectorStoreRetriever fetches matching document chunks.
2. LLMSlim DocumentTransformer prunes redundant prose across chunks.
3. Formatted dense prompt passed into LCEL chain runnable.
Complete, runnable implementation wrapper for LangChain:
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)| Metric Dimension | Uncompressed Payload | LLMSlim Compressed | Recorded Impact |
|---|---|---|---|
| Retrieved Chain Context | 6,000 tokens | 2,400 tokens | 60% Billed Token Reduction |
Yes. You can pipe custom Python functions using RunnableLambda or standard composition.