M17idd commited on
Commit
d55f7c0
·
verified ·
1 Parent(s): 43d9a4f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -238
app.py CHANGED
@@ -1,219 +1,195 @@
 
1
  import streamlit as st
2
- import datetime
3
- import pandas as pd
4
- from typing import List
5
- from langchain_core.embeddings.embeddings import Embeddings
6
  from langchain.vectorstores import FAISS
7
- from langchain.prompts import ChatPromptTemplate
 
8
  from langchain.chat_models import ChatOpenAI
9
- from langchain.chains import ChatChain
10
- from langchain.text_splitter import RecursiveCharacterTextSplitter
11
- from langchain.schema import Document
12
- import re
13
 
14
- st.set_page_config(page_title="رزم‌یار ارتش", page_icon="🪖", layout="wide")
 
15
 
16
  # ----------------- استایل سفارشی -----------------
17
  st.markdown("""
18
  <style>
19
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;700&display=swap');
20
-
21
  html, body, [class*="css"] {
22
  font-family: 'Vazirmatn', Tahoma, sans-serif;
23
  direction: rtl;
24
  text-align: right;
25
  }
26
-
27
  .stApp {
28
- background: linear-gradient(to left, #4b5e40, #2e3b2e);
29
- color: #ffffff;
30
  }
31
-
32
- /* استایل سایدبار */
33
- [data-testid="stSidebar"] {
34
- width: 260px !important;
35
- background-color: #1a2b1e;
36
- border: none !important; /* حذف حاشیه زرد */
37
- padding-top: 20px;
38
  }
39
-
40
- .menu-item {
41
- display: flex;
42
- align-items: center;
43
- gap: 12px;
44
- padding: 12px 20px;
45
- font-size: 16px;
46
- color: #d4d4d4;
47
- cursor: pointer;
48
- transition: background-color 0.3s ease;
49
- }
50
-
51
- .menu-item:hover {
52
- background-color: #2e3b2e;
53
- color: #b8860b;
54
- }
55
-
56
- .menu-item img {
57
- width: 24px;
58
- height: 24px;
59
  }
60
-
61
- /* استایل دکمه‌ها */
62
  .stButton>button {
63
- background-color: #b8860b !important;
64
- color: #1a2b1e !important;
65
- font-family: 'Vazirmatn', Tahoma;
66
- font-weight: 700;
67
- border-radius: 10px;
68
- padding: 12px 24px;
69
- border: none;
70
- transition: all 0.3s ease;
71
- font-size: 16px;
72
- width: 100%;
73
- margin: 10px 0;
74
  }
75
-
76
  .stButton>button:hover {
77
- background-color: #8b6508 !important;
78
- transform: translateY(-2px);
79
- box-shadow: 0 4px 8px rgba(0,0,0,0.3);
80
  }
81
-
82
- /* استایل هدر */
83
  .header-text {
84
  text-align: center;
85
- margin: 20px 0;
86
- background-color: rgba(26, 43, 30, 0.9);
87
- padding: 25px;
88
- border-radius: 15px;
89
- box-shadow: 0 6px 12px rgba(0,0,0,0.4);
 
90
  }
91
-
92
  .header-text h1 {
93
- font-size: 42px;
94
- color: #b8860b;
95
  margin: 0;
96
- font-weight: 700;
97
  }
98
-
99
  .subtitle {
100
- font-size: 18px;
101
- color: #d4d4d4;
102
- margin-top: 10px;
103
  }
104
-
105
- /* استایل پیام چت */
106
  .chat-message {
107
- background-color: rgba(26, 43, 30, 0.95);
108
- border: 2px solid #b8860b;
109
- border-radius: 15px;
110
- padding: 20px;
111
- margin: 15px 0;
112
- box-shadow: 0 6px 12px rgba(0,0,0,0.3);
113
- animation: fadeIn 0.6s ease;
114
- font-size: 18px;
115
- color: #d4d4d4;
116
- display: flex;
117
- align-items: center;
118
- gap: 15px;
119
- }
120
-
121
- @keyframes fadeIn {
122
- from { opacity: 0; transform: translateY(10px); }
123
- to { opacity: 1; transform: translateY(0); }
124
  }
125
-
126
- /* استایل ورودی‌ها */
127
  .stTextInput>div>input, .stTextArea textarea {
128
- background-color: rgba(26, 43, 30, 0.95) !important;
129
- border-radius: 10px !important;
130
- border: 1px solid #b8860b !important;
131
- padding: 12px !important;
132
  font-family: 'Vazirmatn', Tahoma;
133
- font-size: 16px;
134
- color: #d4d4d4 !important;
135
  }
136
-
137
  img.small-logo {
138
- width: 120px;
139
- margin: 0 auto 20px;
140
  display: block;
 
 
141
  }
142
-
143
- hr {
144
- border: 1px solid #b8860b;
145
- margin: 15px 0;
 
 
 
146
  }
147
-
148
- /* رفع مشکل نوار زرد */
149
- [data-testid="stSidebar"] > div {
150
- border: none !important;
151
  }
152
  </style>
153
  """, unsafe_allow_html=True)
154
 
155
- # ----------------- احراز هویت ساده -----------------
156
- if "authenticated" not in st.session_state:
157
- st.session_state.authenticated = False
158
-
159
- if not st.session_state.authenticated:
160
- st.markdown("<h3 style='text-align: center; color: #b8860b;'>ورود به رزم‌یار ارتش</h3>", unsafe_allow_html=True)
161
- username = st.text_input("نام کاربری:", placeholder="شناسه نظامی خود را وارد کنید")
162
- password = st.text_input("رمز عبور:", type="password", placeholder="رمز عبور نظامی")
163
- if st.button("ورود"):
164
- if username == "admin" and password == "123":
165
- st.session_state.authenticated = True
166
- st.rerun()
167
- else:
168
- st.error("نام کاربری یا رمز عبور اشتباه است.")
169
- st.stop()
170
-
171
- # ----------------- سایدبار -----------------
172
  with st.sidebar:
173
- st.image("log.png", use_container_width=True)
174
-
175
- menu_items = [
176
- ("گزارش عملیاتی", "https://cdn-icons-png.flaticon.com/512/3596/3596165.png"),
177
- ("تاریخچه ماموریت‌ها", "https://cdn-icons-png.flaticon.com/512/709/709496.png"),
178
- ("تحلیل داده‌های نظامی", "https://cdn-icons-png.flaticon.com/512/1828/1828932.png"),
179
- ("مدیریت منابع", "https://cdn-icons-png.flaticon.com/512/681/681494.png"),
180
- ("دستیار فرماندهی", "https://cdn-icons-png.flaticon.com/512/3601/3601646.png"),
181
- ("تنظیمات امنیتی", "https://cdn-icons-png.flaticon.com/512/2099/2099058.png"),
182
- ("پشتیبانی فنی", "https://cdn-icons-png.flaticon.com/512/597/597177.png"),
183
- ]
184
 
185
- for idx, (text, icon) in enumerate(menu_items):
186
- st.markdown(f"""
187
- <div class="menu-item">
188
- <img src="{icon}" />
189
- {text}
190
- </div>
191
- """, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
- # ----------------- محتوای اصلی -----------------
194
  st.markdown("""
195
  <div class="header-text">
196
- <h1>رزم‌یار ارتش</h1>
197
- <div class="subtitle">دستیار هوشمند ارتش</div>
198
  </div>
199
  """, unsafe_allow_html=True)
200
 
201
- # پیام خوش‌آمدگویی
202
- st.markdown(f"""
203
- <div class="chat-message">
204
- <span style="font-size: 24px;">🪖</span>
205
- <span>به رزم‌یار ارتش خوش آمدید.</span>
206
- </div>
207
- """, unsafe_allow_html=True)
 
208
 
209
- # ----------------- کلاس توگدر امبدینگ -----------------
 
210
  class TogetherEmbeddings(Embeddings):
211
  def __init__(self, model_name: str, api_key: str):
212
  self.model_name = model_name
213
  self.client = Together(api_key=api_key)
214
 
215
  def embed_documents(self, texts: List[str]) -> List[List[float]]:
216
- batch_size = 100
 
217
  embeddings = []
218
  for i in range(0, len(texts), batch_size):
219
  batch = texts[i:i + batch_size]
@@ -224,99 +200,109 @@ class TogetherEmbeddings(Embeddings):
224
  def embed_query(self, text: str) -> List[float]:
225
  return self.embed_documents([text])[0]
226
 
227
-
228
- # ----------- پردازش و ایندکس کردن CSV -----------
229
  @st.cache_resource
230
- def build_vectorstore_from_csv(csv_file_path: str):
231
- df = pd.read_csv(csv_file_path)
232
- texts = df.iloc[:, 0].astype(str).tolist()
233
- texts = [text.strip() for text in texts if text.strip()]
234
-
235
- # برش متن‌ها
236
- text_splitter = RecursiveCharacterTextSplitter(
237
- chunk_size=2048,
238
- chunk_overlap=256,
239
- length_function=len,
240
- separators=["\n\n", "\n", " ", ""]
241
- )
242
- split_texts = []
243
- for text in texts:
244
- split_texts.extend(text_splitter.split_text(text))
245
 
246
- documents = [Document(page_content=text) for text in split_texts]
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
- embeddings = TogetherEmbeddings(
249
- model_name="togethercomputer/m2-bert-80M-32k-retrieval",
250
- api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979'
251
- )
 
252
 
253
- vectorstore = FAISS.from_documents(documents, embeddings)
254
- return vectorstore, embeddings
 
 
 
 
 
 
 
 
 
255
 
 
 
256
 
257
- # ----------- بارگذاری مدل زبانی -----------
258
- def load_llm():
259
- return ChatOpenAI(
260
- base_url="https://api.together.xyz/v1",
261
- api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979',
262
- model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
263
- )
264
 
265
 
266
- # ----------- پردازش ��وال و بازیابی پاسخ‌ها -----------
267
- def process_user_query(query: str, vectorstore, embedding_model, llm):
268
- # تبدیل سوال کاربر به امبدینگ
269
- query_embedding = embedding_model.embed_query(query)
270
-
271
- # جستجوی نزدیک‌ترین متون به سوال
272
- docs = vectorstore.similarity_search_by_vector(query_embedding, k=3)
273
- context = "\n".join([doc.page_content for doc in docs])
274
-
275
- # چک کردن وجود عدد یا اطلاعات عددی در پاسخ
276
- if "عدد" in query or "قیمت" in query: # اگر سوال عددی است
277
- # استخراج اطلاعات عددی از متون مشابه
278
- context = extract_numbers_from_text(context)
279
 
280
- # ارسال متن به مدل
281
- final_prompt = f"""با توجه به اطلاعات زیر، فقط بر اساس آن‌ها به سؤال پاسخ بده. اگر اطلاعات کافی نیست، بگو اطلاعات کافی ندارم.
282
- 🔹 اطلاعات:\n{context}\n\n❓ سؤال: {query}
283
- """
284
- response = llm.invoke(final_prompt)
285
- raw_answer = response.content.strip()
286
 
287
- clean_answer = raw_answer.strip() or "متأسفم، اطلاعات دقیقی در این مورد ندارم."
288
- return clean_answer
 
 
 
 
289
 
 
 
290
 
291
- def extract_numbers_from_text(text: str):
292
- # استخراج اعداد از متن
293
- numbers = re.findall(r'\d+(?:\.\d+)?', text)
294
- return "\n".join(numbers)
295
 
 
 
 
296
 
297
- # ----------- اجرای Streamlit UI -----------
298
- def run_chat_ui():
299
- csv_file_path = 'output (1).csv'
300
- try:
301
- vectorstore, embedding_model = build_vectorstore_from_csv(csv_file_path)
302
- except Exception as e:
303
- st.error(f"خطا در پردازش فایل: {str(e)}")
304
- return
305
-
306
- llm = load_llm()
307
 
308
- # فرم ورودی و دکمه‌ها
309
- with st.form(key="chat_form"):
310
- user_input = st.text_area("دستور یا پرس‌وجو:", height=120, placeholder="ماموریت یا سوال خود را وارد کنید...")
311
- submit_button = st.form_submit_button("ارسال دستور")
312
 
313
- if submit_button and user_input:
314
- response = process_user_query(user_input, vectorstore, embedding_model, llm)
315
- st.markdown(f"""
316
- <div class="chat-message">
317
- <span style="font-size: 24px;">🎖️</span>
318
- <span>{response}</span>
319
- </div>
320
- """, unsafe_allow_html=True)
321
-
322
- run_chat_ui()
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
  import streamlit as st
3
+ from langchain.document_loaders import PyPDFLoader
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.embeddings.base import Embeddings
 
6
  from langchain.vectorstores import FAISS
7
+ from langchain.indexes import VectorstoreIndexCreator
8
+ from langchain.chains import RetrievalQA
9
  from langchain.chat_models import ChatOpenAI
10
+ from typing import List
11
+ from together import Together
12
+ import pandas as pd
13
+ import streamlit as st
14
 
15
+ # ----------------- تنظیمات صفحه -----------------
16
+ st.set_page_config(page_title="رزم یار ارتش", page_icon="🪖", layout="wide")
17
 
18
  # ----------------- استایل سفارشی -----------------
19
  st.markdown("""
20
  <style>
21
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;700&display=swap');
 
22
  html, body, [class*="css"] {
23
  font-family: 'Vazirmatn', Tahoma, sans-serif;
24
  direction: rtl;
25
  text-align: right;
26
  }
 
27
  .stApp {
28
+ background: linear-gradient(to left, #f0f4f7, #d9e2ec);
 
29
  }
30
+ .sidebar .sidebar-content {
31
+ background-color: #ffffff;
32
+ border-left: 2px solid #4e8a3e;
33
+ padding-top: 10px;
 
 
 
34
  }
35
+ .sidebar .sidebar-content div {
36
+ margin-bottom: 10px;
37
+ font-weight: bold;
38
+ color: #2c3e50;
39
+ font-size: 15px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
 
 
41
  .stButton>button {
42
+ background-color: #4e8a3e !important;
43
+ color: white !important;
44
+ font-weight: bold;
45
+ border-radius: 8px;
46
+ padding: 5px 16px;
47
+ transition: 0.3s;
48
+ font-size: 14px;
 
 
 
 
49
  }
 
50
  .stButton>button:hover {
51
+ background-color: #3c6d30 !important;
 
 
52
  }
 
 
53
  .header-text {
54
  text-align: center;
55
+ margin-top: 15px;
56
+ margin-bottom: 25px;
57
+ background-color: rgba(255, 255, 255, 0.85);
58
+ padding: 16px;
59
+ border-radius: 16px;
60
+ box-shadow: 0 4px 10px rgba(0,0,0,0.1);
61
  }
 
62
  .header-text h1 {
63
+ font-size: 36px;
64
+ color: #2c3e50;
65
  margin: 0;
66
+ font-weight: bold;
67
  }
 
68
  .subtitle {
69
+ font-size: 16px;
70
+ color: #34495e;
71
+ margin-top: 5px;
72
  }
 
 
73
  .chat-message {
74
+ background-color: rgba(255, 255, 255, 0.95);
75
+ border: 1px solid #4e8a3e;
76
+ border-radius: 12px;
77
+ padding: 14px;
78
+ margin-bottom: 10px;
79
+ box-shadow: 0 4px 8px rgba(0,0,0,0.08);
80
+ animation: fadeIn 0.5s ease;
 
 
 
 
 
 
 
 
 
 
81
  }
 
 
82
  .stTextInput>div>input, .stTextArea textarea {
83
+ background-color: rgba(255,255,255,0.9) !important;
84
+ border-radius: 8px !important;
85
+ direction: rtl;
86
+ text-align: right;
87
  font-family: 'Vazirmatn', Tahoma;
 
 
88
  }
 
89
  img.small-logo {
90
+ width: 90px;
91
+ margin-bottom: 15px;
92
  display: block;
93
+ margin-right: auto;
94
+ margin-left: auto;
95
  }
96
+ .menu-item {
97
+ display: flex;
98
+ align-items: center;
99
+ gap: 8px;
100
+ padding: 6px 0;
101
+ font-size: 15px;
102
+ cursor: pointer;
103
  }
104
+ .menu-item img {
105
+ width: 20px;
106
+ height: 20px;
 
107
  }
108
  </style>
109
  """, unsafe_allow_html=True)
110
 
111
+ # ----------------- بدنه اصلی -----------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  with st.sidebar:
113
+ st.image("log.png", width=90)
114
+
 
 
 
 
 
 
 
 
 
115
 
116
+ st.markdown("""
117
+ <div class="menu-item">
118
+ <img src="https://cdn-icons-png.flaticon.com/512/3596/3596165.png" />
119
+ گفتگوی جدید
120
+ </div>
121
+ <div class="menu-item">
122
+ <img src="https://cdn-icons-png.flaticon.com/512/709/709496.png" />
123
+ تاریخچه
124
+ </div>
125
+ <hr/>
126
+ <div class="menu-item">
127
+ <img src="https://cdn-icons-png.flaticon.com/512/1828/1828932.png" />
128
+ مدل‌های هوش مصنوعی
129
+ </div>
130
+ <div class="menu-item">
131
+ <img src="https://cdn-icons-png.flaticon.com/512/681/681494.png" />
132
+ تولید محتوا
133
+ </div>
134
+ <hr/>
135
+ <div class="menu-item">
136
+ <img src="https://cdn-icons-png.flaticon.com/512/3601/3601646.png" />
137
+ دستیار ویژه
138
+ </div>
139
+ <div class="menu-item">
140
+ <img src="https://cdn-icons-png.flaticon.com/512/709/709612.png" />
141
+ ابزار مالی
142
+ </div>
143
+ <hr/>
144
+ <div class="menu-item">
145
+ <img src="https://cdn-icons-png.flaticon.com/512/2099/2099058.png" />
146
+ تنظیمات
147
+ </div>
148
+ <div class="menu-item">
149
+ <img src="https://cdn-icons-png.flaticon.com/512/597/597177.png" />
150
+ پشتیبانی
151
+ </div>
152
+ """, unsafe_allow_html=True)
153
+ st.markdown("""
154
+ <style>
155
+ /* تنظیم سایز سایدبار */
156
+ [data-testid="stSidebar"] {
157
+ width: 220px !important;
158
+ flex-shrink: 0;
159
+ }
160
+ [data-testid="stSidebar"] > div {
161
+ width: 220px !important;
162
+ }
163
+ </style>
164
+ """, unsafe_allow_html=True)
165
 
166
+ # محتوای اصلی
167
  st.markdown("""
168
  <div class="header-text">
169
+ <h1>رزم یار ارتش</h1>
170
+ <div class="subtitle">دستیار هوشمند ارتشی برای پشتیبانی و راهبری</div>
171
  </div>
172
  """, unsafe_allow_html=True)
173
 
174
+ st.markdown('<div class="chat-message">👋 سلام! چطور میتونم کمکتون کنم؟</div>', unsafe_allow_html=True)
175
+
176
+ # چت اینپوت کاربر
177
+ #user_input = st.text_input("پیام خود را وارد کنید...")
178
+
179
+ #if user_input:
180
+ # st.markdown(f'<div class="chat-message">📩 شما: {user_input}</div>', unsafe_allow_html=True)
181
+
182
 
183
+
184
+ # ----------------- لود csv و ساخت ایندکس -----------------
185
  class TogetherEmbeddings(Embeddings):
186
  def __init__(self, model_name: str, api_key: str):
187
  self.model_name = model_name
188
  self.client = Together(api_key=api_key)
189
 
190
  def embed_documents(self, texts: List[str]) -> List[List[float]]:
191
+ # تقسیم متن‌ها به دسته‌های کوچک‌تر برای جلوگیری از خطای 413
192
+ batch_size = 100 # این مقدار را می‌توانید تنظیم کنید
193
  embeddings = []
194
  for i in range(0, len(texts), batch_size):
195
  batch = texts[i:i + batch_size]
 
200
  def embed_query(self, text: str) -> List[float]:
201
  return self.embed_documents([text])[0]
202
 
 
 
203
  @st.cache_resource
204
+ def get_csv_index(csv_file):
205
+ with st.spinner('📄 در حال پردازش فایل CSV...'):
206
+ # خواندن داده‌های CSV
207
+ df = pd.read_csv(csv_file)
208
+
209
+ # تبدیل DataFrame به لیست از متون
210
+ texts = df.iloc[:, 0].astype(str).tolist() # ستون اول را می‌گیرد
 
 
 
 
 
 
 
 
211
 
212
+ # فیلتر کردن متن‌های خالی
213
+ texts = [text for text in texts if text.strip()]
214
+
215
+ # تقسیم متن‌های طولانی به بخش‌های کوچکتر
216
+ text_splitter = RecursiveCharacterTextSplitter(
217
+ chunk_size=300,
218
+ chunk_overlap=50,
219
+ length_function=len,
220
+ separators=["\n\n", "\n", " ", ""]
221
+ )
222
+
223
+ split_texts = []
224
+ for text in texts:
225
+ split_texts.extend(text_splitter.split_text(text))
226
 
227
+ # ایجاد embeddings
228
+ embeddings = TogetherEmbeddings(
229
+ model_name="togethercomputer/m2-bert-80M-8k-retrieval",
230
+ api_key="0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979"
231
+ )
232
 
233
+ # استفاده از VectorstoreIndexCreator برای ساخت ایندکس
234
+ index_creator = VectorstoreIndexCreator(
235
+ embedding=embeddings,
236
+ text_splitter=text_splitter
237
+ )
238
+
239
+ # تبدیل متون به اسناد (documents)
240
+ from langchain.docstore.document import Document
241
+ documents = [Document(page_content=text) for text in split_texts]
242
+
243
+ return index_creator.from_documents(documents)
244
 
245
+ # مسیر فایل CSV
246
+ csv_file_path = 'output (1).csv'
247
 
248
+ try:
249
+ # ساخت ایندکس
250
+ csv_index = get_csv_index(csv_file_path)
251
+ st.success("ایندکس فایل CSV با موفقیت ساخته شد!")
252
+ except Exception as e:
253
+ st.error(f"خطا در ساخت ایندکس: {str(e)}")
 
254
 
255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
+ #------------------------------------------
258
+ llm = ChatOpenAI(
259
+ base_url="https://api.together.xyz/v1",
260
+ api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979',
261
+ model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
262
+ )
263
 
264
+ chain = RetrievalQA.from_chain_type(
265
+ llm=llm,
266
+ chain_type='stuff',
267
+ retriever=csv_index.vectorstore.as_retriever(),
268
+ input_key='question'
269
+ )
270
 
271
+ if 'messages' not in st.session_state:
272
+ st.session_state.messages = []
273
 
274
+ if 'pending_prompt' not in st.session_state:
275
+ st.session_state.pending_prompt = None
 
 
276
 
277
+ for msg in st.session_state.messages:
278
+ with st.chat_message(msg['role']):
279
+ st.markdown(f"🗨️ {msg['content']}", unsafe_allow_html=True)
280
 
281
+ prompt = st.chat_input("چطور می‌تونم کمک کنم؟")
 
 
 
 
 
 
 
 
 
282
 
283
+ if prompt:
284
+ st.session_state.messages.append({'role': 'user', 'content': prompt})
285
+ st.session_state.pending_prompt = prompt
286
+ st.rerun()
287
 
288
+ if st.session_state.pending_prompt:
289
+ with st.chat_message('ai'):
290
+ thinking = st.empty()
291
+ thinking.markdown("🤖 در حال فکر کردن...")
292
+
293
+ response = chain.run(f'پاسخ را فقط به زبان فارسی جواب بده به هیچ عنوان از زبان چینی در پاسخ استفاده نکن. سوال: {st.session_state.pending_prompt}')
294
+ answer = response.split("Helpful Answer:")[-1].strip() if "Helpful Answer:" in response else response.strip()
295
+ if not answer:
296
+ answer = "متأسفم، اطلاعات دقیقی در این مورد ندارم."
297
+
298
+ thinking.empty()
299
+ full_response = ""
300
+ placeholder = st.empty()
301
+ for word in answer.split():
302
+ full_response += word + " "
303
+ placeholder.markdown(full_response + "▌")
304
+ time.sleep(0.03)
305
+
306
+ placeholder.markdown(full_response)
307
+ st.session_state.messages.append({'role': 'ai', 'content': full_response})
308
+ st.session_state.pending_prompt = None