Update app.py
Browse files
app.py
CHANGED
@@ -1,30 +1,23 @@
|
|
1 |
import streamlit as st
|
2 |
from langchain_huggingface import HuggingFaceEmbeddings
|
3 |
from langchain_community.vectorstores import Chroma
|
4 |
-
from langchain_community.llms import HuggingFaceHub
|
5 |
from langchain.prompts import PromptTemplate
|
6 |
-
from langchain.chains import
|
7 |
from langchain.memory import ConversationBufferMemory
|
8 |
import warnings
|
9 |
-
from transformers import pipeline
|
10 |
-
import torch
|
11 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
12 |
import os
|
13 |
from dotenv import load_dotenv
|
14 |
-
from langchain_huggingface import
|
15 |
-
from langchain_community.llms import HuggingFaceEndpoint
|
16 |
-
|
17 |
|
18 |
warnings.filterwarnings("ignore")
|
19 |
load_dotenv()
|
20 |
-
api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
21 |
|
22 |
# Constants and configurations
|
23 |
APP_TITLE = "π Asisten Kesehatan Feminacare"
|
24 |
INITIAL_MESSAGE = """Halo! π Saya adalah asisten kesehatan feminacare yang siap membantu Anda dengan informasi seputar kesehatan wanita.
|
25 |
Silakan ajukan pertanyaan apa saja dan saya akan membantu Anda dengan informasi yang akurat."""
|
26 |
|
27 |
-
# Model configurations
|
28 |
MODEL_NAME = "SeaLLMs/SeaLLMs-v3-7B-Chat"
|
29 |
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
30 |
TOP_K_DOCS = 5
|
@@ -40,19 +33,21 @@ def initialize_models():
|
|
40 |
return vector_store
|
41 |
|
42 |
def create_llm():
|
43 |
-
"""Initialize the language model with
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
)
|
49 |
-
|
50 |
-
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME,
|
51 |
-
quantization_config=bnb_config
|
52 |
-
)
|
53 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
54 |
|
55 |
-
terminators
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
text_generation_pipeline = pipeline(
|
58 |
model=model,
|
@@ -66,51 +61,16 @@ def create_llm():
|
|
66 |
eos_token_id=terminators,
|
67 |
)
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
# return HuggingFaceHub(
|
72 |
-
# repo_id=MODEL_NAME,
|
73 |
-
# model_kwargs={
|
74 |
-
# "temperature": 0.7, # Balanced between creativity and accuracy
|
75 |
-
# "max_new_tokens": 1024,
|
76 |
-
# "top_p": 0.9,
|
77 |
-
# "frequency_penalty": 0.5
|
78 |
-
# }
|
79 |
-
# )
|
80 |
-
# llm = HuggingFaceEndpoint(
|
81 |
-
# repo_id=MODEL_NAME,
|
82 |
-
# huggingfacehub_api_token = api_token,
|
83 |
-
# temperature = 0.7,
|
84 |
-
# max_new_tokens = 1024,
|
85 |
-
# top_k = 0.9,
|
86 |
-
# )
|
87 |
-
# llm = HuggingFacePipeline.from_model_id(
|
88 |
-
# model_id=MODEL_NAME,
|
89 |
-
# task="text-generation",
|
90 |
-
# pipeline_kwargs=dict(
|
91 |
-
# max_new_tokens=512,
|
92 |
-
# do_sample=False,
|
93 |
-
# repetition_penalty=1.03,
|
94 |
-
# ),
|
95 |
-
# )
|
96 |
-
return llm
|
97 |
-
|
98 |
-
|
99 |
-
# chat_model = ChatHuggingFace(llm=llm)
|
100 |
|
101 |
-
# Improved prompt template with better context handling and response structure
|
102 |
PROMPT_TEMPLATE = """
|
103 |
Anda adalah asisten kesehatan profesional dengan nama Feminacare.
|
104 |
Berikan informasi yang akurat, jelas, dan bermanfaat berdasarkan konteks yang tersedia.
|
105 |
-
|
106 |
Context yang tersedia:
|
107 |
{context}
|
108 |
-
|
109 |
Chat historyt:
|
110 |
{chat_history}
|
111 |
-
|
112 |
Question: {question}
|
113 |
-
|
114 |
Instruksi untuk menjawab:
|
115 |
1. Berikan jawaban yang LENGKAP dan TERSTRUKTUR
|
116 |
2. Selalu sertakan SUMBER informasi dari konteks yang diberikan
|
@@ -118,7 +78,6 @@ Instruksi untuk menjawab:
|
|
118 |
4. Gunakan bahasa yang mudah dipahami
|
119 |
5. Jika relevan, berikan poin-poin penting menggunakan format yang rapi
|
120 |
6. Akhiri dengan anjuran untuk konsultasi dengan tenaga kesehatan jika diperlukan
|
121 |
-
|
122 |
Answer:
|
123 |
"""
|
124 |
|
@@ -137,14 +96,10 @@ def setup_qa_chain(vector_store):
|
|
137 |
|
138 |
return ConversationalRetrievalChain.from_llm(
|
139 |
llm=create_llm(),
|
140 |
-
retriever=vector_store.as_retriever(
|
141 |
-
# search_type="mmr", # Maximum Marginal Relevance for better diversity
|
142 |
-
# search_kwargs={"k": TOP_K_DOCS}
|
143 |
-
),
|
144 |
memory=memory,
|
145 |
-
|
146 |
return_source_documents=True,
|
147 |
-
# return_generated_question=True,
|
148 |
)
|
149 |
|
150 |
def initialize_session_state():
|
@@ -199,8 +154,8 @@ def create_ui():
|
|
199 |
def handle_user_input(prompt):
|
200 |
"""Handle user input and generate response"""
|
201 |
with st.spinner("Sedang menyiapkan jawaban..."):
|
202 |
-
|
203 |
-
|
204 |
|
205 |
def main():
|
206 |
initialize_session_state()
|
|
|
1 |
import streamlit as st
|
2 |
from langchain_huggingface import HuggingFaceEmbeddings
|
3 |
from langchain_community.vectorstores import Chroma
|
|
|
4 |
from langchain.prompts import PromptTemplate
|
5 |
+
from langchain.chains import ConversationalRetrievalChain
|
6 |
from langchain.memory import ConversationBufferMemory
|
7 |
import warnings
|
8 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
|
|
|
|
9 |
import os
|
10 |
from dotenv import load_dotenv
|
11 |
+
from langchain_huggingface import HuggingFacePipeline
|
|
|
|
|
12 |
|
13 |
warnings.filterwarnings("ignore")
|
14 |
load_dotenv()
|
|
|
15 |
|
16 |
# Constants and configurations
|
17 |
APP_TITLE = "π Asisten Kesehatan Feminacare"
|
18 |
INITIAL_MESSAGE = """Halo! π Saya adalah asisten kesehatan feminacare yang siap membantu Anda dengan informasi seputar kesehatan wanita.
|
19 |
Silakan ajukan pertanyaan apa saja dan saya akan membantu Anda dengan informasi yang akurat."""
|
20 |
|
|
|
21 |
MODEL_NAME = "SeaLLMs/SeaLLMs-v3-7B-Chat"
|
22 |
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
23 |
TOP_K_DOCS = 5
|
|
|
33 |
return vector_store
|
34 |
|
35 |
def create_llm():
|
36 |
+
"""Initialize the language model with auto device mapping"""
|
37 |
+
model = AutoModelForCausalLM.from_pretrained(
|
38 |
+
MODEL_NAME,
|
39 |
+
device_map="auto",
|
40 |
+
trust_remote_code=True
|
41 |
)
|
|
|
|
|
|
|
|
|
42 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
43 |
|
44 |
+
# Get terminators for the model
|
45 |
+
terminators = [tokenizer.eos_token_id]
|
46 |
+
if hasattr(tokenizer, 'convert_tokens_to_ids'):
|
47 |
+
try:
|
48 |
+
terminators.append(tokenizer.convert_tokens_to_ids("<|eot_id|>"))
|
49 |
+
except:
|
50 |
+
pass
|
51 |
|
52 |
text_generation_pipeline = pipeline(
|
53 |
model=model,
|
|
|
61 |
eos_token_id=terminators,
|
62 |
)
|
63 |
|
64 |
+
return HuggingFacePipeline(pipeline=text_generation_pipeline)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
|
|
66 |
PROMPT_TEMPLATE = """
|
67 |
Anda adalah asisten kesehatan profesional dengan nama Feminacare.
|
68 |
Berikan informasi yang akurat, jelas, dan bermanfaat berdasarkan konteks yang tersedia.
|
|
|
69 |
Context yang tersedia:
|
70 |
{context}
|
|
|
71 |
Chat historyt:
|
72 |
{chat_history}
|
|
|
73 |
Question: {question}
|
|
|
74 |
Instruksi untuk menjawab:
|
75 |
1. Berikan jawaban yang LENGKAP dan TERSTRUKTUR
|
76 |
2. Selalu sertakan SUMBER informasi dari konteks yang diberikan
|
|
|
78 |
4. Gunakan bahasa yang mudah dipahami
|
79 |
5. Jika relevan, berikan poin-poin penting menggunakan format yang rapi
|
80 |
6. Akhiri dengan anjuran untuk konsultasi dengan tenaga kesehatan jika diperlukan
|
|
|
81 |
Answer:
|
82 |
"""
|
83 |
|
|
|
96 |
|
97 |
return ConversationalRetrievalChain.from_llm(
|
98 |
llm=create_llm(),
|
99 |
+
retriever=vector_store.as_retriever(),
|
|
|
|
|
|
|
100 |
memory=memory,
|
101 |
+
combine_docs_chain_kwargs={"prompt": custom_prompt},
|
102 |
return_source_documents=True,
|
|
|
103 |
)
|
104 |
|
105 |
def initialize_session_state():
|
|
|
154 |
def handle_user_input(prompt):
|
155 |
"""Handle user input and generate response"""
|
156 |
with st.spinner("Sedang menyiapkan jawaban..."):
|
157 |
+
response = st.session_state.qa_chain({"question": prompt})
|
158 |
+
return response["answer"]
|
159 |
|
160 |
def main():
|
161 |
initialize_session_state()
|