Skip to content

Commit 384d324

Browse files
committed
feat: enhance CLI with options for environment file and prompt directory
1 parent 585c032 commit 384d324

File tree

5 files changed

+46
-19
lines changed

5 files changed

+46
-19
lines changed

cli/__init__.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
Datahub GMS 서버 URL을 설정하고, 필요 시 Streamlit 인터페이스를 실행하는 CLI 프로그램입니다.
33
"""
44

5+
import os
56
import subprocess
67

78
import click
9+
import dotenv
810

911
from llm_utils.tools import set_gms_server
1012

@@ -39,12 +41,24 @@
3941
"기본 포트는 8501이며, 포트 충돌을 피하거나 여러 인스턴스를 실행할 때 변경할 수 있습니다."
4042
),
4143
)
44+
@click.option(
45+
"--env-file-path",
46+
type=click.Path(exists=True, file_okay=True, dir_okay=False, readable=True),
47+
help="환경 변수를 로드할 .env 파일의 경로를 지정합니다. 지정하지 않으면 기본 경로를 사용합니다.",
48+
)
49+
@click.option(
50+
"--prompt-dir-path",
51+
type=click.Path(exists=True, file_okay=False, dir_okay=True, readable=True),
52+
help="프롬프트 템플릿(.md 파일)이 저장된 디렉토리 경로를 지정합니다. 지정하지 않으면 기본 경로를 사용합니다.",
53+
)
4254
# pylint: disable=redefined-outer-name
4355
def cli(
4456
ctx: click.Context,
4557
datahub_server: str,
4658
run_streamlit: bool,
4759
port: int,
60+
env_file_path: str = None,
61+
prompt_dir_path: str = None,
4862
) -> None:
4963
"""
5064
Datahub GMS 서버 URL을 설정하고, Streamlit 애플리케이션을 실행할 수 있는 CLI 명령 그룹입니다.
@@ -53,17 +67,43 @@ def cli(
5367
- 전달받은 'datahub_server' URL을 바탕으로 GMS 서버 연결을 설정합니다.
5468
- 설정 과정 중 오류가 발생하면 오류 메시지를 출력하고 프로그램을 종료합니다.
5569
- '--run-streamlit' 옵션이 활성화된 경우, 지정된 포트에서 Streamlit 웹 앱을 즉시 실행합니다.
70+
- '--env-file-path' 옵션이 지정된 경우, 해당 .env 파일에서 환경 변수를 로드합니다.
71+
- '--prompt-dir-path' 옵션이 지정된 경우, 해당 디렉토리에서 프롬프트 템플릿을 로드합니다.
5672
5773
매개변수:
5874
ctx (click.Context): 명령어 실행 컨텍스트 객체입니다.
5975
datahub_server (str): 설정할 Datahub GMS 서버의 URL입니다.
6076
run_streamlit (bool): Streamlit 앱을 실행할지 여부를 나타내는 플래그입니다.
6177
port (int): Streamlit 서버가 바인딩될 포트 번호입니다.
78+
env_file_path (str, optional): 환경 변수를 로드할 .env 파일 경로입니다.
79+
prompt_dir_path (str, optional): 프롬프트 템플릿을 로드할 디렉토리 경로입니다.
6280
6381
주의:
6482
'set_gms_server' 함수에서 ValueError가 발생할 경우, 프로그램은 비정상 종료(exit code 1)합니다.
6583
"""
6684

85+
# 환경 변수 파일 로드
86+
if env_file_path:
87+
try:
88+
if not dotenv.load_dotenv(env_file_path, override=True):
89+
click.secho(f"환경 변수 파일 로드 실패: {env_file_path}", fg="yellow")
90+
else:
91+
click.secho(f"환경 변수 파일 로드 성공: {env_file_path}", fg="green")
92+
except Exception as e:
93+
click.secho(f"환경 변수 로드 중 오류 발생: {str(e)}", fg="red")
94+
ctx.exit(1)
95+
96+
# 프롬프트 디렉토리를 환경 변수로 설정
97+
if prompt_dir_path:
98+
try:
99+
os.environ["PROMPT_TEMPLATES_DIR"] = prompt_dir_path
100+
click.secho(
101+
f"프롬프트 디렉토리 환경변수 설정됨: {prompt_dir_path}", fg="green"
102+
)
103+
except Exception as e:
104+
click.secho(f"프롬프트 디렉토리 환경변수 설정 실패: {str(e)}", fg="red")
105+
ctx.exit(1)
106+
67107
try:
68108
set_gms_server(datahub_server)
69109
except ValueError as e:

llm_utils/chains.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,6 @@
1010
from dotenv import load_dotenv
1111
from prompt.template_loader import get_prompt_template
1212

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

2215

llm_utils/connect_db.py

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

1414
import pandas as pd
1515
from clickhouse_driver import Client
16-
from dotenv import load_dotenv
17-
18-
load_dotenv()
1916

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

llm_utils/llm_factory.py

Lines changed: 0 additions & 4 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
@@ -20,9 +19,6 @@
2019
)
2120
from langchain_community.llms.bedrock import Bedrock
2221

23-
# .env 파일 로딩
24-
load_dotenv()
25-
2622

2723
def get_llm() -> BaseLanguageModel:
2824
"""

prompt/template_loader.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33

44
def get_prompt_template(prompt_name: str) -> str:
5+
# 환경변수에서 템플릿 디렉토리를 가져오거나, 없으면 현재 파일 위치 기준으로 설정
6+
templates_dir = os.environ.get("PROMPT_TEMPLATES_DIR", os.path.dirname(__file__))
7+
58
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:
9+
template_path = os.path.join(templates_dir, f"{prompt_name}.md")
10+
with open(template_path, "r", encoding="utf-8") as f:
1111
template = f.read()
1212
except FileNotFoundError:
1313
raise FileNotFoundError(f"경고: '{prompt_name}.md' 파일을 찾을 수 없습니다.")
14+
1415
return template

0 commit comments

Comments
 (0)