File size: 11,453 Bytes
2c517f0
 
 
 
 
 
 
 
 
9dc7296
2c517f0
 
 
 
 
 
 
 
 
 
 
 
 
bc66dcc
2c517f0
bc66dcc
2c517f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196447c
 
 
2c517f0
 
 
 
2bed213
ccd6857
2ab7919
2c517f0
 
 
 
 
196447c
 
 
2c517f0
 
 
 
 
 
 
 
 
 
 
 
196447c
 
 
2c517f0
 
 
 
 
 
 
 
 
 
 
 
24fd24e
f6a850b
2c517f0
 
 
2bed213
 
 
 
2c517f0
2bed213
2c517f0
 
2bed213
2c517f0
 
 
 
 
2bed213
2c517f0
 
 
 
 
 
 
 
 
 
 
ccd6857
2c517f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import streamlit as st
import os
from typing import Optional, List
from dotenv import load_dotenv
import gdown
import llm_providers
import tantivy_search
import json
import zipfile
import agent


INDEX_PATH = "./index"

# Load environment variables
load_dotenv()

class SearchAgentUI:
    index_path = INDEX_PATH
    gdrive_index_id = os.getenv("GDRIVE_INDEX_ID", "1lpbBCPimwcNfC0VZOlQueA4SHNGIp5_t")

   
    @st.cache_resource
    def get_agent(_self,api_keys): 
        index_path = INDEX_PATH
        return agent.Agent(index_path,api_keys)    

    def download_index_from_gdrive(self) -> bool:
        try:
            zip_path = "index.zip"
            url = f"https://drive.google.com/uc?id={self.gdrive_index_id}"
            gdown.download(url, zip_path, quiet=False)  
            with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                zip_ref.extractall(".")
            os.remove(zip_path) 
            return True
        
        except Exception as e:
            st.error(f"Failed to download index: {str(e)}")
            return False
        
        
    @st.cache_resource
    def initialize_system(_self,api_keys:dict[str,str]) -> tuple[bool, str, List[str]]:
        
        try:
            # download index
            if not os.path.exists(_self.index_path):
                st.warning("Index folder not found. Attempting to download from Google Drive...")
                if not _self.download_index_from_gdrive():
                    return False, "שגיאה: לא ניתן להוריד את האינדקס", []
                st.success("Index downloaded successfully!")
            _self.llm_providers = llm_providers.LLMProvider(api_keys)   
            available_providers = _self.llm_providers.get_available_providers()
            if not available_providers:
                return False, "שגיאה: לא נמצאו ספקי AI זמינים. אנא הזן מפתח API אחד לפחות.", []           
            return True, "המערכת מוכנה לחי শবפש", available_providers
         
        except Exception as ex:
            return False, f"שגיאה באתחול המערכת: {str(ex)}", []

    def update_messages(self, messages):
        st.session_state.messages = messages
        
    def main(self):
        st.set_page_config(
            page_title="איתוריא",
            layout="wide",
            initial_sidebar_state="expanded"
        )
        
        
        # Enhanced styling with better visual hierarchy and modern design
        st.markdown("""
        <style>
            /* Global RTL Support */
            .stApp {
                direction: rtl;
                background-color: #f8f9fa;
            }
            
            /* Input Fields RTL */
            .stTextInput > div > div > input,
            .stSelectbox > div > div > div,
            .stNumberInput > div > div > input {
                direction: rtl;
                border-radius: 8px !important;
                border: 2px solid #e2e8f0 !important;
                padding: 0.75rem !important;
                transition: all 0.3s ease;
            }
            
            .stTextInput > div > div > input:focus,
            .stSelectbox > div > div > div:focus {
                border-color: #4299e1 !important;
                box-shadow: 0 0 0 1px #4299e1 !important;
            }
            
            /* Message Containers */
            .chat-container {
                background: white;
                border-radius: 12px;
                padding: 1.5rem;
                margin: 1rem 0;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            
            /* Tool Calls Styling */
            .tool-call {
                background: #f0f7ff;
                border-radius: 8px;
                padding: 1rem;
                margin: 0.5rem 0;
                border-right: 4px solid #3182ce;
            }
            
            /* Search Results */
            .search-step {
                background: white;
                border-radius: 10px;
                padding: 1.25rem;
                margin: 1rem 0;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                border: 1px solid #e2e8f0;
            }
            
            .document-group {
                background: #f7fafc;
                border-radius: 8px;
                padding: 1rem;
                margin: 0.75rem 0;
                border: 1px solid #e2e8f0;
            }
            
            .document-item {
                background: white;
                border-radius: 6px;
                padding: 1rem;
                margin: 0.5rem 0;
                border: 1px solid #edf2f7;
            }
            
            /* Sidebar Styling */
            [data-testid="stSidebar"] {
                direction: rtl;
                background-color: #f8fafc;
                padding: 2rem 1rem;
            }
            
            .sidebar-content {
                padding: 1rem;
            }
            
            /* Chat Messages */
            .stChatMessage {
                direction: rtl;
                background: white !important;
                border-radius: 12px !important;
                padding: 1rem !important;
                margin: 0.75rem 0 !important;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05) !important;
            }
            
            /* Buttons */
            .stButton > button {
                border-radius: 8px !important;
                padding: 0.5rem 1.5rem !important;
                background-color: #3182ce !important;
                color: white !important;
                border: none !important;
                transition: all 0.3s ease !important;
            }
            
            .stButton > button:hover {
                background-color: #2c5282 !important;
                transform: translateY(-1px);
            }
            
            /* Code Blocks */
            .stCodeBlock {
                direction: ltr;
                text-align: left;
                border-radius: 8px !important;
                background: #2d3748 !important;
            }
            
            /* Links */
            a {
                color: #3182ce;
                text-decoration: none;
                transition: color 0.2s ease;
            }
            
            a:hover {
                color: #2c5282;
                text-decoration: underline;
            }
            
            /* Error Messages */
            .stAlert {
                border-radius: 8px !important;
                border: none !important;
            }
        </style>
        """, unsafe_allow_html=True)
        
        # Initialize session state for message deduplication
        if "messages" not in st.session_state:
            st.session_state.messages = []

        st.session_state.api_keys = {
            'Gemimi': "",
            'Claude': "",
            'ChatGPT': ""
        }

        # Sidebar settings
        with st.sidebar:

                
            st.title("הגדרות")
            
            st.subheader("הגדרת מפתחות API")
            
            # API Key inputs with improved styling
            for provider, label in [
                ('Gemimi', 'Google API Key'),
                ('ChatGPT', 'OpenAI API Key'),
                ('Claude', 'Anthropic API Key')
            ]:
                key = st.text_input(
                    label,
                    value=st.session_state.api_keys[provider],
                    type="password",
                    key=f"{provider}_key",
                    help=f"הזן את מפתח ה-API של {label}"
                )
                st.session_state.api_keys[provider] = key
                
                # Provider-specific links
                links = {
                    'Gemimi': 'https://aistudio.google.com/app/apikey',
                    'ChatGPT': 'https://platform.openai.com/account/api-keys',
                    'Claude': 'https://console.anthropic.com/'
                }
                st.html(f'<small> ניתן להשיג מפתח <a href="{links[provider]}">כאן</a> </small>')

            st.markdown("---")

        # Initialize system
        success, status_msg, available_providers = self.initialize_system(st.session_state.api_keys)

        if not success:
            st.error(status_msg)
            return
        
        import agent
        agent = self.get_agent(st.session_state.api_keys)

        # Provider selection in sidebar
        with st.sidebar:

            if st.button("צ'אט חדש"):
                st.session_state.messages = []
                agent.clear_chat()
          
            if 'provider' not in st.session_state or st.session_state.provider not in available_providers:
                    st.session_state.provider = available_providers[0] 
                
            provider = st.selectbox(
                    "ספק בינה מלאכותית",
                    options=available_providers,
                    key='provider',
                    help="בחר את מודל הAI לשימוש (רק מודלים עם מפתח API זמין יוצגו)"
                )
            if agent:
                    agent.set_llm(provider)



        # Main chat interface
        
        query = st.chat_input("הזן שאלה", key="chat_input")        
        if query:
           stream = agent.chat(query)
           for chunk in stream:
                st.session_state.messages = chunk["messages"]

           
        for message in st.session_state.messages: 
                if message.type == "tool":                            
                                    if message.name == "search":
                                        results =json.loads(message.content) if message.content else []
                                        with st.expander(f"🔍 תוצאות חיפוש: {len(results)}"):
                                            for result in results:
                                                st.write(result['reference'])
                                                st.info(result['text'])
                                    elif message.name == "get_text":
                                        st.expander(f"📝 טקסט: {message.content}")
                                    
                elif message.type == "ai" :
                    if message.content != "":
                      
                        with st.chat_message(message.type):
                            if isinstance(message.content, list):
                                for item in message.content:
                                    if ('text' in item):
                                        st.write(item['text'])                                

                            else:
                                st.write(message.content)
                                
                    for tool_call in message.tool_calls:
                        with st.expander(f"🛠️ שימוש בכלי: {tool_call['name']}"):
                            st.json(tool_call["args"])                                
                else: 
                    with st.chat_message(message.type):
                        st.write(message.content)  
           

if __name__ == "__main__":
    app = SearchAgentUI()
    app.main()