[8기 랭체인방] MyBef 책 학습을 도와주는 러닝 메이트 (2)


https://github.com/Abdullahw72/langchain-chatbot-multiple-PDF

Langchain Chatbot for Multiple PDFs: Harnessing GPT and Free Huggingface LLM Alternatives
  • 위의 github 오픈소스는 PDF 를 업로드하면 그것을 읽어들여 chunk 로 분할하여 embedding 후 vector store 에 저장 후 질문 및 대답을 표현하는 streamlit UI 를 포함하고 있다. 가장 단순하면서도 langchain 을 활용하는 일반적인 유스케이스로 생각해서 선택했다.

  • 이번주차에는 코드를 이해하고 로컬 환경에서 실행되고 결과를 일반 chatgpt 와 비교 할수 있도록 하였다. 기대하기로는 관련된 문서를 업로드한 방식이 보다 구체적인 답변을 얻기를 기대한다

  • 영문으로 테스트 했으며 OpenRTB API Specification 문서를 업로드하여 기술적인 질문을 해보았다.


ChatGPT3.5

langchain embedding


향후 방향

학습을 위해서는 학습자가 질문하는게 하니라 메이트가 질문을 해야 한다. 메이트가 학습자에게 한 질문에 대해 메이트는 정답 채점을 할수 있을까?

학습을 목적으로 한 인풋, 아웃풋 형식에 대한 프롬프트는 어떻게 구성해야 할까?

코드 분석

t_template, user_template, css

from transformers import pipeline

def get_pdf_text(pdf_files):
    
    text = ""
    for pdf_file in pdf_files:
        reader = PdfReader(pdf_file)
        for page in reader.pages:
            text += page.extract_text()
    return text

def get_chunk_text(text):
    
    text_splitter = CharacterTextSplitter(
    separator = "\n",
    chunk_size = 1000,
    chunk_overlap = 200,
    length_function = len
    )

    chunks = text_splitter.split_text(text)

    return chunks


def get_vector_store(text_chunks):
    
    # For OpenAI Embeddings
    
    embeddings = OpenAIEmbeddings()
    
    # For Huggingface Embeddings

    # embeddings = HuggingFaceInstructEmbeddings(model_name = "hkunlp/instructor-xl")

    vectorstore = FAISS.from_texts(texts = text_chunks, embedding = embeddings)
    
    return vectorstore

def get_conversation_chain(vector_store):
    
    # OpenAI Model

    llm = ChatOpenAI()

    # HuggingFace Model

    # llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512})

    memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)

    conversation_chain = ConversationalRetrievalChain.from_llm(
        llm = llm,
        retriever = vector_store.as_retriever(),
        memory = memory
    )

    return conversation_chain

def handle_user_input(question):

    response = st.session_state.conversation({'question':question})
    st.session_state.chat_history = response['chat_history']

    for i, message in enumerate(st.session_state.chat_history):
        if i % 2 == 0:
            st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
        else:
            st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)



def main():
    load_dotenv()
    st.set_page_config(page_title='Chat with Your own PDFs', page_icon=':books:')

    st.write(css, unsafe_allow_html=True)
    
    if "conversation" not in st.session_state:
        st.session_state.conversation = None

    if "chat_history" not in st.session_state:
        st.session_state.chat_history = None
    
    st.header('Chat with Your own PDFs :books:')
    question = st.text_input("Ask anything to your PDF: ")

    if question:
        handle_user_input(question)
    

    with st.sidebar:
        st.subheader("Upload your Documents Here: ")
        pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True)

        if st.button("OK"):
            with st.spinner("Processing your PDFs..."):

                # Get PDF Text
                raw_text = get_pdf_text(pdf_files)

                # Get Text Chunks
                text_chunks = get_chunk_text(raw_text)
                

                # Create Vector Store
                
                vector_store = get_vector_store(text_chunks)
                st.write("DONE")

                # Create conversation chain

                st.session_state.conversation =  get_conversation_chain(vector_store)


if __name__ == '__main__':
    main()
4

👉 이 게시글도 읽어보세요