Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę
Zbudują Państwo niestandardowe łańcuchy wyszukiwania integrujące złożoną logikę biznesową, etapy wstępnego przetwarzania lub wyspecjalizowane filtrowanie.
Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę to bezpłatna lekcja LangChain / RAG / Vector DBs na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej LangChain / RAG / Vector DBs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs LangChain / RAG / Vector DBs zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Beyond Basic RAG
Welcome! In this lesson, we'll dive into extending LangChain's retrieval chains. While standard Retrieval Augmented Generation (RAG) is powerful, real-world applications often need more nuanced control.
We'll learn how to inject custom logic into the retrieval process to make your RAG systems smarter and more tailored to specific needs.
Practical Customization Needs
Why would you need custom logic in a retrieval chain? Consider these common scenarios:
- Filtering by User Permissions: Only retrieve documents accessible to the current user.
- Prioritizing Fresh Data: Boost documents created or updated recently.
- Removing Irrelevant Sections: Clean up retrieved text before passing it to the LLM.
- Dynamic Query Rephrasing: Automatically improve user queries for better search results.
These needs go beyond what a basic retriever offers.
LangChain's Custom Primitives
LangChain provides flexible primitives to insert custom Python logic directly into your chains:
RunnableLambda: This allows you to wrap any Python function, making it a runnable component. It's perfect for applying arbitrary transformations.RunnablePassthrough: This simply passes its input through to the next step. It's useful for injecting new keys into the input dictionary or for identity operations.
These are your building blocks for custom steps.
Enhancing User Queries (Pre-processing)
One powerful customization is query pre-processing. This means modifying the user's input query before it's sent to the retriever or vector store.
- You could add specific keywords based on detected intent.
- Expand common abbreviations or synonyms.
- Rephrase the query to improve embedding search results.
This subtle step can significantly boost the relevance of retrieved documents.
Custom Query Transformer Code
Let's see how to implement a simple query pre-processor using RunnableLambda. This example adds a 'detailed search for' prefix to the original query.
from langchain_core.runnables import RunnableLambda
from langchain_core.promnpts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
# Mock LLM for demonstration purposes
class MockLLM(ChatOpenAI):
def invoke(self, input):
return f"LLM processed: {input['enhanced_query']}"
def enhance_query(input_dict):
original_query = input_dict["question"]
return {"enhanced_query": f"detailed search for {original_query}"}
llm = MockLLM() # In a real app, use ChatOpenAI(model="gpt-4")
prompt = ChatPromptTemplate.from_template(
"Answer based on the following search query: {enhanced_query}"
)
custom_chain = (
{"enhanced_query": RunnableLambda(enhance_query)} # Our custom step
| prompt
| llm
)
result = custom_chain.invoke({"question": "latest AI trends"})
print(result)Refining Retrieved Documents (Post-processing)
Another crucial area for custom logic is document post-processing. This occurs after documents have been retrieved but before they are passed to the LLM.
- Filtering: Remove documents that don't meet certain criteria (e.g., outdated, wrong source).
- Re-ranking: Reorder documents based on custom relevance scores.
- Summarizing: Condense lengthy documents to fit context windows.
This ensures the LLM receives the most relevant and concise context, improving answer quality and reducing token usage.
Filtering Documents by Metadata
Here's an example of filtering retrieved documents based on their metadata. We'll simulate a retriever that returns documents and then filter them to only include those from a specific 'blog' source.
from langchain_core.documents import Document
from langchain_core.runnables import RunnableLambda
from langchain_core.promnpts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
# Mock LLM for demonstration
class MockLLM(ChatOpenAI):
def invoke(self, input):
context = input.get("context", "No context provided")
return f"LLM processed docs: {context}"
# Mock retriever returning Documents with metadata
def mock_retrieve(query):
return [
Document(page_content="Doc A about AI", metadata={"source": "blog"}),
Document(page_content="Doc B about ML", metadata={"source": "research"}),
Document(page_content="Doc C about AI ethics", metadata={"source": "blog"}),
]
def filter_by_source(docs, desired_source="blog"):
# Only keep documents from the 'blog' source
return [doc for doc in docs if doc.metadata.get("source") == desired_source]
llm = MockLLM()
prompt = ChatPromptTemplate.from_template(
"Answer based on the following context: {context}"
)
# Build a simple chain with retrieval and custom filter
custom_retrieval_chain = (
RunnableLambda(mock_retrieve) # Simulate retrieval
| RunnableLambda(filter_by_source) # Apply custom filter
| (lambda docs: {"context": "\n\n".join([d.page_content for d in docs])}) # Format for LLM
| prompt
| llm
)
result = custom_retrieval_chain.invoke("AI topics")
print(result)End-to-End Custom Chain
You can combine both query pre-processing and document post-processing within a single LangChain chain. The flow would look something like this:
- User Query
- Custom Query Pre-processor
- Retriever (e.g., Vector Store)
- Custom Document Post-processor
- LLM for Answer Generation
This modular approach gives you fine-grained control over every step of your RAG pipeline, making it highly adaptable to complex requirements.
Advanced: Conditional Routing
For even more dynamic behavior, LangChain offers RunnableBranch. This powerful construct allows your chain to take different paths based on certain conditions.
For example, you could:
- Use one retriever if the query is about 'code' and another for 'general knowledge'.
- Apply different document filters based on the user's role.
RunnableBranch enables sophisticated, context-aware RAG workflows.
Check Your Understanding
Which LangChain primitive is best suited for inserting a simple Python function to modify data (e.g., filter a list of documents) within a chain?
Recap: Extending Retrieval
Great job! In this lesson, you learned how to extend LangChain retrieval chains with custom logic:
- We explored the need for customization in real-world RAG.
- You discovered
RunnableLambdaandRunnablePassthroughas key tools. - We saw how to pre-process queries for better retrieval.
- You learned to post-process retrieved documents for refined context.
- We touched on advanced concepts like
RunnableBranchfor conditional logic.
Experiment with these techniques to build highly customized and efficient RAG applications!
Ucz się LangChain / RAG / Vector DBs dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 12
- Lekcje
- 48
Często zadawane pytania
Czy lekcja „Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę” jest bezpłatna?
Tak — pełny tekst „Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu LangChain / RAG / Vector DBs, przejdź na CoddyKit PRO. Kurs LangChain / RAG / Vector DBs zawiera 4 lekcji w sumie.
Co nauczysz się w „Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę”?
Zbudują Państwo niestandardowe łańcuchy wyszukiwania integrujące złożoną logikę biznesową, etapy wstępnego przetwarzania lub wyspecjalizowane filtrowanie. Ćwiczysz LangChain / RAG / Vector DBs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć LangChain / RAG / Vector DBs?
Nie wymagamy żadnego doświadczenia. LangChain / RAG / Vector DBs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.
Ile czasu zajmuje lekcja „Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji LangChain / RAG / Vector DBs?
Tak. Każda lekcja LangChain / RAG / Vector DBs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Tworzenie niestandardowych loaderów dokumentów
- Integracja niestandardowych modeli embeddingów
- Rozszerzanie łańcuchów wyszukiwania o niestandardową logikę
- Tworzenie niestandardowych parserów wyników