PocketSkye commited on
Commit
d2a762d
·
verified ·
1 Parent(s): 0c50bf1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -322
app.py CHANGED
@@ -12,332 +12,16 @@ from langchain.tools import Tool
12
  from langchain.tools import DuckDuckGoSearchRun
13
  from langchain_core.documents import Document
14
 
15
- apikey="BPOifMTr97adfPfi2NYrEhnUzMltdrCg"
 
 
 
 
 
16
 
17
- llm = ChatOpenAI(
18
- openai_api_key=apikey,
19
- openai_api_base="https://api.mistral.ai/v1",
20
- model="mistral-medium"
21
- )
22
-
23
- prompt_template = PromptTemplate(
24
- input_variables=["user_prompt"],
25
- template="""You are a retriever agent tasked with creating an efficient search small query to retrieve academic papers from arxiv relevant to a user’s request. Based on the user’s input prompt, generate a concise and precise search query (a string of keywords or phrases) that will be used by the function `retrieve_and_extract_papers(query: str, max_papers: int = 3) -> str` to fetch up to 3 relevant papers. The query should focus on key concepts, avoid ambiguity, and prioritize relevance to ensure the extracted text is suitable for summarization.
26
-
27
- User Input Prompt: {user_prompt}
28
-
29
- Instructions:
30
- 1. Identify the core concepts, topics, or questions in the user prompt.
31
- 2. Formulate a search query using relevant keywords or short phrases.
32
- 3. Exclude overly broad or irrelevant terms to improve precision.
33
- 4. Output only the search query as a string.
34
-
35
- Example:
36
- - User Prompt: "Recent advancements in large language models for natural language processing"
37
- - Search Query: "large language models NLP advancements"
38
-
39
- Generate the search query for the provided user prompt.
40
- """
41
- )
42
-
43
-
44
- search_tool = DuckDuckGoSearchRun()
45
- tools = [
46
- Tool(
47
- name="WebSearch",
48
- func=search_tool.run,
49
- description="Useful for fetching up-to-date healthcare information from the web.Use it rarely"
50
- ),
51
- ]
52
-
53
- retriever_agent = initialize_agent(
54
- tools=tools,
55
- agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
56
- llm=llm,
57
- verbose=True,
58
- prompt=prompt_template
59
- )
60
-
61
- import arxiv
62
- import pdfplumber
63
- import requests
64
- import os
65
- from typing import List
66
- embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
67
- def retrieve_and_extract_papers(query: str, max_papers: int = 3) -> str:
68
- """
69
- Retrieves research papers from arXiv, downloads PDFs, extracts text,
70
- and returns a single string with papers separated by '---pprN: Title'.
71
-
72
- Args:
73
- query: Search query (e.g., "diffusion models 2024")
74
- max_papers: Number of papers to retrieve (default: 3)
75
-
76
- Returns:
77
- Single string with extracted text from PDFs, separated by '---pprN: Title'
78
- """
79
- # Initialize arXiv client
80
- client = arxiv.Client()
81
- search = arxiv.Search(
82
- query=query,
83
- max_results=max_papers,
84
- sort_by=arxiv.SortCriterion.Relevance
85
- )
86
-
87
- papers = list(client.results(search))
88
- if not papers:
89
- return "No papers found for the query."
90
-
91
- # Create temporary directory for PDFs
92
- temp_dir = "temp_papers"
93
- os.makedirs(temp_dir, exist_ok=True)
94
-
95
- # Process each paper and collect extracted text
96
- formatted_texts = []
97
- for i, paper in enumerate(papers, 1):
98
- try:
99
- # Download PDF
100
- pdf_url = paper.pdf_url
101
- response = requests.get(pdf_url)
102
- pdf_path = os.path.join(temp_dir, f"paper_{i}.pdf")
103
-
104
- with open(pdf_path, 'wb') as f:
105
- f.write(response.content)
106
-
107
- # Extract text from PDF
108
- text = ""
109
- with pdfplumber.open(pdf_path) as pdf:
110
- for page in pdf.pages:
111
- page_text = page.extract_text()
112
- if page_text:
113
- text += page_text + "\n"
114
-
115
- # Append formatted text with separator including paper title
116
- separator = f"---ppr{i}: {paper.title}"
117
- formatted_texts.append(f"{separator}\n{text}")
118
-
119
- # Clean up: Remove the downloaded PDF
120
- os.remove(pdf_path)
121
-
122
- except Exception as e:
123
- print(f"Error processing paper {i} ({paper.title}): {e}")
124
- formatted_texts.append(f"---ppr{i}: {paper.title}\nError: Could not process paper.")
125
-
126
- # Clean up: Remove temporary directory if empty
127
- if os.path.exists(temp_dir) and not os.listdir(temp_dir):
128
- os.rmdir(temp_dir)
129
-
130
- # Join all texts into a single string
131
- return "\n".join(formatted_texts)
132
  # Initialize embedding model
133
  embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
134
 
135
-
136
- embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
137
- faiss_index = FAISS.load_local("faiss_index", embedding_model, allow_dangerous_deserialization=True)
138
- retriever = faiss_index.as_retriever(search_kwargs={"k": 3})
139
-
140
- llm = ChatOpenAI(
141
- openai_api_key=apikey,
142
- openai_api_base="https://api.mistral.ai/v1",
143
- model="mistral-medium"
144
- )
145
-
146
- from langchain.prompts import PromptTemplate
147
-
148
- prompt_template = PromptTemplate(
149
- input_variables=["user_prompt", "retriever_query"],
150
- template="""You are a summarizer agent tasked with generating a concise summary of academic papers retrieved from a RAG pipeline. Using the user’s prompt and the retriever query used for searching, fetch relevant document content with the RAG tool and summarize the key points, findings, or insights relevant to the user’s request.
151
-
152
- User Input Prompt: {user_prompt}
153
- Retriever Query: {retriever_query}
154
-
155
- Instructions:
156
- 1. Use the RAG tool to retrieve document content based on the retriever query.
157
- 2. Analyze the user prompt to identify the focus or specific aspects of interest.
158
- 3. Summarize the main ideas, results, or trends from the retrieved documents, excluding unnecessary details.
159
- 4. Ensure the summary is clear, coherent, and no longer than 1500 words.
160
- 5. If the RAG tool returns irrelevant or insufficient documents, note this briefly and provide a general response based on the prompt.
161
- 6. Output only the summary as a string.
162
-
163
- Example:
164
- - User Prompt: "Recent advancements in large language models for natural language processing"
165
- - Retriever Query: "large language models NLP advancements"
166
- - Summary: "Recent advancements in large language models (LLMs) focus on improved efficiency and performance in NLP tasks. Techniques like fine-tuning and transformer architectures enhance accuracy in text generation and understanding."
167
-
168
- Generate the summary for the provided user prompt and retriever query.
169
- """
170
- )
171
- search_tool = DuckDuckGoSearchRun()
172
-
173
- tools = [
174
- Tool(
175
- name="FAISSRetriever",
176
- func=lambda query: "\n\n".join([doc.page_content for doc in retriever.invoke(query)]),
177
- description="Fetches the top 3 relevant document chunks from a FAISS index containing academic paper content based on a query. Use for retrieving scholarly text for summarization."
178
- ),
179
- ]
180
- summarizer_agent = initialize_agent(
181
- tools=tools,
182
- agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
183
- llm=llm,
184
- verbose=True,
185
- prompt=prompt_template,
186
- retriever=retriever
187
- )
188
-
189
-
190
- llm = ChatOpenAI(
191
- openai_api_key=apikey,
192
- openai_api_base="https://api.mistral.ai/v1",
193
- model="mistral-large-2411"
194
- )
195
-
196
-
197
- embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
198
- faiss_index = FAISS.load_local("faiss_index", embedding_model, allow_dangerous_deserialization=True)
199
- retriever = faiss_index.as_retriever(search_kwargs={"k": 3})
200
-
201
- tools = [
202
- Tool(
203
- name="FAISSRetriever",
204
- func=lambda query: "\n\n".join([doc.page_content for doc in retriever.invoke(query)]),
205
- description="Fetches the top 3 relevant document chunks from a FAISS index containing academic paper content based on a query. Use for scholarly text analysis."
206
- ),
207
- Tool(
208
- name="WebSearch",
209
- func=DuckDuckGoSearchRun().run,
210
- description="Fetches up-to-date information from the web. Use for verifying claims or finding additional context."
211
- ),
212
- ]
213
-
214
-
215
- prompt_template = PromptTemplate(
216
- input_variables=["user_query", "summary"],
217
- template="""You are a critique agent tasked with strictly evaluating a summary of academic papers based on a user query. Using the provided user query and summary, analyze the content for accuracy, completeness, and biases. Use the FAISSRetriever and WebSearch tools to cross-reference information and validate claims. Provide a detailed critique, including recommendations, identified biases, and a relevance rating (1–5, where 5 is highly relevant and accurate).
218
-
219
- User Query: {user_query}
220
- Summary: {summary}
221
-
222
- Instructions:
223
- 1. Use the FAISSRetriever tool to fetch document chunks related to the user query for additional context from academic papers.
224
- 2. Use the WebSearch tool to verify claims in the summary or find recent developments.
225
- 3. Evaluate the summary for:
226
- - Accuracy: Are claims supported by evidence from the tools?
227
- - Completeness: Does it cover key aspects of the user query?
228
- - Biases: Identify methodological, dataset, author, or other biases (e.g., overemphasis on positive results, lack of diverse perspectives).
229
- 4. Provide recommendations to improve the summary (e.g., additional topics, clearer explanations).
230
- 5. Assign a relevance rating (1–5) based on how well the summary addresses the user query and its reliability.
231
- 6. Be strict in identifying biases and unsupported claims.
232
- 7. Output a structured response with sections: Critique, Recommendations, Biases, Relevance Rating.
233
-
234
- Example:
235
- - User Query: "Advancements in diffusion models for image generation"
236
- - Summary: "Diffusion models outperform GANs in image quality."
237
- - Output:
238
- Critique: The summary claims diffusion models outperform GANs but lacks evidence or metrics.
239
- Recommendations: Include specific metrics (e.g., FID scores) and compare computational costs.
240
- Biases: Potential bias toward diffusion models; ignores GANs’ strengths in training speed.
241
- Relevance Rating: 2/5 (lacks depth and evidence).
242
-
243
- Generate the critique for the provided user query and summary.
244
- """
245
- )
246
-
247
- critique_agent = initialize_agent(
248
- tools=tools,
249
- agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
250
- llm=llm,
251
- verbose=True,
252
- prompt=prompt_template,
253
- )
254
-
255
- llm = ChatOpenAI(
256
- openai_api_key=apikey,
257
- openai_api_base="https://api.mistral.ai/v1",
258
- model="mistral-large-2411"
259
- )
260
-
261
- from langchain.prompts import PromptTemplate
262
-
263
- prompt_template = PromptTemplate(
264
- input_variables=["user_prompt", "summaries", "critiques"],
265
- template="""You are a Synthesizer Agent assisting in generating a structured research overview for a given topic.
266
- You are provided with:
267
- 1. The user’s original prompt.
268
- 2. A set of summaries extracted from multiple research papers.
269
- 3. Critique analysis, including commentary on contradictions, outdated information, and biased claims, along with associated critique scores (from 1 to 5, where 5 is most critical).
270
-
271
- Your task is to:
272
- - Analyze the summaries to extract core findings and organize them into a clear, topic-wise outline.
273
- - Incorporate the critiques along with their scores in a dedicated section to highlight research limitations or cautionary notes.
274
-
275
- User Prompt:
276
- {user_prompt}
277
-
278
- Paper Summaries:
279
- {summaries}
280
-
281
- Critique Analysis (with scores):
282
- {critiques}
283
-
284
- Instructions:
285
- 1. Begin with a concise introduction to the research topic based on the user prompt.
286
- 2. Generate a structured outline capturing key themes, methodologies, findings, and notable contributions.
287
- 3. Follow up with a \"Critical Reflections\" section that includes:
288
- - A list of critical observations.
289
- - Their corresponding critique scores.
290
- - Any specific recommendations or warnings.
291
- 4. Maintain a professional and academic tone throughout.
292
- 5. The final response should be suitable for inclusion in a research literature review or academic discussion.
293
-
294
- Output Format:
295
- - **Introduction**
296
- - **Outline**
297
- - Theme 1: ...
298
- - Theme 2: ...
299
- - **Critical Reflections**
300
- - Observation 1 (Score: X): ...
301
- - Observation 2 (Score: X): ...
302
- - Outdated or Contradictory Claims (if any): ...
303
- - Recommendations: ...
304
-
305
- Now generate the structured synthesis below:
306
- """
307
- )
308
-
309
- search_tool = DuckDuckGoSearchRun()
310
-
311
- tools = [
312
- Tool(
313
- name="WebSearch",
314
- func=DuckDuckGoSearchRun().run,
315
- description="Fetches up-to-date information from the web. Use for verifying claims or finding additional context."
316
- ),
317
- ]
318
-
319
- synthesizer_agent = initialize_agent(
320
- tools=tools,
321
- agent_type=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
322
- llm=llm,
323
- verbose=True,
324
- prompt=prompt_template
325
- )
326
-
327
-
328
-
329
-
330
-
331
-
332
-
333
-
334
-
335
-
336
-
337
-
338
-
339
-
340
-
341
  # Define prompt templates
342
  retriever_template = PromptTemplate(
343
  input_variables=["user_prompt"],
 
12
  from langchain.tools import DuckDuckGoSearchRun
13
  from langchain_core.documents import Document
14
 
15
+ # Import agents and functions
16
+ from retriever import retriever_agent
17
+ from retriever import retrieve_and_extract_papers
18
+ from summarizer import summarizer_agent
19
+ from critique import critique_agent
20
+ from synthesizer import synthesizer_agent
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # Initialize embedding model
23
  embedding_model = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # Define prompt templates
26
  retriever_template = PromptTemplate(
27
  input_variables=["user_prompt"],