LangChain으로 한국어 문법 검사기를 만들어 보자

안녕하세요? 랭체인 & 코딩 왕초보인 제가 랭체인을 사용한 간단한 문법 검사기를 만들어 보려고 합니다.


1. ChatGpt에게 한국어 문법 검사기 만들기에 필요한 code를 작성해 달라고 하기

1) 환경 설정

  • VS Code를 열고 터미널에서 다음과 같이 라이브러리를 설치합니다.

2) OpenAI API 설정

3) VS Code에 아래의 파일들을 복사해 저장합니다.

3.1) 문법 검사기 함수 구현: grammar_checker.py

3.2) 웹 인터페이스 추가

3.2.1) Flask 애플리케이션 구현: app.py

3.2.2) HTML 템플릿 생성

  • 먼저 문법 검사기 만들기에 필요한 file들이 들어 있는 폴더 안에 templates 폴더를 생성하고 그 안에 index.html 파일을 작성합니다.

  • index.html 파일 코드를 약간 수정해 봅니다.

  • 그리고 result.html 파일도 templates 폴더에 작성합니다.

2. 애플리케이션 실행

1) VS Code에서 터미널을 열고 app.py 파일을 실행합니다.

2) 웹 브라우저에서 http://127.0.0.1:5000/ 를 열어 문법 검사기를 실행해 봅니다.

  • 문법 검사기를 실행했더니 다음과 같은 오류가 뜨네요! 🥲

3. 오류 해결 방안 찾아보기

  • 여러군데를 검색해 본 결과 code를 좀 수정할 필요가 있다는 사실을 알게 되었습니다.

  • grammar_checker.py 수정

  • app.py 수정

  • 아래와 같이 결과가 나왔습니다. 😊

4. RAG 개념 추가 + Gradio

  • 한국어 예문들이 있는 csv file을 참고해서 검사 결과를 생성하면 더욱 정확한 답변이 나오지 않을까 해서 csv file을 RAG의 개념로 사용하였습니다.

  • 입력한 단어와 검사 결과를 한 화면에서 보기 위해서 Gradio를 사용해 보았습니다.

import sqlite3
import openai
from dotenv import load_dotenv
import gradio as gr
import os

# Load environment variables from .env file
load_dotenv()

# Database setup
DATABASE = 'documents.db'

# OpenAI API setup
# OpenAI API 키 설정
api_key = 'key'
openai.api_key = api_key
if not api_key:
    raise ValueError("API key is not set in the environment variables.")
openai.api_key = api_key

def get_db():
    return sqlite3.connect(DATABASE)

def check_grammar(text):
    if not text:
        return "No text provided"

    # Retrieve relevant documents
    with get_db() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT text FROM documents")
        rows = cursor.fetchall()
        context = " ".join([row[0] for row in rows])

    # Generate response
    response = openai.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": f"Check the grammar of this text but do not contain any texts from 'provided context': {text}\n\nContext: {context}"}
        ],
        max_tokens=100
    ).choices[0].message.content.strip()

    return response

# Create Gradio interface
iface = gr.Interface(
    fn=check_grammar,
    inputs=gr.Textbox(lines=5, label="Enter text to check grammar"),
    outputs=gr.Textbox(label="Corrected Text"),
    title="한국어 문장을 써 보세요!",
   
)

# Launch the Gradio app
if __name__ == '__main__':
    iface.launch()
  • 아래와 같이 결과가 나왔습니다. 😊

  1. app.py 코드를 조금 변형해 보았습니다.

import openai
from dotenv import load_dotenv
import gradio as gr
import os
from langchain import document_loaders
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain_community.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain_community.utilities import SQLDatabase
from langchain_community.document_loaders import DataFrameLoader
import pandas as pd
import sqlalchemy

# Load environment variables
load_dotenv()

# OpenAI API setup
api_key = 'Key'
openai.api_key = api_key
if not api_key:
    raise ValueError("API key is not set in the environment variables.")
openai.api_key = api_key

# Database setup
DATABASE = 'documents.db'

# Connect to the SQLite database
db = SQLDatabase.from_uri(f"sqlite:///{DATABASE}")

# Create a SQLAlchemy engine using the connection string
engine = sqlalchemy.create_engine(db._engine.url)

# Execute the query and load the results into a pandas DataFrame
df = pd.read_sql_query("SELECT text FROM documents", engine)

# Use DataFrameLoader to create documents
loader = DataFrameLoader(df, page_content_column="text")

# Load the documents
documents = loader.load()


# Create vector store
embeddings = OpenAIEmbeddings()
vector_store = FAISS.from_documents(documents, embeddings)

# Create prompt template
prompt_template = """You are a helpful assistant specializing in Korean language and grammar. Your task is to check and correct the grammar of Korean text input by users. Refer to the grammar rules and patterns stored in the database for guidance, but do not directly quote or include specific sentences from the database in your responses. Don't include any explanation.

Context: {context}

User's text: {question}

Provide a corrected version of the text but don't explain any grammar mistakes:"""

PROMPT = PromptTemplate(
    template=prompt_template, input_variables=["context", "question"]
)

# Create RetrievalQA chain
qa_chain = RetrievalQA.from_chain_type(
    llm=OpenAI(),
    chain_type="stuff",
    retriever=vector_store.as_retriever(),
    chain_type_kwargs={"prompt": PROMPT}
)

def check_grammar(text):
    if not text:
        return "No text provided"

    # Generate response using RAG
    response = qa_chain.run(text)
    return response

# Create Gradio interface
iface = gr.Interface(
    fn=check_grammar,
    inputs=gr.Textbox(lines=5, label="Enter text to check grammar"),
    outputs=gr.Textbox(label="Corrected Text"),
    title="한국어 문장을 써 보세요!",
)

# Launch the Gradio app
if __name__ == '__main__':
    iface.launch(share=True)
  • 아래와 같이 결과가 나왔습니다. 😊







#11기랭체인

5
2개의 답글

👉 이 게시글도 읽어보세요