# data[].attributes.headline
제미나이 api활용 챗봇기

# data[].attributes.subject
제미나이 api활용 챗봇기

# data[].attributes.body
https://github.com/sumilee-pcu/libraryChatbot_gemini

# data[].attributes.attachment_link.description
Contribute to sumilee-pcu/libraryChatbot_gemini development by creating an account on GitHub.

# data[].attributes.attachment_link.readable_text
import os
import streamlit as st

from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI
from langchain.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.output_parsers import StrOutputParser
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_history_aware_retriever, create_retrieval_chain
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories.streamlit import StreamlitChatMessageHistory


__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
from langchain_chroma import Chroma


#Gemini API ��� ������
os.environ["GOOGLE_API_KEY"] = st.secrets["GOOGLE_API_KEY"]

#cache_resource��� ������ ��������� ������ ���������������
@st.cache_resource
def load_and_split_pdf(file_path):
    loader = PyPDFLoader(file_path)
    return loader.load_and_split()

#��������� ������������ Chroma ������ ��������� ��������� ������
@st.cache_resource
def create_vector_store(_docs):
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
    split_docs = text_splitter.split_documents(_docs)
    persist_directory = "./chroma_db"
    vectorstore = Chroma.from_documents(
        split_docs,
        GoogleGenerativeAIEmbeddings(model='models/embedding-001'),
        persist_directory=persist_directory
    )
    return vectorstore

#������ ��������� ������������ ChromaDB��� ������ ������, ������ ������
@st.cache_resource
def get_vectorstore(_docs):
    persist_directory = "./chroma_db"
    if os.path.exists(persist_directory):
        return Chroma(
            persist_directory=persist_directory,
            embedding_function=GoogleGenerativeAIEmbeddings(model='models/embedding-001')
        )
    else:
        return create_vector_store(_docs)
    
# PDF ������ ������-������ DB ������-���������-������������ ������ ������ Chain ������
@st.cache_resource
def initialize_components(selected_model):
    file_path = r"/mount/src/library_chatbot1/[���������������������������] ��������������� ���������.pdf"
    pages = load_and_split_pdf(file_path)
    vectorstore = get_vectorstore(pages)
    retriever = vectorstore.as_retriever()

    # ������ ������������ ������ ��������� ������������
    contextualize_q_system_prompt = """Given a chat history and the latest user question \
    which might reference context in the chat history, formulate a standalone question \
    which can be understood without the chat history. Do NOT answer the question, \
    just reformulate it if needed and otherwise return it as is."""
    contextualize_q_prompt = ChatPromptTemplate.from_messages(
        [
            ("system", contextualize_q_system_prompt),
            MessagesPlaceholder("history"),
            ("human", "{input}"),
        ]
    )

    # ������-������ ��������� ������������
    qa_system_prompt = """You are an assistant for question-answering tasks. \
    Use the following pieces of retrieved context to answer the question. \
    If you don't know the answer, just say that you don't know. \
    Keep the answer perfect. please use imogi with the answer.
    ��������� ������������ ������, ������������ ������.\

    {context}"""
    qa_prompt = ChatPromptTemplate.from_messages(
        [
            ("system", qa_system_prompt),
            MessagesPlaceholder("history"),
            ("human", "{input}"),
        ]
    )

    llm = ChatGoogleGenerativeAI(model=selected_model)
    history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_q_prompt)
    question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
    rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
    return rag_chain

# Streamlit UI
st.header("��������������� ��������� ������ Q&A ������ ���� ����")
option = st.selectbox("Select Gemini Model", ("gemini-1.5-pro", "gemini-1.5-flash"))
rag_chain = initialize_components(option)
chat_history = StreamlitChatMessageHistory(key="chat_messages")

conversational_rag_chain = RunnableWithMessageHistory(
    rag_chain,
    lambda session_id: chat_history,
    input_messages_key="input",
    history_messages_key="history",
    output_messages_key="answer",
)


if "messages" not in st.session_state:
    st.session_state["messages"] = [{"role": "assistant", 
                                     "content": "��������������� ��������� ��������� ������ ������������ ���������������!!!!!"}]

for msg in chat_history.messages:
    st.chat_message(msg.type).write(msg.content)


if prompt_message := st.chat_input("Your question"):
    st.chat_message("human").write(prompt_message)
    with st.chat_message("ai"):
        with st.spinner("Thinking..."):
            config = {"configurable": {"session_id": "any"}}
            response = conversational_rag_chain.invoke(
                {"input": prompt_message},
                config)
            
            answer = response['answer']
            st.write(answer)
            with st.expander("������ ������ ������"):
                for doc in response['context']:
                    st.markdown(doc.metadata['source'], help=doc.page_content)

# data[].attributes.body
https://aistudio.google.com/

# data[].attributes.attachment_link.readable_text
Send feedback Stay organized with collections Save and categorize content based on your preferences.

Google AI Studio is the fastest way to start building with Gemini, our next generation multimodal generative AI model.

# data[].attributes.attachment_link.title
Google AI Studio | Gemini API | Google for Developers

# data[].attributes.attachment_link.description
Send feedback Stay organized with collections Save and categorize content based on your preferences. Google AI Studio is the fastest way to start building with Gemini, our next generation multimodal generative AI model.

# data[].attributes.body
이상해요 ㅎㅎ

# data[].attributes.body
출석

# data[].attributes.body
...라고 할 때 살 걸!

# data[].attributes.body
출석

# data[].attributes.body
출석

# data[].attributes.body
출석

# data[].attributes.body
출석