LangChain은 어떻게 셀프 쿼리를 구현하는가
LangChain은 LLM 오케스트레이션을 위한 매우 인기 있는 오픈 소스 라이브러리입니다. 최근 LangChain은 “Self Query” retriever를 추가했습니다. “Self Query” retriever를 사용하면 LangChain을 사용하여 Milvus 같은 벡터 데이터베이스를 쿼리할 수 있습니다. 이 self-query retriever가 어떻게 구현되어 있는지 살펴보겠습니다. self-query 폴더의 base.py 파일 189행부터 233행까지를 다룹니다. 이 게시물에서는 유일한 클래스 메서드인 from_llm도 다룹니다.
이 게시물에서 다룰 내용은 다음과 같습니다:
- Self Query 클래스 메서드 정의
- Self-Query 매개변수 파싱
- LLM Chain 생성
- Self Query Retriever 반환
Self query 클래스 메서드 정의
self query 기본 클래스의 유일한 클래스 메서드는 from_llm입니다. 지정된 매개변수는 8개이며, 키워드 인수(kwargs)를 전달할 수 있게 해주는 매개변수가 하나 있습니다. 클래스의 첫 번째 “매개변수”가 cls라는 것을 눈치챘을 수도 있습니다. Python에 대한 정식 교육을 받지 않았다면, PEP8에 따르면 cls와 self의 차이는 단순히 스타일과 사용 방식의 문제입니다.
self query 클래스를 생성하는 데 필요한 필수 매개변수는 네 가지입니다: llm, vectorstore, document_contents, metadata_field_info.
llm은 언어 모델을 전달하는 데 사용됩니다.vectorstore는 Milvus 같은 벡터 스토어를 전달하는 데 사용됩니다.document_contents매개변수의 이름은 다소 오해의 소지가 있습니다. 저장된 문서의 실제 내용을 의미하는 것이 아니라, 해당 문서에 대한 짧은 설명을 의미합니다.metadata_field_info는AttributeInfo객체의 시퀀스로, 벡터 데이터베이스의 데이터에 대한 정보를 담고 있는 딕셔너리입니다.
필수 매개변수 다음에는 선택적 매개변수가 옵니다. 이것들도 네 가지입니다: structured_query_translator, chain_kwargs, enable_limit, use_original_query. 처음 두 개의 기본값은 None이고, 뒤의 두 개는 False입니다.
structured_query_translator 매개변수를 사용하면 translator를 전달할 수 있습니다. Translators는 표현식을 각 벡터 데이터베이스에 대한 필터 문으로 변환합니다. 이러한 필터 문은 사용 방식에 따라 “allowed_comparators” 또는 “allowed_operators”로 chain_kwargs에 전달됩니다. 각 벡터 스토어에는 고유한 comparators와 operators가 있습니다. 예를 들어, 이것들은 Milvus에서 허용되는 boolean expressions입니다.
enable_limit 매개변수를 사용하면 limit operator를 활성화할지 여부를 결정할 수 있습니다. 이 operator는 검색할 문서 수를 제한하는 LangChain의 기본 기능입니다. 마지막 매개변수는 use_original_query로, 원래 쿼리를 사용할지 LLM이 생성한 쿼리를 사용할지 결정합니다.
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel,
vectorstore: VectorStore,
document_contents: str,
metadata_field_info: Sequence[Union[AttributeInfo, dict]],
structured_query_translator: Optional[Visitor] = None,
chain_kwargs: Optional[Dict] = None,
enable_limit: bool = False,
use_original_query: bool = False,
**kwargs: Any,
) -> "SelfQueryRetriever":
self query 매개변수 파싱
매개변수를 어떻게 처리하는지 설명하겠습니다. 전달된 매개변수에 따라 일련의 if 문을 사용하여 무엇을 할지 결정합니다.
먼저, 이미 정의된 structured query translator가 있는지 확인합니다. 없다면 정의된 벡터 스토어에 대한 내장 translator를 사용합니다.
다음으로, 체인의 키워드 인수를 확인합니다. 이를 전달된 값으로 설정하거나 빈 딕셔너리로 둘 수 있습니다. 이어지는 두 개의 if 문에서 이러한 인수를 계속 확인합니다. 우리가 찾는 두 키는 허용된 비교자와 연산자입니다. 이러한 키는 필터 표현식을 어떻게 작성할 수 있는지를 결정합니다.
if structured_query_translator is None:
structured_query_translator = _get_builtin_translator(vectorstore)
chain_kwargs = chain_kwargs or {}
if (
"allowed_comparators" not in chain_kwargs
and structured_query_translator.allowed_comparators is not None
):
chain_kwargs[
"allowed_comparators"
] = structured_query_translator.allowed_comparators
if (
"allowed_operators" not in chain_kwargs
and structured_query_translator.allowed_operators is not None
):
chain_kwargs[
"allowed_operators"
] = structured_query_translator.allowed_operators
LLM 체인 생성하기
모든 것이 정의되었으므로 이제 쿼리 생성자를 만들 수 있습니다. 이 단계에서는 쿼리 생성자에서 load_query_constructor_runnable 함수를 호출합니다. 이 단계에 대해서는 다른 글에서 더 깊이 살펴보겠습니다.
LLM, 문서 콘텐츠 설명, 메타데이터 필드, limit을 활성화할지 여부, 그리고 체인에 전달할 키워드 인수를 전달해야 합니다. 이러한 요소를 모두 정의한 후 함수는 지정된 스크립트를 실행할 수 있게 해주는 Runnable 객체를 반환합니다.
query_constructor = load_query_constructor_runnable(
llm,
document_contents,
metadata_field_info,
enable_limit=enable_limit,
**chain_kwargs,
)
셀프 쿼리 검색기 반환하기
이 클래스 메서드의 끝에서는 셀프 쿼리 검색기를 반환해야 합니다. 이 메서드는 셀프 쿼리 클래스의 인스턴스를 반환합니다. 방금 정의한 쿼리 생성자와 함께 전달된 벡터 스토어, 원본 쿼리를 사용할지 여부, 번역기, 그리고 키워드 인수 목록을 전달합니다.
return cls(
query_constructor=query_constructor,
vectorstore=vectorstore,
use_original_query=use_original_query,
structured_query_translator=structured_query_translator,
**kwargs,
)
LangChain이 셀프 쿼리를 구현하는 방식 요약
이 글에서는 LangChain이 “셀프 쿼리”라고 부르는 개념을 어떻게 구현하는지 다루었습니다. 이는 간단한 검색 증강 생성(RAG) 애플리케이션을 구축하는 방법입니다. LLM, 벡터 데이터베이스, 그리고 LLM과 인터페이스하기 위한 몇 가지 프롬프트라는 동일한 구성 요소를 모두 사용합니다.
셀프 쿼리는 LangChain에서 꽤 큰 코드 블록이지만, 이 글에서는 특히 클래스 메서드 from_llm을 다룹니다. 이 메서드를 사용하면 네 개의 필수 필드만 전달하여 RAG 앱을 만들 수 있습니다. LLM, 벡터 데이터베이스, 문서에 대한 설명, 그리고 메타데이터 정보입니다. LLM과 벡터 데이터베이스에 대해 더 알고 싶으신가요? Discord에서 저희와 대화해 보세요.
계속 읽기

Zilliz Cloud Now Available in AWS Europe (Ireland)
Zilliz Cloud launches in AWS eu-west-1 (Ireland) — bringing low-latency vector search, EU data residency, and full GDPR-ready infrastructure to European AI teams. Now live across 30 regions on five cloud providers.

Announcing the General Availability of Zilliz Cloud BYOC on Google Cloud Platform
Zilliz Cloud BYOC on GCP offers enterprise vector search with full data sovereignty and seamless integration.

Democratizing AI: Making Vector Search Powerful and Affordable
Zilliz democratizes AI vector search with Milvus 2.6 and Zilliz Cloud for powerful, affordable scalability, cutting costs in infrastructure, operations, and development.



