| from langchain_community.llms import HuggingFaceHub |
| from langchain_community.embeddings import HuggingFaceEmbeddings |
| from langchain_community.vectorstores import FAISS |
| from langchain.chains import RetrievalQA |
| import os |
| import requests |
| import gradio as gr |
|
|
| |
| HF_TOKEN = os.environ.get("HF_TOKEN", "") |
| CLOUDFLARE_API = "https://notary-662-sbz.pages.dev/api/db/chats" |
|
|
| |
| llm = HuggingFaceHub( |
| repo_id="meta-llama/Meta-Llama-3-8B-Instruct", |
| huggingfacehub_api_token=HF_TOKEN, |
| model_kwargs={"temperature": 0.7, "max_new_tokens": 512} |
| ) |
|
|
| |
| embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2") |
|
|
| def query_rag_system(user_query, chat_id="default"): |
| |
| try: |
| vector_store = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True) |
| qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=vector_store.as_retriever()) |
| |
| |
| result = qa_chain.run(user_query) |
| |
| |
| chat_data = { |
| "id": chat_id, |
| "title": user_query[:30], |
| "docType": "notary_rag_llama", |
| "messages": [ |
| {"role": "user", "text": user_query}, |
| {"role": "model", "text": result} |
| ] |
| } |
| requests.post(CLOUDFLARE_API, json=chat_data) |
| |
| return result |
| except Exception as e: |
| return f"خطا در اتصال به بانک اسناد: {str(e)}" |
|
|
| |
| iface = gr.Interface( |
| fn=query_rag_system, |
| inputs="text", |
| outputs="text", |
| title="Notary Llama-3 RAG Engine", |
| description="این سیستم مستقیماً به Cloudflare و ۱۰۰ فایل PDF محضر متصل است." |
| ) |
|
|
| if __name__ == "__main__": |
| iface.launch() |
|
|