[랭체인] SQL 데이터베이스 쿼리 자동화
안녕하세요! 오늘은 LangChain을 사용하여 자연어로 SQL 데이터베이스를 쿼리하는 방법에 대해 알아보겠습니다. 이 기술을 사용하면 복잡한 SQL 쿼리를 작성하지 않고도 데이터베이스에서 원하는 정보를 쉽게 얻을 수 있습니다.
1. 환경 설정
먼저, 필요한 라이브러리를 설치합니다:
pip install -Uq langchain langchain_core langchain_openai langchain_community
그리고 OpenAI API 키를 환경 변수로 설정합니다:
import os
from google.colab import userdata
os.environ["OPENAI_API_KEY"] = userdata.get('OPENAI_API_KEY')
참고: 이 부분은 Google Colab에서 작업할 때 필요한 단계입니다. 로컬 환경에서는 API 키를 직접 설정해주세요.
2. 데이터베이스 준비
이 예제에서는 Chinook 데이터베이스를 사용합니다. GitHub에서 SQL 파일을 다운로드하고 SQLite 데이터베이스를 생성합니다:
import urllib.request
import sqlite3
# SQL 파일 다운로드
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql",
filename="Chinook_Sqlite.sql"
)
# 데이터베이스 생성 및 스크립트 실행
conn = sqlite3.connect('Chinook.db')
with open("Chinook_Sqlite.sql", 'r') as file:
script = file.read()
conn.executescript(script)
conn.close()
3. LangChain 컴포넌트 설정
LangChain을 사용하여 데이터베이스에 연결하고 필요한 컴포넌트를 설정합니다:
from langchain_community.utilities import SQLDatabase
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# 데이터베이스 연결
db = SQLDatabase.from_uri("sqlite:///Chinook.db")
# 프롬프트 템플릿 정의
prompt_template = ChatPromptTemplate.from_template("""Based on the table schema below,
write a SQL query that would answer the user's question:
{schema}
Question: {question}
SQL Query:""")
# 스키마 정보를 가져오는 함수
def get_schema(_):
return db.get_table_info()
4. LangChain 체인 구성
이제 모든 컴포넌트를 연결하여 체인을 구성합니다:
chain = RunnablePassthrough.assign(schema = get_schema)
| prompt_template
| ChatOpenAI()
| StrOutputParser()
| db.run
이 체인은 다음과 같은 순서로 작동합니다:
- 스키마 정보를 가져옵니다.
- 프롬프트 템플릿에 스키마와 사용자 질문을 삽입합니다.
- ChatGPT 모델을 사용하여 SQL 쿼리를 생성합니다.
- 생성된 SQL 쿼리를 파싱합니다.
- 데이터베이스에서 쿼리를 실행합니다.
5. 체인 사용하기
이제 자연어로 데이터베이스에 질문을 할 수 있습니다:
result = chain.invoke({"question": '점원의 수는?'})
print(result)
이 코드를 실행하면 "8"이라는 결과가 출력됩니다. 이는 데이터베이스에 8명의 점원이 있다는 것을 의미합니다.
마무리
LangChain을 사용하면 복잡한 데이터베이스 쿼리를 자연어로 간단히 수행할 수 있습니다. 이 기술은 데이터 분석가, 비즈니스 사용자, 그리고 SQL에 익숙하지 않은 사람들에게 특히 유용할 것입니다.
다음 단계로는 더 복잡한 쿼리를 처리하거나, 결과를 시각화하는 방법을 탐구해볼 수 있습니다. LangChain의 강력한 기능을 활용하여 여러분의 데이터베이스 작업을 더욱 효율적으로 만들어보세요!
- [랭체인] 간단한 텍스트 생성 체인 만들기
- [랭체인] 텍스트 감성 분류 체인 만들기
- [랭체인] 간단한 챗봇 만들기
- [랭체인] 수학 연산 체인 구현하기
- [랭체인] SQL 데이터베이스 쿼리 자동화
- [랭체인] PythonREPL을 활용한 동적 코드 실행 챗봇 구현
- [랭체인] PDF 문서 기반 QA챗봇 구현
- [랭체인] 대화형 챗봇 만들기
- [랭체인] 도구 체인 구축 가이드
- [랭체인] 라우팅 체인 - 유연한 AI 응답 시스템 구축하기
[광고] STEEM 개발자 커뮤니티에 참여 하시면, 다양한 혜택을 받을 수 있습니다.
Congratulations, your post has been upvoted by @upex with a 0.22% upvote. We invite you to continue producing quality content and join our Discord community here. Keep up the good work! #upex