Skip to content

Commit e73f484

Browse files
committed
user input 관련 코드 제거 및 그래프 구조 수정 # 134
- 쿼리 리파이너 관련 함수 및 노드 삭제 - 기본 및 확장 그래프에서 쿼리 리파이너 노드 제거 - 관련 문서 및 README 업데이트 - 단순화된 그래프 파일 삭제
1 parent d3e4326 commit e73f484

File tree

10 files changed

+64
-239
lines changed

10 files changed

+64
-239
lines changed

engine/query_executor.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
from llm_utils.graph_utils.enriched_graph import builder as enriched_builder
1414
from llm_utils.graph_utils.basic_graph import builder as basic_builder
15-
from llm_utils.graph_utils.simplified_graph import builder as simplified_builder
1615
from llm_utils.llm_response_parser import LLMResponseParser
1716

1817
logger = logging.getLogger(__name__)
@@ -26,7 +25,6 @@ def execute_query(
2625
top_n: int = 5,
2726
device: str = "cpu",
2827
use_enriched_graph: bool = False,
29-
use_simplified_graph: bool = False,
3028
session_state: Optional[Union[Dict[str, Any], Any]] = None,
3129
) -> Dict[str, Any]:
3230
"""
@@ -49,17 +47,13 @@ def execute_query(
4947
Dict[str, Any]: 다음 정보를 포함한 Lang2SQL 실행 결과 딕셔너리:
5048
- "generated_query": 생성된 SQL 쿼리 (`AIMessage`)
5149
- "messages": 전체 LLM 응답 메시지 목록
52-
- "refined_input": AI가 재구성한 입력 질문
5350
- "searched_tables": 참조된 테이블 목록 등 추가 정보
5451
"""
5552

5653
logger.info("Processing query: %s", query)
5754

5855
# 그래프 선택
59-
if use_simplified_graph:
60-
graph_type = "simplified"
61-
graph_builder = simplified_builder
62-
elif use_enriched_graph:
56+
if use_enriched_graph:
6357
graph_type = "enriched"
6458
graph_builder = enriched_builder
6559
else:

interface/lang2sql.py

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
from infra.observability.token_usage import TokenUtils
2121
from llm_utils.graph_utils.enriched_graph import builder as enriched_builder
2222
from llm_utils.graph_utils.basic_graph import builder
23-
from llm_utils.graph_utils.simplified_graph import builder as simplified_builder
2423

2524

2625
TITLE = "Lang2SQL"
@@ -61,7 +60,6 @@ def execute_query(
6160
dict: 다음 정보를 포함한 Lang2SQL 실행 결과 딕셔너리:
6261
- "generated_query": 생성된 SQL 쿼리 (`AIMessage`)
6362
- "messages": 전체 LLM 응답 메시지 목록
64-
- "refined_input": AI가 재구성한 입력 질문
6563
- "searched_tables": 참조된 테이블 목록 등 추가 정보
6664
"""
6765

@@ -72,7 +70,6 @@ def execute_query(
7270
top_n=top_n,
7371
device=device,
7472
use_enriched_graph=st.session_state.get("use_enriched", False),
75-
use_simplified_graph=st.session_state.get("use_simplified", False),
7673
session_state=st.session_state,
7774
)
7875

@@ -164,7 +161,17 @@ def should_show(_key: str) -> bool:
164161
if should_show("show_question_reinterpreted_by_ai"):
165162
st.markdown("---")
166163
st.markdown("**AI가 재해석한 사용자 질문:**")
167-
st.code(res["refined_input"].content)
164+
try:
165+
if len(res["messages"]) > 1:
166+
candidate = res["messages"][ -2 ]
167+
question_text = (
168+
candidate.content if hasattr(candidate, "content") else str(candidate)
169+
)
170+
else:
171+
question_text = res["messages"][0].content
172+
except Exception:
173+
question_text = str(res["messages"][0].content)
174+
st.code(question_text)
168175

169176
if should_show("show_referenced_tables"):
170177
st.markdown("---")
@@ -200,8 +207,19 @@ def should_show(_key: str) -> bool:
200207
sql = LLMResponseParser.extract_sql(sql_raw)
201208
df = database.run_sql(sql)
202209
st.markdown("**쿼리 결과 시각화:**")
210+
try:
211+
if len(res["messages"]) > 1:
212+
candidate = res["messages"][ -2 ]
213+
chart_question = (
214+
candidate.content if hasattr(candidate, "content") else str(candidate)
215+
)
216+
else:
217+
chart_question = res["messages"][0].content
218+
except Exception:
219+
chart_question = str(res["messages"][0].content)
220+
203221
display_code = DisplayChart(
204-
question=res["refined_input"].content,
222+
question=chart_question,
205223
sql=sql,
206224
df_metadata=f"Running df.dtypes gives:\n{df.dtypes}",
207225
)
@@ -225,21 +243,14 @@ def should_show(_key: str) -> bool:
225243
use_enriched = st.sidebar.checkbox(
226244
"프로파일 추출 & 컨텍스트 보강 워크플로우 사용", value=False
227245
)
228-
use_simplified = st.sidebar.checkbox(
229-
"단순화된 워크플로우 사용 (QUERY_REFINER 제거)", value=False
230-
)
231246

232247
# 세션 상태 초기화
233248
if (
234249
"graph" not in st.session_state
235250
or st.session_state.get("use_enriched") != use_enriched
236-
or st.session_state.get("use_simplified") != use_simplified
237251
):
238252
# 그래프 선택 로직
239-
if use_simplified:
240-
graph_builder = simplified_builder
241-
graph_type = "단순화된"
242-
elif use_enriched:
253+
if use_enriched:
243254
graph_builder = enriched_builder
244255
graph_type = "확장된"
245256
else:
@@ -248,16 +259,12 @@ def should_show(_key: str) -> bool:
248259

249260
st.session_state["graph"] = graph_builder.compile()
250261
st.session_state["use_enriched"] = use_enriched
251-
st.session_state["use_simplified"] = use_simplified
252262
st.info(f"Lang2SQL이 성공적으로 시작되었습니다. ({graph_type} 워크플로우)")
253263

254264
# 새로고침 버튼 추가
255265
if st.sidebar.button("Lang2SQL 새로고침"):
256266
# 그래프 선택 로직
257-
if st.session_state.get("use_simplified"):
258-
graph_builder = simplified_builder
259-
graph_type = "단순화된"
260-
elif st.session_state.get("use_enriched"):
267+
if st.session_state.get("use_enriched"):
261268
graph_builder = enriched_builder
262269
graph_type = "확장된"
263270
else:

llm_utils/README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,16 @@ Lang2SQL 파이프라인에서 LLM, 검색(RAG), 그래프 워크플로우, DB
4040
### Depth 2.5: 체인(Chains)
4141

4242
- **`chains.py`**: LangChain ChatPromptTemplate로 구성된 체인.
43-
- `create_query_refiner_chain`, `create_query_maker_chain`, `create_profile_extraction_chain`, `create_query_refiner_with_profile_chain`, `create_query_enrichment_chain`
43+
- `create_query_maker_chain`, `create_profile_extraction_chain`, `create_query_enrichment_chain`
4444
- `QuestionProfile` Pydantic 모델로 질의 특성 구조화 추출.
4545

4646
### Depth 3: 그래프(Graph) 워크플로우
4747

4848
- **`graph_utils/base.py`**: 공통 상태(`QueryMakerState`)와 노드 함수 집합.
49-
- 노드: `get_table_info_node`(RAG), `profile_extraction_node`, `query_refiner_node`/`query_refiner_with_profile_node`, `context_enrichment_node`, `query_maker_node`, `query_maker_node_without_refiner`.
49+
- 노드: `get_table_info_node`(RAG), `profile_extraction_node`, `context_enrichment_node`, `query_maker_node`, `query_maker_node_without_refiner`.
5050
- 각 노드는 `chains.py``retrieval.py`, `utils.profile_to_text` 등을 호출하며 상태를 갱신.
51-
- **`graph_utils/basic_graph.py`**: GET_TABLE_INFO → QUERY_REFINER → QUERY_MAKER → END
52-
- **`graph_utils/enriched_graph.py`**: GET_TABLE_INFO → PROFILE_EXTRACTION → QUERY_REFINER(with profile) → CONTEXT_ENRICHMENT → QUERY_MAKER → END
51+
- **`graph_utils/basic_graph.py`**: GET_TABLE_INFO → QUERY_MAKER → END
52+
- **`graph_utils/enriched_graph.py`**: GET_TABLE_INFO → PROFILE_EXTRACTION → CONTEXT_ENRICHMENT → QUERY_MAKER → END
5353
- **`graph_utils/simplified_graph.py`**: GET_TABLE_INFO → PROFILE_EXTRACTION → CONTEXT_ENRICHMENT → QUERY_MAKER(without refiner) → END
5454

5555
### 통합 흐름(End-to-End)

llm_utils/chains.py

Lines changed: 2 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,6 @@ class QuestionProfile(BaseModel):
2323
has_temporal_comparison: bool = Field(description="기간 비교 포함 여부")
2424
intent_type: str = Field(description="질문의 주요 의도 유형")
2525

26-
27-
def create_query_refiner_chain(llm):
28-
prompt = get_prompt_template("query_refiner_prompt")
29-
tool_choice_prompt = ChatPromptTemplate.from_messages(
30-
[
31-
SystemMessagePromptTemplate.from_template(prompt),
32-
MessagesPlaceholder(variable_name="user_input"),
33-
SystemMessagePromptTemplate.from_template(
34-
"다음은 사용자의 실제 사용 가능한 테이블 및 컬럼 정보 와 예시쿼리 및 용어집 정보입니다:"
35-
),
36-
MessagesPlaceholder(variable_name="searched_tables"),
37-
SystemMessagePromptTemplate.from_template(
38-
"""
39-
위 사용자의 입력을 바탕으로
40-
분석 관점에서 **충분히 답변 가능한 형태**로
41-
"구체화된 질문"을 작성하고,
42-
필요한 경우 가정이나 전제 조건을 함께 제시해 주세요.
43-
""",
44-
),
45-
]
46-
)
47-
48-
return tool_choice_prompt | llm
49-
50-
5126
# QueryMakerChain
5227
def create_query_maker_chain(llm):
5328
# SystemPrompt만 yaml 파일로 불러와서 사용
@@ -57,10 +32,9 @@ def create_query_maker_chain(llm):
5732
SystemMessagePromptTemplate.from_template(prompt),
5833
(
5934
"system",
60-
"아래는 사용자의 질문 및 구체화된 질문입니다:",
35+
"아래는 사용자의 질문입니다:",
6136
),
6237
MessagesPlaceholder(variable_name="user_input"),
63-
MessagesPlaceholder(variable_name="refined_input"),
6438
(
6539
"system",
6640
"다음은 사용자의 db 환경정보와 사용 가능한 테이블 및 컬럼 정보 와 예시쿼리 및 용어집 정보입니다:",
@@ -76,35 +50,6 @@ def create_query_maker_chain(llm):
7650
return query_maker_prompt | llm
7751

7852

79-
def create_query_refiner_with_profile_chain(llm):
80-
prompt = get_prompt_template("query_refiner_prompt")
81-
82-
tool_choice_prompt = ChatPromptTemplate.from_messages(
83-
[
84-
SystemMessagePromptTemplate.from_template(prompt),
85-
MessagesPlaceholder(variable_name="user_input"),
86-
SystemMessagePromptTemplate.from_template(
87-
"다음은 사용자의 실제 사용 가능한 테이블 및 컬럼 정보 와 예시쿼리 및 용어집 정보입니다:"
88-
),
89-
MessagesPlaceholder(variable_name="searched_tables"),
90-
# 프로파일 정보 입력
91-
SystemMessagePromptTemplate.from_template(
92-
"다음은 사용자의 질문을 분석한 프로파일 정보입니다."
93-
),
94-
MessagesPlaceholder("profile_prompt"),
95-
SystemMessagePromptTemplate.from_template(
96-
"""
97-
위 사용자의 입력과 위 조건을 바탕으로
98-
분석 관점에서 **충분히 답변 가능한 형태**로
99-
"구체화된 질문"을 작성하세요.
100-
""",
101-
),
102-
]
103-
)
104-
105-
return tool_choice_prompt | llm
106-
107-
10853
def create_query_enrichment_chain(llm):
10954
prompt = get_prompt_template("query_enrichment_prompt")
11055

@@ -131,11 +76,9 @@ def create_profile_extraction_chain(llm):
13176
return chain
13277

13378

134-
query_refiner_chain = create_query_refiner_chain(llm)
13579
query_maker_chain = create_query_maker_chain(llm)
13680
profile_extraction_chain = create_profile_extraction_chain(llm)
137-
query_refiner_with_profile_chain = create_query_refiner_with_profile_chain(llm)
13881
query_enrichment_chain = create_query_enrichment_chain(llm)
13982

14083
if __name__ == "__main__":
141-
query_refiner_chain.invoke()
84+
pass

llm_utils/graph_utils/__init__.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,43 +7,35 @@
77
from .base import (
88
QueryMakerState,
99
GET_TABLE_INFO,
10-
QUERY_REFINER,
1110
QUERY_MAKER,
1211
PROFILE_EXTRACTION,
1312
CONTEXT_ENRICHMENT,
1413
get_table_info_node,
15-
query_refiner_node,
1614
query_maker_node,
1715
profile_extraction_node,
18-
query_refiner_with_profile_node,
1916
context_enrichment_node,
2017
query_maker_node_with_db_guide,
2118
query_maker_node_without_refiner,
2219
)
2320

2421
from .basic_graph import builder as basic_builder
2522
from .enriched_graph import builder as enriched_builder
26-
from .simplified_graph import builder as simplified_builder
2723

2824
__all__ = [
2925
# 상태 및 노드 식별자
3026
"QueryMakerState",
3127
"GET_TABLE_INFO",
32-
"QUERY_REFINER",
3328
"QUERY_MAKER",
3429
"PROFILE_EXTRACTION",
3530
"CONTEXT_ENRICHMENT",
3631
# 노드 함수들
3732
"get_table_info_node",
38-
"query_refiner_node",
3933
"query_maker_node",
4034
"profile_extraction_node",
41-
"query_refiner_with_profile_node",
4235
"context_enrichment_node",
4336
"query_maker_node_with_db_guide",
4437
"query_maker_node_without_refiner",
4538
# 그래프 빌더들
4639
"basic_builder",
4740
"enriched_builder",
48-
"simplified_builder",
4941
]

0 commit comments

Comments
 (0)