Pavan2k4 commited on
Commit
7f5dc30
Β·
verified Β·
1 Parent(s): ee28456

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -53
app.py CHANGED
@@ -1,64 +1,87 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import os
2
  import gradio as gr
3
+ from langchain.chains import RetrievalQA
4
+ from langchain_pinecone import Pinecone
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain_community.llms import HuggingFacePipeline
7
+ from langchain_community.embeddings import HuggingFaceEmbeddings
8
+ from dotenv import load_dotenv
9
+ import torch
10
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, pipeline, AutoTokenizer
11
+ from huggingface_hub import login
12
 
13
+ # Load environment variables
14
+ load_dotenv()
15
+ login(token=os.environ.get('HF_KEY'))
 
16
 
17
+ # Initialize Embedding Model
18
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
19
 
20
+ # Pinecone Retriever
21
+ api_key = os.environ.get('PINCE_CONE_LIGHT')
22
+ if api_key is None:
23
+ raise ValueError("Pinecone API key missing.")
24
+ else:
25
+ pc = Pinecone(pinecone_api_key=api_key, embedding=embedding_model, index_name='rag-rubic', namespace='vectors_lightmodel')
26
+ retriever = pc.as_retriever()
 
 
27
 
28
+ # LLM Options
29
+ llm_options = {
30
+ "OpenAI": "gpt-4o-mini",
31
+ "Microsoft-Phi": "microsoft/Phi-3.5-mini-instruct",
32
+ "DeepSeek-R1": "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
33
+ "Intel-tinybert": "Intel/dynamic_tinybert"
34
+ }
35
 
36
+ def load_llm(name, model_name):
37
+ """Loads the selected LLM model only when needed."""
38
+ if name == "OpenAI":
39
+ openai_api_key = os.environ.get('OPEN_AI_KEY')
40
+ return ChatOpenAI(model='gpt-4o-mini', openai_api_key=openai_api_key)
41
+
42
+ if "Phi" in name or "DeepSeek" in name:
43
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype=torch.float16)
44
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
45
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_length=4096, eos_token_id=tokenizer.eos_token_id, return_full_text=False,
46
+ do_sample=False, num_return_sequences=1, max_new_tokens=50, temperature=0.1)
47
+ elif "tinybert" in name:
48
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
49
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
50
+ pipe = pipeline("feature-extraction", model=model, tokenizer=tokenizer, truncation=True, padding=True, max_length=512)
51
+ else:
52
+ return None
53
+
54
+ return HuggingFacePipeline(pipeline=pipe)
55
 
56
+ # Initialize default LLM
57
+ selected_llm = list(llm_options.keys())[0]
58
+ llm = load_llm(selected_llm, llm_options[selected_llm])
59
 
60
+ # Create QA Retrieval Chain
61
+ qa = RetrievalQA.from_llm(llm=llm, retriever=retriever)
 
 
 
 
 
 
62
 
63
+ # Chatbot function
64
+ def chatbot(selected_llm, user_input, chat_history):
65
+ global llm
66
+ if selected_llm != llm.model_name:
67
+ llm = load_llm(selected_llm, llm_options[selected_llm])
68
+
69
+ response = qa.invoke({"query": user_input})
70
+ answer = response.get("result", "No response received.")
71
+ chat_history.append(("πŸ§‘β€πŸ’» You", user_input))
72
+ chat_history.append(("πŸ€– Bot", answer))
73
+ return chat_history, ""
74
 
75
+ # Gradio Interface
76
+ with gr.Blocks() as demo:
77
+ gr.Markdown("# πŸ€– RAG-Powered Chatbot")
78
+ llm_selector = gr.Dropdown(choices=list(llm_options.keys()), value=selected_llm, label="Choose an LLM")
79
+ chat_history = gr.State([])
80
+ chatbot_ui = gr.Chatbot()
81
+ user_input = gr.Textbox(label="πŸ’¬ Type your message and press Enter:")
82
+ send_button = gr.Button("Send")
83
+
84
+ send_button.click(chatbot, inputs=[llm_selector, user_input, chat_history], outputs=[chatbot_ui, user_input])
85
+ user_input.submit(chatbot, inputs=[llm_selector, user_input, chat_history], outputs=[chatbot_ui, user_input])
86
 
87
+ demo.launch()