Spaces:
Sleeping
Sleeping
import streamlit as st | |
from langchain_community.embeddings import HuggingFaceEmbeddings | |
from langchain_community.vectorstores import FAISS | |
from langchain_community.llms import HuggingFaceHub | |
from langchain.chains import RetrievalQA | |
from langchain.text_splitter import CharacterTextSplitter | |
from langchain.docstore.document import Document | |
from langchain.prompts import PromptTemplate | |
import os | |
# 設定 HuggingFace token | |
os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_your_token" | |
# 假資料:簡單 Q&A 列表 | |
qa_data = [ | |
{"問題": "什麼是AI?", "答案": "人工智慧(AI)是一種模擬人類智能的技術。"}, | |
{"問題": "LangChain是什麼?", "答案": "LangChain 是一個用於構建基於 LLM 的應用框架。"}, | |
{"問題": "FAISS有什麼用?", "答案": "FAISS 是一個用於高效相似度搜尋的向量資料庫工具。"}, | |
] | |
# 將問答資料轉換為 Document 格式 | |
def build_documents(qa_data): | |
docs = [] | |
for item in qa_data: | |
content = f"問題:{item['問題']}\n答案:{item['答案']}" | |
docs.append(Document(page_content=content)) | |
return docs | |
# 向量資料庫 | |
def create_vectorstore(docs, embeddings): | |
return FAISS.from_documents(docs, embedding=embeddings) | |
# 建立嵌入模型 | |
def get_embedding_model(): | |
return HuggingFaceEmbeddings(model_name="text2vec-base-chinese") | |
# 建立語言模型(ChatGLM3) | |
def get_llm_model(): | |
return HuggingFaceHub( | |
repo_id="THUDM/chatglm3-6b", | |
model_kwargs={"temperature": 0.1, "max_length": 2048} | |
) | |
# 建立問答鏈 | |
def build_qa_chain(llm, vectorstore): | |
return RetrievalQA.from_chain_type( | |
llm=llm, | |
retriever=vectorstore.as_retriever(), | |
chain_type="stuff", | |
return_source_documents=True | |
) | |
# Streamlit UI | |
st.title("💬 小型知識問答機器人") | |
st.markdown("目前使用內建知識,無需上傳 Excel") | |
# 準備模型與資料 | |
embedding_model = get_embedding_model() | |
llm_model = get_llm_model() | |
documents = build_documents(qa_data) | |
vectorstore = create_vectorstore(documents, embedding_model) | |
qa_chain = build_qa_chain(llm_model, vectorstore) | |
# 問答輸入 | |
user_question = st.text_input("請輸入你的問題:") | |
if st.button("送出") and user_question: | |
with st.spinner("思考中..."): | |
result = qa_chain({"query": user_question}) | |
st.success("回答:") | |
st.write(result["result"]) | |