|
| 1 | +## DataHub 없이 시작하기 (튜토리얼) |
| 2 | + |
| 3 | +이 문서는 DataHub 없이도 Lang2SQL을 바로 사용하기 위한 최소 절차를 설명합니다. CSV로 테이블/컬럼 설명을 준비해 FAISS 또는 pgvector에 적재한 뒤 Lang2SQL을 실행합니다. |
| 4 | + |
| 5 | +### 1) .env 최소 설정 (OpenAI 기준) |
| 6 | + |
| 7 | +```bash |
| 8 | +# LLM/임베딩 |
| 9 | +LLM_PROVIDER=openai |
| 10 | +OPEN_AI_KEY=sk-... # OpenAI API Key (주의: OPENAI_API_KEY가 아니라 OPEN_AI_KEY) |
| 11 | +OPEN_AI_LLM_MODEL=gpt-4o # 또는 gpt-4.1 등 |
| 12 | +EMBEDDING_PROVIDER=openai |
| 13 | +OPEN_AI_EMBEDDING_MODEL=text-embedding-3-large # 권장 |
| 14 | + |
| 15 | +# VectorDB (선택: 명시하지 않으면 기본값 동작) |
| 16 | +VECTORDB_TYPE=faiss |
| 17 | +VECTORDB_LOCATION=./table_info_db # FAISS 디렉토리 경로 |
| 18 | + |
| 19 | +# (pgvector를 쓰는 경우) |
| 20 | +# VECTORDB_TYPE=pgvector |
| 21 | +# VECTORDB_LOCATION=postgresql://user:pass@host:5432/db |
| 22 | +# PGVECTOR_COLLECTION=table_info_db |
| 23 | +``` |
| 24 | + |
| 25 | +중요: 코드상 OpenAI 키는 `OPEN_AI_KEY` 환경변수를 사용합니다. `.example.env`의 `OPENAI_API_KEY`는 사용되지 않으니 혼동에 주의하세요. |
| 26 | + |
| 27 | +### 2) 테이블/컬럼 메타데이터 준비(CSV 예시) |
| 28 | + |
| 29 | +```csv |
| 30 | +table_name,table_description,column_name,column_description |
| 31 | +customers,고객 정보 테이블,customer_id,고객 고유 ID |
| 32 | +customers,고객 정보 테이블,name,고객 이름 |
| 33 | +customers,고객 정보 테이블,created_at,가입 일시 |
| 34 | +orders,주문 정보 테이블,order_id,주문 ID |
| 35 | +orders,주문 정보 테이블,customer_id,주문 고객 ID |
| 36 | +orders,주문 정보 테이블,amount,결제 금액 |
| 37 | +orders,주문 정보 테이블,status,주문 상태 |
| 38 | +``` |
| 39 | + |
| 40 | +### 3) FAISS 인덱스 생성(로컬) |
| 41 | + |
| 42 | +```python |
| 43 | +from collections import defaultdict |
| 44 | +import csv, os |
| 45 | +from langchain_openai import OpenAIEmbeddings |
| 46 | +from langchain_community.vectorstores import FAISS |
| 47 | + |
| 48 | +CSV_PATH = "./table_catalog.csv" # 위 CSV 파일 경로 |
| 49 | +OUTPUT_DIR = "./table_info_db" # VECTORDB_LOCATION과 동일하게 맞추세요 |
| 50 | + |
| 51 | +tables = defaultdict(lambda: {"desc": "", "columns": []}) |
| 52 | +with open(CSV_PATH, newline="", encoding="utf-8") as f: |
| 53 | + reader = csv.DictReader(f) |
| 54 | + for row in reader: |
| 55 | + t = row["table_name"].strip() |
| 56 | + tables[t]["desc"] = row["table_description"].strip() |
| 57 | + col = row["column_name"].strip() |
| 58 | + col_desc = row["column_description"].strip() |
| 59 | + tables[t]["columns"].append((col, col_desc)) |
| 60 | + |
| 61 | +docs = [] |
| 62 | +for t, info in tables.items(): |
| 63 | + cols = "\n".join([f"{c}: {d}" for c, d in info["columns"]]) |
| 64 | + page = f"{t}: {info['desc']}\nColumns:\n {cols}" |
| 65 | + from langchain.schema import Document |
| 66 | + docs.append(Document(page_content=page)) |
| 67 | + |
| 68 | +emb = OpenAIEmbeddings(model=os.getenv("OPEN_AI_EMBEDDING_MODEL"), openai_api_key=os.getenv("OPEN_AI_KEY")) |
| 69 | +db = FAISS.from_documents(docs, emb) |
| 70 | +os.makedirs(OUTPUT_DIR, exist_ok=True) |
| 71 | +db.save_local(OUTPUT_DIR) |
| 72 | +print(f"FAISS index saved to: {OUTPUT_DIR}") |
| 73 | +``` |
| 74 | + |
| 75 | +### 4) 실행 |
| 76 | + |
| 77 | +```bash |
| 78 | +# Streamlit UI |
| 79 | +lang2sql --vectordb-type faiss --vectordb-location ./table_info_db run-streamlit |
| 80 | + |
| 81 | +# CLI 예시 |
| 82 | +lang2sql query "주문 수를 집계하는 SQL을 만들어줘" --vectordb-type faiss --vectordb-location ./table_info_db |
| 83 | + |
| 84 | +# CLI 예시 (pgvector) |
| 85 | +lang2sql query "주문 수를 집계하는 SQL을 만들어줘" --vectordb-type pgvector --vectordb-location "postgresql://postgres:postgres@localhost:5431/postgres" |
| 86 | +``` |
| 87 | + |
| 88 | +### 5) (선택) pgvector로 적재하기 |
| 89 | + |
| 90 | +```python |
| 91 | +from collections import defaultdict |
| 92 | +import csv, os |
| 93 | +from langchain_openai import OpenAIEmbeddings |
| 94 | +from langchain_postgres.vectorstores import PGVector |
| 95 | +from langchain.schema import Document |
| 96 | + |
| 97 | +CSV_PATH = "./table_catalog.csv" |
| 98 | +CONN = os.getenv("VECTORDB_LOCATION") or "postgresql://user:pass@host:5432/db" |
| 99 | +COLLECTION = os.getenv("PGVECTOR_COLLECTION", "table_info_db") |
| 100 | + |
| 101 | +tables = defaultdict(lambda: {"desc": "", "columns": []}) |
| 102 | +with open(CSV_PATH, newline="", encoding="utf-8") as f: |
| 103 | + reader = csv.DictReader(f) |
| 104 | + for row in reader: |
| 105 | + t = row["table_name"].strip() |
| 106 | + tables[t]["desc"] = row["table_description"].strip() |
| 107 | + col = row["column_name"].strip() |
| 108 | + col_desc = row["column_description"] |
| 109 | + tables[t]["columns"].append((col, col_desc)) |
| 110 | + |
| 111 | +docs = [] |
| 112 | +for t, info in tables.items(): |
| 113 | + cols = "\n".join([f"{c}: {d}" for c, d in info["columns"]]) |
| 114 | + docs.append(Document(page_content=f"{t}: {info['desc']}\nColumns:\n {cols}")) |
| 115 | + |
| 116 | +emb = OpenAIEmbeddings(model=os.getenv("OPEN_AI_EMBEDDING_MODEL"), openai_api_key=os.getenv("OPEN_AI_KEY")) |
| 117 | +PGVector.from_documents(documents=docs, embedding=emb, connection=CONN, collection_name=COLLECTION) |
| 118 | +print(f"pgvector collection populated: {COLLECTION}") |
| 119 | +``` |
| 120 | + |
| 121 | +주의: FAISS 디렉토리가 없으면 현재 코드는 DataHub에서 메타데이터를 가져와 인덱스를 생성하려고 시도합니다. DataHub를 사용하지 않는 경우 위 절차로 사전에 VectorDB를 만들어 두세요. |
| 122 | + |
| 123 | + |
0 commit comments