Skip to content

Commit 28cb854

Browse files
authored
Merge pull request #109 from #108
feat: enhance CLI with options for environment file and prompt directory
2 parents 6a5451c + fff9a8a commit 28cb854

File tree

8 files changed

+51
-55
lines changed

8 files changed

+51
-55
lines changed

cli/__init__.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
명령어 예시: lang2sql --datahub_server http://localhost:8080 --run-streamlit
66
"""
77

8+
import os
89
import logging
910
import subprocess
1011

1112
import click
13+
import dotenv
1214

1315
from llm_utils.check_server import CheckServer
1416
from llm_utils.tools import set_gms_server
@@ -52,12 +54,24 @@
5254
"기본 포트는 8501이며, 포트 충돌을 피하거나 여러 인스턴스를 실행할 때 변경할 수 있습니다."
5355
),
5456
)
57+
@click.option(
58+
"--env-file-path",
59+
type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True),
60+
help="환경 변수를 로드할 .env 파일의 경로를 지정합니다. 지정하지 않으면 기본 경로를 사용합니다.",
61+
)
62+
@click.option(
63+
"--prompt-dir-path",
64+
type=click.Path(exists=True, file_okay=False, dir_okay=True, readable=True),
65+
help="프롬프트 템플릿(.md 파일)이 저장된 디렉토리 경로를 지정합니다. 지정하지 않으면 기본 경로를 사용합니다.",
66+
)
5567
# pylint: disable=redefined-outer-name
5668
def cli(
5769
ctx: click.Context,
5870
datahub_server: str,
5971
run_streamlit: bool,
6072
port: int,
73+
env_file_path: str = None,
74+
prompt_dir_path: str = None,
6175
) -> None:
6276
"""
6377
Datahub GMS 서버 URL을 설정하고, Streamlit 애플리케이션을 실행할 수 있는 CLI 명령 그룹입니다.
@@ -66,17 +80,43 @@ def cli(
6680
- 전달받은 'datahub_server' URL을 바탕으로 GMS 서버 연결을 설정합니다.
6781
- 설정 과정 중 오류가 발생하면 오류 메시지를 출력하고 프로그램을 종료합니다.
6882
- '--run-streamlit' 옵션이 활성화된 경우, 지정된 포트에서 Streamlit 웹 앱을 즉시 실행합니다.
83+
- '--env-file-path' 옵션이 지정된 경우, 해당 .env 파일에서 환경 변수를 로드합니다.
84+
- '--prompt-dir-path' 옵션이 지정된 경우, 해당 디렉토리에서 프롬프트 템플릿을 로드합니다.
6985
7086
매개변수:
7187
ctx (click.Context): 명령어 실행 컨텍스트 객체입니다.
7288
datahub_server (str): 설정할 Datahub GMS 서버의 URL입니다.
7389
run_streamlit (bool): Streamlit 앱을 실행할지 여부를 나타내는 플래그입니다.
7490
port (int): Streamlit 서버가 바인딩될 포트 번호입니다.
91+
env_file_path (str, optional): 환경 변수를 로드할 .env 파일 경로입니다.
92+
prompt_dir_path (str, optional): 프롬프트 템플릿을 로드할 디렉토리 경로입니다.
7593
7694
주의:
7795
'set_gms_server' 함수에서 ValueError가 발생할 경우, 프로그램은 비정상 종료(exit code 1)합니다.
7896
"""
7997

98+
# 환경 변수 파일 로드
99+
if env_file_path:
100+
try:
101+
if not dotenv.load_dotenv(env_file_path, override=True):
102+
click.secho(f"환경 변수 파일 로드 실패: {env_file_path}", fg="yellow")
103+
else:
104+
click.secho(f"환경 변수 파일 로드 성공: {env_file_path}", fg="green")
105+
except Exception as e:
106+
click.secho(f"환경 변수 로드 중 오류 발생: {str(e)}", fg="red")
107+
ctx.exit(1)
108+
109+
# 프롬프트 디렉토리를 환경 변수로 설정
110+
if prompt_dir_path:
111+
try:
112+
os.environ["PROMPT_TEMPLATES_DIR"] = prompt_dir_path
113+
click.secho(
114+
f"프롬프트 디렉토리 환경변수 설정됨: {prompt_dir_path}", fg="green"
115+
)
116+
except Exception as e:
117+
click.secho(f"프롬프트 디렉토리 환경변수 설정 실패: {str(e)}", fg="red")
118+
ctx.exit(1)
119+
80120
logger.info(
81121
"Initialization started: GMS server = %s, run_streamlit = %s, port = %d",
82122
datahub_server,

db_utils/__init__.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
from .config import DBConfig
44
from .logger import logger
55

6-
from dotenv import load_dotenv
7-
86
from .base_connector import BaseConnector
97

108
from .clickhouse_connector import ClickHouseConnector
@@ -18,12 +16,6 @@
1816

1917
env_path = os.path.join(os.getcwd(), ".env")
2018

21-
if os.path.exists(env_path):
22-
load_dotenv(env_path, override=True)
23-
print(f"✅ 환경변수 파일(.env)이 {os.getcwd()}에 로드되었습니다!")
24-
else:
25-
print(f"⚠️ 환경변수 파일(.env)이 {os.getcwd()}에 없습니다!")
26-
2719

2820
def get_db_connector(db_type: Optional[str] = None, config: Optional[DBConfig] = None):
2921
"""

llm_utils/chains.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,9 @@
88

99
from .llm_factory import get_llm
1010

11-
from dotenv import load_dotenv
1211
from prompt.template_loader import get_prompt_template
1312

1413

15-
env_path = os.path.join(os.getcwd(), ".env")
16-
17-
if os.path.exists(env_path):
18-
load_dotenv(env_path)
19-
else:
20-
print(f"⚠️ 환경변수 파일(.env)이 {os.getcwd()}에 없습니다!")
21-
2214
llm = get_llm()
2315

2416

llm_utils/connect_db.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@
1414

1515
import pandas as pd
1616
from clickhouse_driver import Client
17-
from dotenv import load_dotenv
18-
19-
load_dotenv()
2017

2118
logging.basicConfig(
2219
level=logging.INFO,

llm_utils/display_chart.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import re
2-
from llm_utils import llm_factory
3-
from dotenv import load_dotenv
4-
from langchain.chains.llm import LLMChain
52
from langchain_openai import ChatOpenAI
6-
from langchain_core.prompts import PromptTemplate
73
from langchain_core.messages import HumanMessage, SystemMessage
84
import pandas as pd
95
import os
@@ -13,10 +9,6 @@
139
import plotly.graph_objects as go
1410

1511

16-
# .env 파일 로딩
17-
load_dotenv()
18-
19-
2012
class DisplayChart:
2113
"""
2214
SQL쿼리가 실행된 결과를 그래프로 시각화하는 Class입니다.

llm_utils/llm_factory.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import os
33
from typing import Optional
44

5-
from dotenv import load_dotenv
65
from langchain.llms.base import BaseLanguageModel
76
from langchain_aws import ChatBedrockConverse, BedrockEmbeddings
87
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
@@ -19,14 +18,6 @@
1918
OpenAIEmbeddings,
2019
)
2120

22-
env_path = os.path.join(os.getcwd(), ".env")
23-
24-
if os.path.exists(env_path):
25-
load_dotenv(env_path, override=True)
26-
print(f"✅ 환경변수 파일(.env)이 {os.getcwd()}에 로드되었습니다!")
27-
else:
28-
print(f"⚠️ 환경변수 파일(.env)이 {os.getcwd()}에 없습니다!")
29-
3021

3122
def get_llm(**kwargs) -> BaseLanguageModel:
3223
"""

prompt/template_loader.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
1+
"""
2+
이 모듈은 프롬프트 템플릿을 로드하는 기능을 제공합니다.
3+
- 프롬프트 템플릿은 마크다운 파일로 관리되고 있으며, 환경변수에서 템플릿 디렉토리를 가져오거나, 없으면 현재 파일 위치 기준으로 설정합니다.
4+
"""
5+
16
import os
27

38

49
def get_prompt_template(prompt_name: str) -> str:
10+
# 환경변수에서 템플릿 디렉토리를 가져오거나, 없으면 현재 파일 위치 기준으로 설정
11+
templates_dir = os.environ.get("PROMPT_TEMPLATES_DIR", os.path.dirname(__file__))
12+
513
try:
6-
with open(
7-
os.path.join(os.path.dirname(__file__), f"{prompt_name}.md"),
8-
"r",
9-
encoding="utf-8",
10-
) as f:
14+
template_path = os.path.join(templates_dir, f"{prompt_name}.md")
15+
with open(template_path, "r", encoding="utf-8") as f:
1116
template = f.read()
1217
except FileNotFoundError:
1318
raise FileNotFoundError(f"경고: '{prompt_name}.md' 파일을 찾을 수 없습니다.")
19+
1420
return template

pyproject.toml

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)