0Pricing
LangChain / RAG / Vector DBs · 강의

사용자 지정 로직으로 검색 체인 확장

복잡한 비즈니스 로직, 전처리 단계 또는 특수 필터링을 통합하는 사용자 지정 검색 체인을 구축합니다.

사용자 지정 로직으로 검색 체인 확장은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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:

  1. User Query
  2. Custom Query Pre-processor
  3. Retriever (e.g., Vector Store)
  4. Custom Document Post-processor
  5. 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 RunnableLambda and RunnablePassthrough as 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 RunnableBranch for conditional logic.

Experiment with these techniques to build highly customized and efficient RAG applications!

자주 묻는 질문

“사용자 지정 로직으로 검색 체인 확장” 강의는 무료인가요?

네 — “사용자 지정 로직으로 검색 체인 확장” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 로직으로 검색 체인 확장”에서 뭘 배우나요?

복잡한 비즈니스 로직, 전처리 단계 또는 특수 필터링을 통합하는 사용자 지정 검색 체인을 구축합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 LangChain / RAG / Vector DBs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“사용자 지정 로직으로 검색 체인 확장” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 LangChain / RAG / Vector DBs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 지정 문서 로더 개발
  2. 사용자 지정 임베딩 모델 통합
  3. 사용자 지정 로직으로 검색 체인 확장
  4. 사용자 지정 출력 파서 만들기
← LangChain / RAG / Vector DBs(으)로 돌아가기