Skip to content

6 dbms별 sql 차이를 반영한 few shot prompt 최적화 제안 #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions interface/streamlit_app.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import streamlit as st
from langchain_core.messages import HumanMessage
from llm_utils.graph import builder
from langchain.chains.sql_database.prompt import SQL_PROMPTS

# Streamlit 앱 제목
st.title("Lang2SQL")
Expand All @@ -11,9 +12,10 @@
value="고객 데이터를 기반으로 유니크한 유저 수를 카운트하는 쿼리",
)

user_database_env = st.text_area(
user_database_env = st.selectbox(
"db 환경정보를 입력하세요:",
value="duckdb",
options=SQL_PROMPTS.keys(),
index=0,
)


Expand Down Expand Up @@ -42,6 +44,8 @@ def summarize_total_tokens(data):

# 결과 출력
st.write("총 토큰 사용량:", total_tokens)
st.write("결과:", res["generated_query"].content)
# st.write("결과:", res["generated_query"].content)
st.write("결과:", "\n\n```sql\n" + res["generated_query"] + "\n```")
st.write("결과 설명:\n\n", res["messages"][-1].content)
st.write("AI가 재해석한 사용자 질문:\n", res["refined_input"].content)
st.write("참고한 테이블 목록:", res["searched_tables"])
35 changes: 34 additions & 1 deletion llm_utils/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from typing_extensions import TypedDict, Annotated
from langgraph.graph import END, StateGraph
from langgraph.graph.message import add_messages
from langchain.chains.sql_database.prompt import SQL_PROMPTS
from pydantic import BaseModel, Field
from .llm_factory import get_llm

from llm_utils.chains import (
query_refiner_chain,
Expand Down Expand Up @@ -102,14 +105,44 @@ def query_maker_node(state: QueryMakerState):
return state


class SQLResult(BaseModel):
sql: str = Field(description="SQL 쿼리 문자열")
explanation: str = Field(description="SQL 쿼리 설명")


def query_maker_node_with_db_guide(state: QueryMakerState):
sql_prompt = SQL_PROMPTS[state["user_database_env"]]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💊: 추후 유저나 개발자가 프롬프트를 수정하고자 할 때, 추후 변경이 어려울 수도 있을 것 같습니다. 별도의 Class로 관리하는 것도 좋을 것 같다고 생각해 제안드립니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💊: 추후 유저나 개발자가 프롬프트를 수정하고자 할 때, 추후 변경이 어려울 수도 있을 것 같습니다. 별도의 Class로 관리하는 것도 좋을 것 같다고 생각해 제안드립니다.

👍 #11 와 연결하면 좋을 것 같은데 Propmt를 위한 class가 정해지면 멘션 주시면 저도 참여하여 작업하도록 하겠습니다. 😄

llm = get_llm(
model_type="openai",
model_name="gpt-4o-mini",
openai_api_key=os.getenv("OPENAI_API_KEY"),
)
chain = sql_prompt | llm.with_structured_output(SQLResult)
res = chain.invoke(
input={
"input": "\n\n---\n\n".join(
[state["messages"][0].content] + [state["refined_input"].content]
),
"table_info": [json.dumps(state["searched_tables"])],
"top_k": 10,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💊 top_k가 10개로 제한되어있는데 해당 파라미터의 갯수를 input으로 받게하는건 어떨까요?

그렇다면 top_k의 값을

  1. 사용자 input
  2. LLM의 redefined input 생성때 희망하는 테이블 갯수도 함께 생성

이런식으로 받을 수 있을것 같습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

top_k의 의미가 SQL LIMIT top_k 의미라서 생각하시는 것과 조금 다른 것 같은데 말씀하시는 top_k의 의미가 참고되는 table을 말씀하시는 것일까요??

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 그렇군요!! SQL_PROMPTS의 top_k 파라미터군요 설명 감사합니다.ㅎㅎㅎㅎ

}
)
state["generated_query"] = res.sql
state["messages"].append(res.explanation)
return state


# StateGraph 생성 및 구성
builder = StateGraph(QueryMakerState)
builder.set_entry_point(QUERY_REFINER)

# 노드 추가
builder.add_node(QUERY_REFINER, query_refiner_node)
builder.add_node(GET_TABLE_INFO, get_table_info_node)
builder.add_node(QUERY_MAKER, query_maker_node)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 query_maker_node 함수 정의는 삭제되지 않았네요! (이견은 없습니다.)

추후에 성능평가 부분이 추가된다면 query_maker_node, query_maker_node_with_db_guide 를 비교해볼수도 있을것 같습니다ㅎㅎㅎ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 만들면서 #3 작업이 필요함을 느꼈습니다. token 소비는 많이 줄었는데 이게 제대로 만든 것인지 구분이 안되어서

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 교체된 프롬프트 덕분인지 그런지 토큰 사용량 측면에서는 비용이 꽤 많이 절약되는 것 같습니다. 그런데 호민님께서 말씀해주셨듯이 생성된 쿼리가 제대로 된 작업을 하는지 검증할 수 있으면 좋을 것 같습니다!!

또한 추가적으로 생성된 쿼리의 성능평가를 한다면 어떤 측면에서(비용, 실행시간, 리소스, 쿼리 정확도 등등) 해야 할지 논의해 보아야 할 것 같습니다.

# builder.add_node(QUERY_MAKER, query_maker_node) # query_maker_node_with_db_guide
builder.add_node(
QUERY_MAKER, query_maker_node_with_db_guide
) # query_maker_node_with_db_guide

# 기본 엣지 설정
builder.add_edge(QUERY_REFINER, GET_TABLE_INFO)
Expand Down
2 changes: 1 addition & 1 deletion llm_utils/llm_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def get_llm(
if model_type == "openai":
return ChatOpenAI(
model=model_name,
openai_api_key=openai_api_key,
api_key=openai_api_key,
**kwargs,
)

Expand Down