Sarath0x8f commited on
Commit
da94819
Β·
verified Β·
1 Parent(s): 8f1cfb9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +303 -135
app.py CHANGED
@@ -1,135 +1,303 @@
1
- import gradio as gr
2
- import pymongo
3
- import certifi
4
- from llama_index.core import VectorStoreIndex
5
- from llama_index.embeddings.huggingface import HuggingFaceEmbedding
6
- from llama_index.llms.groq import Groq
7
- from llama_index.vector_stores.mongodb import MongoDBAtlasVectorSearch
8
- from llama_index.core.prompts import PromptTemplate
9
- from dotenv import load_dotenv
10
- import os
11
- import base64
12
- import markdown as md
13
-
14
- # Load environment variables
15
- load_dotenv()
16
-
17
- # --- MongoDB Config ---
18
- # ATLAS_CONNECTION_STRING = "mongodb+srv://sarath:[email protected]/?retryWrites=true&w=majority&appName=Itihasa"
19
- ATLAS_CONNECTION_STRING = os.getenv("ATLAS_CONNECTION_STRING")
20
- DB_NAME = "RAG"
21
- COLLECTION_NAME = "ramayana"
22
- VECTOR_INDEX_NAME = "ramayana_vector_index"
23
-
24
- # --- Embedding Model ---
25
- embed_model = HuggingFaceEmbedding(model_name="intfloat/multilingual-e5-base")
26
-
27
- # --- Prompt Template ---
28
- ramayana_qa_template = PromptTemplate(
29
- """You are an expert on the Valmiki Ramayana and a guide who always inspires people with the great Itihasa like the Ramayana.
30
-
31
- Below is text from the epic, including shlokas and their explanations:
32
- ---------------------
33
- {context_str}
34
- ---------------------
35
-
36
- Using only this information, answer the following query.
37
-
38
- Query: {query_str}
39
-
40
- Answer:
41
- - Intro or general description to ```Query```
42
- - Related shloka/shlokas followed by its explanation
43
- - Overview of ```Query```
44
- """
45
- )
46
-
47
- # --- Connect to MongoDB once at startup ---
48
- def get_vector_index_once():
49
- mongo_client = pymongo.MongoClient(
50
- ATLAS_CONNECTION_STRING,
51
- tlsCAFile=certifi.where(),
52
- tlsAllowInvalidCertificates=False,
53
- connectTimeoutMS=30000,
54
- serverSelectionTimeoutMS=30000,
55
- )
56
- mongo_client.server_info()
57
- print("βœ… Connected to MongoDB Atlas.")
58
-
59
- vector_store = MongoDBAtlasVectorSearch(
60
- mongo_client,
61
- db_name=DB_NAME,
62
- collection_name=COLLECTION_NAME,
63
- vector_index_name=VECTOR_INDEX_NAME,
64
- )
65
- return VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model)
66
-
67
- # Connect once
68
- vector_index = get_vector_index_once()
69
-
70
- # --- Respond Function (uses API key from state) ---
71
- def chat_with_groq(message, history, groq_key):
72
- llm = Groq(model="llama-3.1-8b-instant", api_key=groq_key)
73
-
74
- query_engine = vector_index.as_query_engine(
75
- llm=llm,
76
- text_qa_template=ramayana_qa_template,
77
- similarity_top_k=5,
78
- verbose=True,
79
- )
80
-
81
- response = query_engine.query(message)
82
- return str(response)
83
-
84
- def encode_image(image_path):
85
- with open(image_path, "rb") as image_file:
86
- return base64.b64encode(image_file.read()).decode('utf-8')
87
-
88
- # Encode the images
89
- github_logo_encoded = encode_image("Images/github-logo.png")
90
- linkedin_logo_encoded = encode_image("Images/linkedin-logo.png")
91
- website_logo_encoded = encode_image("Images/ai-logo.png")
92
-
93
- # --- Gradio UI ---
94
- with gr.Blocks(theme=gr.themes.Soft(font=[gr.themes.GoogleFont("Roboto Mono")]), css='footer {visibility: hidden}') as demo:
95
- with gr.Tabs():
96
- with gr.TabItem("Intro"):
97
- gr.Markdown(md.description)
98
-
99
- with gr.TabItem("GPT"):
100
- with gr.Column(visible=True) as accordion_container:
101
- with gr.Accordion("How to get Groq API KEY", open=False):
102
- gr.Markdown(md.groq_api_key)
103
-
104
- groq_key_box = gr.Textbox(
105
- label="Enter Groq API Key",
106
- type="password",
107
- placeholder="Paste your Groq API key here..."
108
- )
109
-
110
- start_btn = gr.Button("Start Chat")
111
-
112
- groq_state = gr.State(value="")
113
-
114
- # Chat container, initially hidden
115
- with gr.Column(visible=False) as chatbot_container:
116
- chatbot = gr.ChatInterface(
117
- fn=lambda message, history, groq_key: chat_with_groq(message, history, groq_key),
118
- additional_inputs=[groq_state],
119
- title="πŸ•‰οΈ RamayanaGPT",
120
- # description="Ask questions from the Valmiki Ramayana. Powered by RAG + MongoDB + LlamaIndex.",
121
- )
122
-
123
- # Show chat and hide inputs
124
- def save_key_and_show_chat(key):
125
- return key, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
126
-
127
- start_btn.click(
128
- fn=save_key_and_show_chat,
129
- inputs=[groq_key_box],
130
- outputs=[groq_state, groq_key_box, start_btn, accordion_container, chatbot_container]
131
- )
132
- gr.HTML(md.footer.format(github_logo_encoded, linkedin_logo_encoded, website_logo_encoded))
133
-
134
- if __name__ == "__main__":
135
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import markdown as md
3
+ import yaml
4
+ from Agents.ContentGeneratorAgent import run_crew_cga, set_model, llm_models
5
+ from Agents.GameBuilderAgent import run_crew_game
6
+ from Agents.MarketingPostGeneratorAgent import run_crew_mpga
7
+ from Agents.TripPlannerAgent import run_crew_tp
8
+ from Agents.AIAgentDevAgent import run_crew_aida # Import the AI Agent Dev Agent crew function
9
+ import base64
10
+
11
+ def toggle_serper_input(choice):
12
+ return gr.Textbox(visible=(choice == "Yes"))
13
+
14
+ def update_game_instructions(example_key):
15
+ # Load the game design examples from the YAML file
16
+ with open('gamedesign.yaml', 'r', encoding='utf-8') as f:
17
+ examples = yaml.safe_load(f)
18
+ return examples.get(example_key, "")
19
+
20
+ def encode_image(image_path):
21
+ with open(image_path, "rb") as image_file:
22
+ return base64.b64encode(image_file.read()).decode('utf-8')
23
+
24
+ # Encode the images
25
+ github_logo_encoded = encode_image("Images/github-logo.png")
26
+ linkedin_logo_encoded = encode_image("Images/linkedin-logo.png")
27
+ website_logo_encoded = encode_image("Images/ai-logo.png")
28
+
29
+ # UI Setup
30
+ with gr.Blocks(theme=gr.themes.Soft(font=[gr.themes.GoogleFont("Roboto Mono")]),
31
+ css='footer {visibility: hidden}') as demo:
32
+ gr.Markdown("# AI Agent Nexus πŸ€–πŸ•΅πŸ»")
33
+
34
+ with gr.Tabs():
35
+ with gr.TabItem("Intro"):
36
+ gr.Markdown(md.description)
37
+
38
+ # Tab for SEO Content Generator Agent
39
+ with gr.TabItem("SEO Content Agent"):
40
+ with gr.Accordion("πŸ“” Description:", open=False):
41
+ gr.Markdown(md.seo_content)
42
+ with gr.Accordion("How to get GEMINI API KEY", open=False):
43
+ gr.Markdown(md.gemini_api_key)
44
+ with gr.Accordion("How to get SERPER API KEY", open=False):
45
+ gr.Markdown(md.serper_api_key)
46
+ with gr.Row():
47
+ with gr.Column(scale=1):
48
+ model_dropdown = gr.Dropdown(
49
+ llm_models,
50
+ label="1. Select AI Model",
51
+ value=llm_models[0]
52
+ )
53
+ gemini_key = gr.Textbox(
54
+ label="2. Enter Gemini API Key",
55
+ type="password",
56
+ placeholder="Paste your Gemini API key here..."
57
+ )
58
+ search_toggle = gr.Radio(
59
+ ["Yes", "No"],
60
+ label="3. Enable Online Search?",
61
+ value="No"
62
+ )
63
+ serper_key = gr.Textbox(
64
+ label="4. Enter Serper API Key",
65
+ type="password",
66
+ visible=False,
67
+ placeholder="Paste your Serper API key if enabled..."
68
+ )
69
+ topic_input = gr.Textbox(
70
+ label="5. Enter Content Topic",
71
+ placeholder="Enter your article topic here..."
72
+ )
73
+ run_btn = gr.Button("Generate Content", variant="primary")
74
+ with gr.Column(scale=3):
75
+ output = gr.Markdown(
76
+ label="Generated Content",
77
+ value="Your content will appear here..."
78
+ )
79
+ with gr.Accordion("Process Logs", open=True):
80
+ logs = gr.Markdown()
81
+
82
+ # Event handlers for SEO Content Generator
83
+ model_dropdown.change(set_model, model_dropdown)
84
+ search_toggle.change(
85
+ toggle_serper_input,
86
+ inputs=search_toggle,
87
+ outputs=serper_key
88
+ )
89
+ run_btn.click(
90
+ run_crew_cga,
91
+ inputs=[gemini_key, search_toggle, serper_key, topic_input],
92
+ outputs=[output, logs],
93
+ show_progress="full"
94
+ )
95
+
96
+ # Tab for Game Dev Agent
97
+ with gr.TabItem("Game Dev Agent"):
98
+ with gr.Accordion('πŸ“” Description:', open=False):
99
+ gr.Markdown(md.game_dev)
100
+ with gr.Accordion("How to get GEMINI API KEY", open=False):
101
+ gr.Markdown(md.gemini_api_key)
102
+ with gr.Row():
103
+ with gr.Column(scale=1):
104
+ game_model_dropdown = gr.Dropdown(
105
+ llm_models,
106
+ label="1. Select AI Model",
107
+ value=llm_models[0]
108
+ )
109
+ game_gemini_key = gr.Textbox(
110
+ label="2. Enter Gemini API Key",
111
+ type="password",
112
+ placeholder="Paste your Gemini API key here..."
113
+ )
114
+ game_example_dropdown = gr.Dropdown(
115
+ choices=["pacman", "pacman2", "snake", "space_invaders", "Tetris", "Frogger", "Chess", "Go", "Reversi"],
116
+ label="3. Select Example",
117
+ value="pacman"
118
+ )
119
+ game_load_example_btn = gr.Button("Load Example", variant="secondary")
120
+ game_instructions = gr.Textbox(
121
+ label="4. Enter Game Design Instructions",
122
+ placeholder="Enter your game design instructions here...",
123
+ lines=5
124
+ )
125
+ game_run_btn = gr.Button("Generate Game Code", variant="primary")
126
+ with gr.Column(scale=3):
127
+ game_output = gr.Markdown(
128
+ label="Generated Game Code",
129
+ value="Your game code will appear here..."
130
+ )
131
+ with gr.Accordion("Process Logs", open=False):
132
+ game_logs = gr.Markdown()
133
+
134
+ # Event handlers for Game Dev Agent
135
+ game_model_dropdown.change(set_model, game_model_dropdown)
136
+ game_load_example_btn.click(
137
+ update_game_instructions,
138
+ inputs=[game_example_dropdown],
139
+ outputs=[game_instructions]
140
+ )
141
+ game_run_btn.click(
142
+ run_crew_game,
143
+ inputs=[game_gemini_key, game_instructions],
144
+ outputs=[game_output, game_logs],
145
+ show_progress="full"
146
+ )
147
+
148
+ # Tab for Marketing Posts Generator Agent
149
+ with gr.TabItem("Marketing Posts Generator Agent"):
150
+ with gr.Accordion("πŸ“” Description: ", open=False):
151
+ gr.Markdown(md.marking_post_gen_agent)
152
+ with gr.Accordion("How to get GEMINI API KEY", open=False):
153
+ gr.Markdown(md.gemini_api_key)
154
+ with gr.Accordion("How to get SERPER API KEY", open=False):
155
+ gr.Markdown(md.serper_api_key)
156
+ with gr.Row():
157
+ with gr.Column(scale=1):
158
+ mpga_model_dropdown = gr.Dropdown(
159
+ llm_models,
160
+ label="1. Select AI Model",
161
+ value=llm_models[0]
162
+ )
163
+ mpga_gemini_key = gr.Textbox(
164
+ label="2. Enter Gemini API Key",
165
+ type="password",
166
+ placeholder="Paste your Gemini API key here..."
167
+ )
168
+ mpga_serper_key = gr.Textbox(
169
+ label="3. Enter Serper API Key",
170
+ type="password",
171
+ placeholder="Paste your Serper API key here..."
172
+ )
173
+ customer_domain = gr.Textbox(
174
+ label="4. Enter Customer Domain",
175
+ placeholder="Enter the customer domain here..."
176
+ )
177
+ project_description = gr.Textbox(
178
+ label="5. Enter Project Description",
179
+ placeholder="Enter the project description here..."
180
+ )
181
+ mpga_run_btn = gr.Button("Generate Marketing Posts", variant="primary")
182
+ with gr.Column(scale=3):
183
+ mpga_output = gr.Markdown(
184
+ label="Generated Marketing Posts",
185
+ value="Your marketing posts will appear here..."
186
+ )
187
+ with gr.Accordion("Process Logs", open=False):
188
+ mpga_logs = gr.Markdown()
189
+
190
+ # Event handlers for Marketing Posts Generator Agent
191
+ mpga_model_dropdown.change(set_model, mpga_model_dropdown)
192
+ mpga_run_btn.click(
193
+ run_crew_mpga,
194
+ inputs=[mpga_gemini_key, customer_domain, project_description],
195
+ outputs=[mpga_output, mpga_logs],
196
+ show_progress="full"
197
+ )
198
+
199
+ # Tab for Trip Planner Agent
200
+ with gr.TabItem("Trip Planner Agent"):
201
+ with gr.Accordion("πŸ“” Description: ", open=False):
202
+ gr.Markdown(md.trip_planner_agent)
203
+ with gr.Accordion("How to get GEMINI API KEY", open=False):
204
+ gr.Markdown(md.gemini_api_key)
205
+ with gr.Row():
206
+ with gr.Column(scale=1):
207
+ tp_model_dropdown = gr.Dropdown(
208
+ llm_models,
209
+ label="1. Select AI Model",
210
+ value=llm_models[0]
211
+ )
212
+ tp_gemini_key = gr.Textbox(
213
+ label="2. Enter Gemini API Key",
214
+ type="password",
215
+ placeholder="Paste your Gemini API key here..."
216
+ )
217
+ origin_input = gr.Textbox(
218
+ label="3. Enter Origin (Your Starting Location)",
219
+ placeholder="Enter your origin city..."
220
+ )
221
+ cities_input = gr.Textbox(
222
+ label="4. Enter City Options",
223
+ placeholder="List the cities you're interested in visiting..."
224
+ )
225
+ trip_date_input = gr.Textbox(
226
+ label="5. Enter Trip Date",
227
+ placeholder="Enter your trip date (e.g., YYYY-MM-DD to YYYY-MM-DD)..."
228
+ )
229
+ interests_input = gr.Textbox(
230
+ label="6. Enter Traveler Interests",
231
+ placeholder="Enter your interests/hobbies..."
232
+ )
233
+ tp_run_btn = gr.Button("Generate Trip Plan", variant="primary")
234
+ with gr.Column(scale=3):
235
+ tp_output = gr.Markdown(
236
+ label="Trip Plan",
237
+ value="Your trip plan will appear here..."
238
+ )
239
+ with gr.Accordion("Process Logs", open=True):
240
+ tp_logs = gr.Markdown()
241
+
242
+ # Event handlers for Trip Planner Agent
243
+ tp_model_dropdown.change(set_model, tp_model_dropdown)
244
+ tp_run_btn.click(
245
+ run_crew_tp,
246
+ inputs=[tp_gemini_key, origin_input, cities_input, trip_date_input, interests_input],
247
+ outputs=[tp_output, tp_logs],
248
+ show_progress="full"
249
+ )
250
+
251
+ # Tab for AI Agent Dev Agent
252
+ with gr.TabItem("AI Agent Dev Agent"):
253
+ with gr.Accordion("πŸ“” Description: ", open=False):
254
+ gr.Markdown(md.ai_agent_dev_agent if hasattr(md, 'ai_agent_dev_agent') else
255
+ "This agent helps in creating new AI agents based on your query. It analyzes your requirements, designs a high-level architecture, identifies necessary agent roles and tasks, maps required tools, constructs the code, validates integration, and provides a final review and deployment plan.")
256
+ with gr.Accordion("How to get GEMINI API KEY", open=False):
257
+ gr.Markdown(md.gemini_api_key)
258
+ with gr.Accordion("How to get SERPER API KEY", open=False):
259
+ gr.Markdown(md.serper_api_key)
260
+ with gr.Row():
261
+ with gr.Column(scale=1):
262
+ aida_model_dropdown = gr.Dropdown(
263
+ llm_models,
264
+ label="1. Select AI Model",
265
+ value=llm_models[0]
266
+ )
267
+ aida_gemini_key = gr.Textbox(
268
+ label="2. Enter Gemini API Key",
269
+ type="password",
270
+ placeholder="Paste your Gemini API key here..."
271
+ )
272
+ aida_serper_key = gr.Textbox(
273
+ label="3. Enter Serper API Key",
274
+ type="password",
275
+ placeholder="Paste your Serper API key here..."
276
+ )
277
+ aida_agent_query = gr.Textbox(
278
+ label="4. Enter Agent Query",
279
+ placeholder="Describe the AI agent you want to create...",
280
+ lines=5
281
+ )
282
+ aida_run_btn = gr.Button("Generate AI Agent Blueprint", variant="primary")
283
+ with gr.Column(scale=3):
284
+ aida_output = gr.Markdown(
285
+ label="Generated AI Agent Blueprint",
286
+ value="Your AI agent blueprint will appear here..."
287
+ )
288
+ with gr.Accordion("Process Logs", open=True):
289
+ aida_logs = gr.Markdown()
290
+
291
+ # Event handlers for AI Agent Dev Agent
292
+ aida_model_dropdown.change(set_model, aida_model_dropdown)
293
+ aida_run_btn.click(
294
+ run_crew_aida,
295
+ inputs=[aida_gemini_key, aida_serper_key, aida_agent_query],
296
+ outputs=[aida_output, aida_logs],
297
+ show_progress="full"
298
+ )
299
+
300
+ gr.HTML(md.footer.format(github_logo_encoded, linkedin_logo_encoded, website_logo_encoded))
301
+
302
+ if __name__ == "__main__":
303
+ demo.launch()