Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
import logging
|
| 4 |
from langchain.chains import ConversationalRetrievalChain
|
| 5 |
from langchain.text_splitter import CharacterTextSplitter
|
| 6 |
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
|
|
@@ -8,9 +7,6 @@ from langchain_community.vectorstores import Chroma
|
|
| 8 |
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
|
| 11 |
-
# 設定日誌級別,顯示更多詳細資訊
|
| 12 |
-
logging.basicConfig(level=logging.DEBUG)
|
| 13 |
-
|
| 14 |
# 加載環境變量
|
| 15 |
load_dotenv()
|
| 16 |
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
|
@@ -20,9 +16,12 @@ api_key = os.getenv('OPENAI_API_KEY')
|
|
| 20 |
if not api_key:
|
| 21 |
raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
# 將聊天歷史轉換為適合 LangChain 的二元組格式
|
| 24 |
def transform_history_for_langchain(history):
|
| 25 |
-
return [(chat[0], chat[1]) for chat in history if chat[0]]
|
| 26 |
|
| 27 |
# 將 Gradio 的歷史紀錄轉換為 OpenAI 格式
|
| 28 |
def transform_history_for_openai(history):
|
|
@@ -49,11 +48,9 @@ def load_and_process_documents(folder_path):
|
|
| 49 |
loader = TextLoader(file_path)
|
| 50 |
documents.extend(loader.load())
|
| 51 |
|
| 52 |
-
# 使用 CharacterTextSplitter 分割文檔
|
| 53 |
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=10)
|
| 54 |
documents = text_splitter.split_documents(documents)
|
| 55 |
|
| 56 |
-
# 建立向量數據庫
|
| 57 |
vectordb = Chroma.from_documents(
|
| 58 |
documents,
|
| 59 |
embedding=OpenAIEmbeddings(),
|
|
@@ -82,7 +79,7 @@ def handle_query(user_message, temperature, chat_history):
|
|
| 82 |
previous_answers = transform_history_for_langchain(chat_history)
|
| 83 |
|
| 84 |
pdf_qa = ConversationalRetrievalChain.from_llm(
|
| 85 |
-
ChatOpenAI(temperature=temperature, model_name='gpt-
|
| 86 |
retriever=vectordb.as_retriever(search_kwargs={'k': 6}),
|
| 87 |
return_source_documents=True,
|
| 88 |
verbose=False
|
|
@@ -101,20 +98,19 @@ def handle_query(user_message, temperature, chat_history):
|
|
| 101 |
return chat_history
|
| 102 |
|
| 103 |
except Exception as e:
|
| 104 |
-
logging.error(f"處理查詢時出現錯誤: {e}")
|
| 105 |
return chat_history + [("系統", f"出現錯誤: {str(e)}")]
|
| 106 |
|
| 107 |
# 使用 Gradio 的 Blocks API 創建自訂聊天介面
|
| 108 |
with gr.Blocks() as demo:
|
| 109 |
gr.Markdown("<h1 style='text-align: center;'>AI 小助教</h1>")
|
| 110 |
|
| 111 |
-
chatbot = gr.Chatbot(
|
| 112 |
state = gr.State([])
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
-
with gr.Column(scale=
|
| 116 |
txt = gr.Textbox(show_label=False, placeholder="請輸入您的問題...")
|
| 117 |
-
with gr.Column(scale=
|
| 118 |
submit_btn = gr.Button("提問")
|
| 119 |
|
| 120 |
# 用戶輸入後立即顯示提問文字,不添加回應部分,並清空輸入框
|
|
@@ -138,5 +134,5 @@ with gr.Blocks() as demo:
|
|
| 138 |
bot_response, state, [chatbot, state]
|
| 139 |
)
|
| 140 |
|
| 141 |
-
# 啟動 Gradio 應用
|
| 142 |
-
demo.launch(
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
|
|
|
| 3 |
from langchain.chains import ConversationalRetrievalChain
|
| 4 |
from langchain.text_splitter import CharacterTextSplitter
|
| 5 |
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
|
|
|
|
| 7 |
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
|
|
|
|
|
|
|
|
|
|
| 10 |
# 加載環境變量
|
| 11 |
load_dotenv()
|
| 12 |
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
|
|
|
| 16 |
if not api_key:
|
| 17 |
raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")
|
| 18 |
|
| 19 |
+
# OpenAI API key
|
| 20 |
+
openai_api_key = api_key
|
| 21 |
+
|
| 22 |
# 將聊天歷史轉換為適合 LangChain 的二元組格式
|
| 23 |
def transform_history_for_langchain(history):
|
| 24 |
+
return [(chat[0], chat[1]) for chat in history if chat[0]] # 使用整數索引來訪問元組中的元素
|
| 25 |
|
| 26 |
# 將 Gradio 的歷史紀錄轉換為 OpenAI 格式
|
| 27 |
def transform_history_for_openai(history):
|
|
|
|
| 48 |
loader = TextLoader(file_path)
|
| 49 |
documents.extend(loader.load())
|
| 50 |
|
|
|
|
| 51 |
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=10)
|
| 52 |
documents = text_splitter.split_documents(documents)
|
| 53 |
|
|
|
|
| 54 |
vectordb = Chroma.from_documents(
|
| 55 |
documents,
|
| 56 |
embedding=OpenAIEmbeddings(),
|
|
|
|
| 79 |
previous_answers = transform_history_for_langchain(chat_history)
|
| 80 |
|
| 81 |
pdf_qa = ConversationalRetrievalChain.from_llm(
|
| 82 |
+
ChatOpenAI(temperature=temperature, model_name='gpt-4o'),
|
| 83 |
retriever=vectordb.as_retriever(search_kwargs={'k': 6}),
|
| 84 |
return_source_documents=True,
|
| 85 |
verbose=False
|
|
|
|
| 98 |
return chat_history
|
| 99 |
|
| 100 |
except Exception as e:
|
|
|
|
| 101 |
return chat_history + [("系統", f"出現錯誤: {str(e)}")]
|
| 102 |
|
| 103 |
# 使用 Gradio 的 Blocks API 創建自訂聊天介面
|
| 104 |
with gr.Blocks() as demo:
|
| 105 |
gr.Markdown("<h1 style='text-align: center;'>AI 小助教</h1>")
|
| 106 |
|
| 107 |
+
chatbot = gr.Chatbot()
|
| 108 |
state = gr.State([])
|
| 109 |
|
| 110 |
with gr.Row():
|
| 111 |
+
with gr.Column(scale=0.85):
|
| 112 |
txt = gr.Textbox(show_label=False, placeholder="請輸入您的問題...")
|
| 113 |
+
with gr.Column(scale=0.15, min_width=0):
|
| 114 |
submit_btn = gr.Button("提問")
|
| 115 |
|
| 116 |
# 用戶輸入後立即顯示提問文字,不添加回應部分,並清空輸入框
|
|
|
|
| 134 |
bot_response, state, [chatbot, state]
|
| 135 |
)
|
| 136 |
|
| 137 |
+
# 啟動 Gradio 應用
|
| 138 |
+
demo.launch()
|