Subhadip866 commited on
Commit
7f520db
·
verified ·
1 Parent(s): bc22452

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +295 -0
app.py CHANGED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from kognieLlama import Kognie
2
+ import os
3
+ from dotenv import load_dotenv
4
+ import datetime
5
+
6
+ import asyncio
7
+ from functools import partial
8
+
9
+ from llama_index.core.agent.workflow import FunctionAgent
10
+ from llama_index.legacy.llms.types import ChatMessage
11
+ from llama_index.tools.bing_search import BingSearchToolSpec
12
+ from llama_index.llms.openai import OpenAI
13
+ from llama_index.llms.anthropic import Anthropic
14
+ import gradio as gr
15
+ import time
16
+ import base64
17
+
18
+ # Convert image to base64
19
+ with open("drop-down.png", "rb") as f:
20
+ base64_img = base64.b64encode(f.read()).decode("utf-8")
21
+
22
+ load_dotenv()
23
+
24
+ KOGNIE_BASE_URL = os.getenv("KOGNIE_BASE_URL")
25
+ KOGNIE_API_KEY = os.getenv("KOGNIE_API_KEY")
26
+ BING_SUBSCRIPTION_KEY = os.getenv('BING_SUBSCRIPTION_KEY')
27
+ BING_SEARCH_URL = os.getenv('BING_SEARCH_URL')
28
+ ANTHROPIC_API_KEY = os.getenv('ANTHROPIC_API_KEY')
29
+ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
30
+
31
+
32
+
33
+ async def async_llm_call(model, messages):
34
+ """Wraps the synchronous chat method in a thread to make it non-blocking"""
35
+ loop = asyncio.get_running_loop()
36
+ chat_func = partial(model.chat, messages=messages)
37
+ try:
38
+ result = await loop.run_in_executor(None, chat_func)
39
+ return result
40
+ except Exception as e:
41
+ print(f"Error occurred while invoking {model.model}: {e}")
42
+ return None
43
+
44
+ async def multillm_verifier_tool(claim: str) -> str:
45
+ """
46
+ An async tool that runs multiple LLMs to check/verify the claim in parallel.
47
+ """
48
+ gpt = Kognie(
49
+ api_key=KOGNIE_API_KEY,
50
+ model="gpt-4o-mini"
51
+ )
52
+ gemini = Kognie(
53
+ api_key=KOGNIE_API_KEY,
54
+ model='gemini-2.0-flash'
55
+ )
56
+ mistral = Kognie(
57
+ api_key=KOGNIE_API_KEY,
58
+ model='open-mistral-nemo'
59
+ )
60
+
61
+ prompt = f"""you are a helpful assistant. Your task is to provide evidence for the claim to the extent there is any such evidence and provide evidence against the claim to the extent there is any such evidence. Under no circumstances fabricate evidence. You must list out all the evidence you can find.
62
+ Claim: {claim}
63
+ Evidences:
64
+ """
65
+
66
+ messages = [ChatMessage(role="system", content=prompt), ChatMessage(role="user", content=claim)]
67
+
68
+ tasks = [
69
+ async_llm_call(gpt, messages),
70
+ async_llm_call(gemini, messages),
71
+ async_llm_call(mistral, messages)
72
+ ]
73
+
74
+ results = await asyncio.gather(*tasks)
75
+ print("multillm done")
76
+ return {
77
+ "gpt-4": results[0],
78
+ "gemini-2.0-flash": results[1],
79
+ "open-mistral-nemo": results[2]
80
+ }
81
+
82
+
83
+ def web_evidence_retriever_tool(claim: str) -> str:
84
+ """
85
+ A tool that retrieves relevant evidence from the web to support or refute a claim.
86
+ Uses Bing Search API to gather information, then analyzes it to provide evidence.
87
+ """
88
+ # Step 1: Generate search queries based on the claim
89
+ search_query = f"{claim} evidence facts verification"
90
+
91
+ # Step 2: Retrieve search results
92
+ search = BingSearchToolSpec(
93
+ api_key=BING_SUBSCRIPTION_KEY,
94
+ results=5,
95
+ )
96
+ search_results = search.bing_news_search(search_query) # Get more results for better coverage
97
+ print("web done")
98
+ # Return the structured analysis
99
+ return search_results
100
+
101
+
102
+
103
+
104
+ multiLLMVerifier = FunctionAgent(
105
+ tools=[multillm_verifier_tool],
106
+ llm=Anthropic(model="claude-3-5-sonnet-20240620", api_key=ANTHROPIC_API_KEY),
107
+ system_prompt=f"you are a helpful assistant. Your task is to provide evidence for the claim to the extent there is any such evidence and provide evidence against the claim to the extent there is any such evidence. Under no circumstances fabricate evidence. You must list out all the evidence you can find.",
108
+ )
109
+
110
+ webEvidenceRetriever = FunctionAgent(
111
+ tools=[web_evidence_retriever_tool],
112
+ llm=Anthropic(model="claude-3-5-sonnet-20240620", api_key=ANTHROPIC_API_KEY),
113
+ system_prompt=f"you are a helpful assistant. Your task is to provide evidence for the claim to the extent there is any such evidence and provide evidence against the claim to the extent there is any such evidence. Under no circumstances fabricate evidence. You must list out all the evidence you can find.. Today's date is: {datetime.datetime.now().strftime('%Y-%m-%d')}",
114
+ )
115
+
116
+ AgentResponses = {}
117
+
118
+ async def multiagent_tool_run(user_input: str):
119
+ """
120
+ This function runs multiple agents to verify a claim using different tools.
121
+ Each agent will provide its own analysis, and the coordinator will make a final decision.
122
+ """
123
+ # Run agents concurrently
124
+ responses = {}
125
+ tasks = [
126
+ multiLLMVerifier.run(user_input),
127
+ webEvidenceRetriever.run(user_input)
128
+ ]
129
+
130
+ start_time = time.time()
131
+
132
+ results = await asyncio.gather(*tasks)
133
+
134
+ end_time = time.time()
135
+ elapsed_time = end_time - start_time
136
+ print(f"Elapsed time for multi-agent run: {elapsed_time} seconds")
137
+
138
+ responses["MultiLLMVerifier"] = results[0]
139
+ responses["WebEvidenceRetriever"] = results[1]
140
+
141
+ # print("\n===========Responses from MultiLLMVerifier:================\n", responses["MultiLLMVerifier"])
142
+ # print("\n===========Responses from WebEvidenceRetriever:================\n", responses["WebEvidenceRetriever"])
143
+
144
+ try:
145
+ print("Responses from all agents received.", responses)
146
+ AgentResponses['GPT'] = responses['MultiLLMVerifier']
147
+ AgentResponses['Web Research'] = responses['WebEvidenceRetriever']
148
+ # AgentResponses['GPT'] = results[0].blocks[0].text
149
+ # AgentResponses['Web Research'] = results[1].blocks[0].text
150
+ except Exception as e:
151
+ print(f"Error processing agent responses: {e}")
152
+ AgentResponses['GPT'] = "No response from GPT"
153
+ AgentResponses['Web Research'] = "No response from Web Research"
154
+
155
+
156
+ return {
157
+ "individual_responses": responses,
158
+ }
159
+
160
+
161
+
162
+
163
+ BossAgent = FunctionAgent(
164
+ tools=[multiagent_tool_run],
165
+ return_intermediate_steps=True,
166
+ llm=OpenAI(
167
+ api_key=OPENAI_API_KEY,
168
+ model="gpt-4.1"
169
+ ),
170
+ system_prompt=f"You are a coordinator that runs multiple agents to verify claims using different tools. You are the final decision maker.Your decision must be based on the evidence presented by the different agents. Please generate a very short decision in html format. The main decision should come at the top in bold and larger fonts and color green if TRUE or red is FALSE and followed by some small reasoning and evidence. Give priority to the Web agent if it conflicts with the other agents as it has the latest information. Today's date is : {datetime.datetime.now().strftime('%Y-%m-%d')}",
171
+ )
172
+
173
+ async def main(claim: str):
174
+
175
+ # Run the agent
176
+ print(f"Running claim verification for: {claim}")
177
+ response = await BossAgent.run(claim)
178
+ print(str(response))
179
+ return str(response)
180
+
181
+
182
+
183
+ async def verify_claim(message: str, history):
184
+ """
185
+ Use this tool to verify a claim
186
+ """
187
+
188
+ print(f"Received message: {message}")
189
+
190
+ # Start running the main task in background
191
+ task = asyncio.create_task(main(message))
192
+
193
+ response = await task
194
+ yield [gr.ChatMessage(role="assistant",
195
+ content=gr.HTML(str(response)),
196
+ ), gr.ChatMessage(
197
+ role="assistant",
198
+ content=gr.HTML(
199
+ f"""
200
+ <style>
201
+ .collapsible {{
202
+ display: flex;
203
+ align-items: center;
204
+ justify-content: flex-start;
205
+ background-color: #3498db;
206
+ color: white;
207
+ cursor: pointer;
208
+ padding: 15px;
209
+ width: 100%;
210
+ border: none;
211
+ text-align: left;
212
+ outline: none;
213
+ font-size: 14px !important;
214
+ border-radius: 5px;
215
+ }}
216
+
217
+ .arrow {{
218
+ transition: transform 0.3s ease;
219
+ filter: invert(1);
220
+ margin: 0 !important;
221
+ margin-left: 5px !important;
222
+ }}
223
+
224
+ .collapsible.active .arrow {{
225
+ transform: rotate(180deg);
226
+ }}
227
+
228
+ .content {{
229
+ padding: 0 15px;
230
+ max-height: 0;
231
+ overflow: hidden;
232
+ transition: max-height 0.3s ease-out;
233
+ background-color: transparent;
234
+ border-radius: 0 0 5px 5px;
235
+ }}
236
+ </style>
237
+ <button class="collapsible" onclick="this.classList.toggle('active');
238
+ const content = this.nextElementSibling;
239
+ if (content.style.maxHeight){{
240
+ content.style.maxHeight = null;
241
+ }} else {{
242
+ content.style.maxHeight = content.scrollHeight + 'px';
243
+ }}">Show analysis<img src="data:image/png;base64,{base64_img}" class="arrow"></button>
244
+ <div class="content">
245
+ {f'<p style="font-size: 16px;">Generation Specialist : <span style="font-size: 14px;">{AgentResponses["GPT"]}</span></p>' if 'GPT' in AgentResponses and AgentResponses['GPT'] else ''}
246
+
247
+ {f'<p style="font-size: 16px;">Web Research : <span style="font-size: 14px;">{AgentResponses["Web Research"]}</span></p>' if 'Web Research' in AgentResponses and AgentResponses['Web Research'] else ''}
248
+ </div>
249
+ """
250
+ ),
251
+ )
252
+ ]
253
+
254
+
255
+
256
+
257
+
258
+ # chatbot = gr.Chatbot(history, type="messages")
259
+
260
+ demo = gr.ChatInterface(
261
+ verify_claim,
262
+ type="messages",
263
+ flagging_mode="never",
264
+ save_history=True,
265
+ show_progress="full",
266
+ title="Claim Verification System using Kognie API",
267
+ textbox=gr.Textbox(
268
+ placeholder="Enter a claim to verify",
269
+ show_label=False,
270
+ elem_classes=["claim-input"],
271
+ submit_btn=True
272
+ ),
273
+ css = '''
274
+ .claim-input {
275
+ border-width: 2px !important;
276
+ border-style: solid !important;
277
+ border-color: #EA580C !important;
278
+ border-radius: 5px;
279
+ font-size: 16px;
280
+ }
281
+
282
+ '''
283
+
284
+ )
285
+
286
+ # Launch the interface
287
+ if __name__ == "__main__":
288
+ # Remove or comment out the existing test run
289
+ # result = final_run("RCB are the 2025 IPL winners.")
290
+ # print("Final Decision:\n", result['output'])
291
+
292
+ # Launch Gradio interface
293
+ demo.launch( # Default Gradio port
294
+ mcp_server=True # Enable debug mode
295
+ )