1️⃣QueryEngine

https://docs.llamaindex.ai/en/stable/module_guides/deploying/query_engine/

QueryEngine은 데이터에 대해 질문할 수 있는 일반적인 인터페이스입니다.쿼리 엔진은 자연어 쿼리를 받아 풍부한 응답을 반환합니다. 쿼리 엔진은 대부분 검색기를 통해 하나 또는 여러 개의 인덱스를 기반으로 구축됩니다여러 개의 쿼리 엔진을 구성하여 고급 기능을 구현할 수 있습니다.

기본 사용 예시는 아래와 같습니다.

query_engine = index.as_query_engine()
response = query_engine.query("Who is Paul Graham.")

Response 응답의 steaming 설정:

query_engine = index.as_query_engine(streaming=True) streaming_response = query_engine.query("Who is Paul Graham.") streaming_response.print_response_stream()

LlmaIndex의 QueryEngine에서 Advanced 방법론인 RouterQueryEngineSub-Qenstion Query Engine의 사례를 알아보겠습니다.


SubQuestionQueryEngine

SubQuestionQueryEngine은 주로 둘 이상의 데이터 원본이 제공되는 복잡한 쿼리를 처리하도록 설계되었으며, 특정 카테고리를 비교하고 대조하는 쿼리가 트리거되는 경우가 많습니다.

SubQuestionQueryEngine은 데이터 원본에 대한 설명이 주어진 하위 질문을 생성합니다. 그런 다음 선택한 데이터 원본에 대해 하위 질문을 실행하고 하위 응답을 수집한 후 최종 답변을 합성합니다.

Step 1: Setup Environments

#!pip install -q llama_index pypdf
import logging, sys, os
import nest_asyncio
from dotenv import load_dotenv  

nest_asyncio.apply()

!echo "OPENAI_API_KEY=<Your OpenAI Key>" >> .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

Step 2: Download Data

2021년 및 2022년 재무 보고서 요약본을 fiscal.treasury.gov 웹사이트에서 다운로드하여 'report' 디렉터리에 저장합니다.

!mkdir reports
!wget https://www.fiscal.treasury.gov/files/reports-statements/financial-report/2021/executive-summary-2021.pdf -O ./reports/executive-summary-2021.pdf
!wget https://www.fiscal.treasury.gov/files/reports-statements/financial-report/2022/executive-summary-2022.pdf -O ./reports/executive-summary-2022.pdf

Step 3: Load data & define `SubQuestionQueryEngin``

from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.tools import QueryEngineTool, ToolMetadata
from llama_index.core.query_engine import SubQuestionQueryEngine

#load data
report_2021_docs = SimpleDirectoryReader(input_files=["reports/executive-summary-2021.pdf"]).load_data()
print(f"loaded executive summary 2021 with {len(report_2021_docs)} pages")

report_2022_docs = SimpleDirectoryReader(input_files=["reports/executive-summary-2022.pdf"]).load_data()
print(f"loaded executive summary 2022 with {len(report_2022_docs)} pages")

#build indices
report_2021_index = VectorStoreIndex.from_documents(report_2021_docs)
print(f"built index for executive summary 2021 with {len(report_2021_index.docstore.docs)} nodes")

report_2022_index = VectorStoreIndex.from_documents(report_2022_docs)
print(f"built index for executive summary 2022 with {len(report_2022_index.docstore.docs)} nodes")

#build query engines
report_2021_engine = report_2021_index.as_query_engine(similarity_top_k=3)
report_2022_engine = report_2022_index.as_query_engine(similarity_top_k=3)

#build query engine tools
query_engine_tools = [
    QueryEngineTool(
        query_engine = report_2021_engine,
        metadata = ToolMetadata(name='executive_summary_2021', description='미국 정부 재무 보고서 요약 2021에 대한 정보 제공')
    ),
    QueryEngineTool(
        query_engine = report_2022_engine,
        metadata = ToolMetadata(name='executive_summary_2022', description='미국 정부 재무 보고서 요약 2022에 대한 정보 제공')
    )
]

#define SubQuestionQueryEngine
sub_question_engine = SubQuestionQueryEngine.from_defaults(query_engine_tools=query_engine_tools)
loaded executive summary 2021 with 11 pages
loaded executive summary 2022 with 10 pages
built index for executive summary 2021 with 16 nodes
built index for executive summary 2022 with 11 nodes

Step 4: Execute Queries

from IPython.display import Markdown

response = sub_question_engine.query("2021년과 2022년의 국방부 비용을 비교 및 대조해줄래?")
display(Markdown(f"<b>{response}</b>"))
Generated 2 sub questions.
[executive_summary_2021] Q: Compare defense budget of 2021
[executive_summary_2022] Q: Compare defense budget of 2022
[executive_summary_2021] A: The defense budget of 2021 is not explicitly mentioned in the provided context information.
[executive_summary_2022] A: The defense budget of 2022 saw a notable increase, with the Department of Defense's net costs rising by $568.4 billion primarily due to changes in assumptions and other factors. This increase was driven by a $444.2 billion loss increase from changes in assumptions, along with additional costs related to military operations, readiness, support, procurement, personnel, and research and development.


2021년의 국방 예산은 명시적으로 언급되지 않았습니다. 그러나 2022년의 국방 예산은 근본적으로 가정의 변화와 기타 요인들로 인해 국방부의 순 비용이 5684억 달러 증가했습니다. 이 증가는 가정의 변화로 인한 4442억 달러의 손실 증가와 함께 군사 작전, 전투 준비, 지원, 조달, 인력, 연구 및 개발과 관련된 추가 비용에 기인합니다.

response = sub_question_engine.query("2021년과 2022년의 총 부채를 비교하고 대조해줄래?")
display(Markdown(f"<b>{response}</b>"))
Generated 2 sub questions.
[executive_summary_2021] Q: 2021년의 총 부채는 얼마인가요?
[executive_summary_2022] Q: 2022년의 총 부채는 얼마인가요?
[executive_summary_2021] A: 2021년의 총 부채는 100%입니다.
[executive_summary_2022] A: 2022년의 총 부채는 $39.0 트리리언입니다.


2021년의 총 부채는 100%이며, 2022년의 총 부채는 $39.0 트리리언입니다.

response = sub_question_engine.query("2021년과 2022년의 정부 세금 및 기타 수입을 비교해줄래?")
display(Markdown(f"<b>{response}</b>"))
Generated 4 sub questions.
[executive_summary_2021] Q: Compare government taxes between 2021 and 2022
[executive_summary_2021] Q: Compare other government revenues between 2021 and 2022
[executive_summary_2022] Q: Compare government taxes between 2021 and 2022
[executive_summary_2022] Q: Compare other government revenues between 2021 and 2022
[executive_summary_2022] A: In 2022, total government tax and other revenues increased by $670.0 billion compared to 2021. This growth was primarily driven by increases in individual income tax collections and tax withholdings.
[executive_summary_2022] A: In 2022, total government tax and other revenues increased by $670.0 billion to about $4.9 trillion. This increase was primarily driven by growth in individual income tax collections and tax withholdings. In comparison, the total government tax and other revenues for 2021 are not explicitly provided in the context information.
[executive_summary_2021] A: In 2021, total government tax and other revenues increased by $684.3 billion to about $4.3 trillion. The increase was primarily due to growth in income taxes collections, partially offset by increased refunds. Individual income tax, tax withholdings, and corporate taxes accounted for about 87.7% of total tax and other revenues in 2021. Other revenues included Federal Reserve earnings, excise taxes, and customs duties.
[executive_summary_2021] A: Total government tax and other revenues increased by $684.3 billion in FY 2021 compared to the previous year. The increase was primarily due to growth in income taxes collections, partially offset by increased refunds. Individual income tax, tax withholdings, and corporate taxes accounted for about 87.7% of total tax and other revenues in FY 2021. Other revenues include Federal Reserve earnings, excise taxes, and customs duties.


2021년에는 총 정부 세금 및 기타 수입이 약 4.3조 달러로 증가했고, 주로 소득세 수입의 증가와 환급액의 증가로 이루어졌습니다. 개인 소득세, 세금 공제, 법인세가 총 세금 및 기타 수입의 약 87.7%를 차지했습니다. 반면, 2022년에는 총 정부 세금 및 기타 수입이 약 4.9조 달러로 증가했고, 주로 개인 소득세 수입과 세금 공제의 증가로 이루어졌습니다.

response = sub_question_engine.query("2021년과 2022년 사이의 개인 소득세 및 원천징수, 법인 소득세, 기타 수입을 세부 금액으로 비교해줄래?")
display(Markdown(f"<b>{response}</b>"))
Generated 8 sub questions.
[executive_summary_2021] Q: 개인 소득세 2021년 금액 조회
[executive_summary_2022] Q: 개인 소득세 2022년 금액 조회
[executive_summary_2021] Q: 원천징수 2021년 금액 조회
[executive_summary_2022] Q: 원천징수 2022년 금액 조회
[executive_summary_2021] Q: 법인 소득세 2021년 금액 조회
[executive_summary_2022] Q: 법인 소득세 2022년 금액 조회
[executive_summary_2021] Q: 기타 수입 2021년 금액 조회
[executive_summary_2022] Q: 기타 수입 2022년 금액 조회
[executive_summary_2021] A: $4.3 조
[executive_summary_2021] A: $4.3 trillion
[executive_summary_2022] A: Corporate income tax for 2022 was not explicitly mentioned in the provided context information.
[executive_summary_2021] A: Individual income tax collections increased by $684.3 billion to about $4.3 trillion for FY 2021.
[executive_summary_2022] A: $670.0 billion
[executive_summary_2022] A: Individual income tax collections for FY 2022 increased, contributing to the total government tax and other revenues reaching about $4.9 trillion.
[executive_summary_2021] A: Corporate income tax amount for 2021 can be found by deducting the total government tax and other revenues of $4.3 trillion from the net operating cost of $3.1 trillion, resulting in a corporate income tax amount of $1.2 trillion for the year 2021.
[executive_summary_2022] A: The FY 2022 Financial Report of the U.S. Government provides detailed information on the government's financial position and condition for the fiscal years ended September 30, 2022, and 2021. It includes key metrics such as the budget deficit, net operating cost, government's gross costs, revenues, assets, liabilities, debt-to-GDP ratio, and long-term fiscal projections. For specific details on withholding tax amounts for 2022, refer to the financial report available through the provided links for Treasury, OMB, and GAO.


For the year 2021, individual income tax collections were about $4.3 trillion, while withholding tax amounted to $4.3 trillion as well. Corporate income tax for 2021 was $1.2 trillion, and other revenues totaled $4.3 trillion. Moving to 2022, individual income tax collections increased to contribute to total government tax and other revenues reaching about $4.9 trillion. However, specific details on withholding tax amounts for 2022 were not provided. Corporate income tax for 2022 was not explicitly mentioned. Other revenues for 2022 amounted to $670.0 billion.


RouterQueryEngine

Private 데이터에 대한 LLM 기반 쿼리에는 여러 가지 기술이 있습니다. 몇 가지 예를 들어보겠습니다:

  • 요약(Summarization)

  • 상위 k 시맨틱 검색(Top-k semantic search)

  • 비교 및 대조와 같은 복잡한 쿼리(Complex queries such as compare and contrast)

라우터 쿼리 엔진은 쿼리를 여러 쿼리 엔진으로 라우팅하는 하나의 단일 인터페이스입니다. 여러 후보 쿼리 엔진 중 하나를 선택하여 쿼리를 실행합니다.

Step 1: Install and Setup

#%pip install -q llama_index pypdf
import logging, sys, os
import nest_asyncio
from dotenv import load_dotenv  

nest_asyncio.apply()

!echo "OPENAI_API_KEY=<YOUR OpenAI Key>" >> .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

Step 2: Load data & define RouterQueryEngine

from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, SummaryIndex
from llama_index.core.node_parser import SimpleNodeParser
from llama_index.core.tools import QueryEngineTool, ToolMetadata
from llama_index.core.query_engine.router_query_engine import RouterQueryEngine
from llama_index.core.selectors.llm_selectors import LLMSingleSelector

documents = SimpleDirectoryReader("data").load_data()
print(f"loaded {len(documents)} documents")

node_parser = SimpleNodeParser.from_defaults()
nodes = node_parser.get_nodes_from_documents(documents)

# construct summary_index and vector_index
summary_index = SummaryIndex(nodes)
vector_index = VectorStoreIndex(nodes)

# define summary_query_engine and vector_query_engine
summary_query_engine = summary_index.as_query_engine(
    response_mode="tree_summarize",
    use_async=True,
)
vector_query_engine = summary_index.as_query_engine()

# build summary_tool and vector_tool
summary_tool = QueryEngineTool.from_defaults(
    query_engine=summary_query_engine,
    description="DevSecOps 도구에 대한 요약 질문에 유용합니다.",
)
vector_tool = QueryEngineTool.from_defaults(
    query_engine=vector_query_engine,
    description="개발자 도구에서 특정 컨텍스트를 검색하는 데 유용합니다.",
)

# define RouterQueryEngine
query_engine = RouterQueryEngine(
    selector=LLMSingleSelector.from_defaults(),
    query_engine_tools=[
        summary_tool,
        vector_tool,
    ],
    verbose=True,
)
loaded 49 documents

Step 3: Execute Queries

from IPython.display import Markdown

response = query_engine.query("DevOps 셀프 서비스 중심 파이프라인 보안 및 가드레일에 대해 요약해 주세요.")
display(Markdown(f"<b>{response}</b>"))
Selecting query engine 0: DevSecOps 도구에 대한 요약 질문에 유용하다..


DevOps 셀프 서비스 중심 파이프라인 보안 및 가드레일은 파이프라인 보안을 강화하고 안전을 보장하기 위한 중요한 구현 요소로, Harden-Runner와 Infracost와 같은 도구들을 활용하여 악의적인 패턴을 감지하고 예방하며 클라우드 비용을 사전에 파악하여 비정상적인 비용을 방지합니다. 이러한 조치는 루트 사용자의 활동을 모니터링하고 보안을 강화하며, 인프라스트럭처 코드를 분석하여 구성 오류를 식별하는 도구들을 포함하여 파이프라인의 안전성과 비용 관리를 강화합니다.

response = query_engine.query("TFLint를 사용하여 클라우드 비용을 관리할 수 있나요? 그렇지 않다면 어떤 도구로 클라우드 비용을 관리할 수 있나요?")
display(Markdown(f"<b>{response}</b>"))
Selecting query engine 1: TFLint은 Terraform 코드의 오류를 찾는 데 사용되는 도구이며, 클라우드 비용을 관리하는 데 사용되지 않습니다. 클라우드 비용을 관리하기 위해서는 다른 도구들이 필요합니다..


Infracost를 사용하여 클라우드 비용을 관리할 수 있습니다. Infracost는 DevOps, SRE 및 엔지니어들이 비용을 분석하고 변경하기 전에 비용을 이해할 수 있도록 도와주는 도구로, 비정상적인 클라우드 비용 추정치를 감지하여 팀에 안전장치를 제공합니다.

response = query_engine.query("하든 러너와 인프라코스트를 비교하고 대조하세요. 각 도구는 언제 사용해야 하나요?")
display(Markdown(f"<b>{response}</b>"))
Selecting query engine 0: DevSecOps 도구에 대한 요약 질문에 유용하다..


하든 러너는 Terraform 코드의 보안을 강화하고 취약점을 식별하는 데 사용되며, 인프라코스트는 클라우드 리소스의 비용을 추정하고 비교하는 데 사용됩니다. 따라서 보안 감사 및 취약점 식별이 필요한 경우 하든 러너를 사용하고, 비용 추정 및 비교가 필요한 경우 인프라코스트를 사용해야 합니다.

Last updated