GOKULSINGHSHAH123 commited on
Commit
9df681f
·
verified ·
1 Parent(s): fc22f3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -63
app.py CHANGED
@@ -4,6 +4,17 @@ import operator
4
  from langgraph.checkpoint.sqlite import SqliteSaver
5
  from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, AIMessage, ChatMessage
6
  from langchain_google_genai import ChatGoogleGenerativeAI
 
 
 
 
 
 
 
 
 
 
 
7
  memory = SqliteSaver.from_conn_string(":memory:")
8
 
9
  class AgentState(TypedDict):
@@ -16,192 +27,156 @@ class AgentState(TypedDict):
16
  max_revisions: int
17
 
18
  from langchain_openai import ChatOpenAI
19
- model = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key="AIzaSyAxaNMQlai9ybEiAVlSIOaY-pRivTMuR54", convert_system_message_to_human=True, temperature=0.6)
20
-
 
 
21
  PLAN_PROMPT = """You are an experienced writer tasked with drafting a highly detailed and comprehensive outline for a research report. Your goal is to create an exceptionally structured outline for the user's chosen topic, ensuring it encourages an in-depth examination of recent trends, specific advancements, technical details, and future research directions.
22
-
23
  **Outline Requirements:**
24
  1. **Executive Summary:**
25
  - Summarize key findings, significance, and implications.
26
  - Highlight main conclusions and recommendations.
27
-
28
  2. **Introduction:**
29
  - Provide background on the topic.
30
  - State research questions or hypotheses.
31
  - Define the scope and objectives of the report.
32
-
33
  3. **Recent Trends and Advancements:**
34
  -give resposne according to users topic
35
-
36
  4. **Integration of Technologies:**
37
  - Discuss how these technologies intersect and enhance each other.
38
  - Provide examples of synergistic effects and combined applications.
39
  - Address integration challenges and potential solutions.
40
-
41
  5. **Privacy and Security Challenges:**
42
  - Identify key privacy and security issues.
43
  - Discuss mitigation strategies and best practices.
44
  - Explore ethical considerations related to these technologies.
45
-
46
  6. **Case Studies:**
47
  - Include detailed case studies with specific examples.
48
  - Analyze real-world applications and their outcomes.
49
  - Discuss lessons learned and best practices from each case study.
50
-
51
  7. **Future Research Directions:**
52
  - Propose areas for further investigation and development.
53
  - Highlight emerging trends and technologies.
54
  - Discuss potential impact and applications of future research.
55
-
56
  8. **Conclusions:**
57
  - Summarize main findings and insights.
58
  - Reflect on the implications for researchers and practitioners.
59
  - Provide actionable recommendations and future outlook.
60
-
61
  9. **References:**
62
  - Include a comprehensive list of recent research papers, articles, and other relevant sources.
63
  - Ensure accurate and complete citations to support the analysis.
64
-
65
  **Additional Instructions:**
66
  - Break down complex topics into clear sub-sections.
67
  - Ensure each section transitions smoothly to the next.
68
  - Use visual aids where applicable (e.g., charts, graphs, tables).
69
  - Address privacy and security systematically throughout the report.
70
-
71
  """
72
 
73
 
74
  WRITER_PROMPT = """You are an essay assistant specializing in research reports. Produce a comprehensive research report based on the provided outline and user's requirements. Your report should cover recent trends, specific advancements, technical details, and future research directions in depth.
75
-
76
  **Report Requirements:**
77
  1. **Executive Summary:**
78
  - Summarize key findings, significance, and implications.
79
  - Ensure clarity and brevity while covering essential points.
80
-
81
  2. **Introduction:**
82
  - Provide detailed background and context.
83
  - State and elaborate on research questions or hypotheses.
84
-
85
  3. **Recent Trends and Advancements:**
86
  - Present detailed and up-to-date information on each technology.
87
  - Use concrete examples and recent data to support your analysis.
88
-
89
  4. **Integration of Technologies:**
90
  - Discuss how technologies intersect and enhance each other.
91
  - Include specific examples of successful integration and its benefits.
92
-
93
  5. **Privacy and Security Challenges:**
94
  - Thoroughly address potential privacy and security issues.
95
  - Provide a balanced view of potential solutions and ongoing research.
96
-
97
  6. **Case Studies:**
98
  - Include detailed, well-researched case studies.
99
  - Provide concrete examples and analyze outcomes and lessons learned.
100
-
101
  7. **Future Research Directions:**
102
  - Propose and justify areas for further investigation.
103
  - Discuss potential future applications and their significance.
104
-
105
  8. **Conclusions:**
106
  - Summarize key insights and recommendations clearly.
107
  - Ensure the conclusions reflect the report’s findings and implications.
108
-
109
  9. **References:**
110
  - Accurately cite recent research papers and relevant sources.
111
  - Ensure all references are credible and support the report’s content.
112
-
113
  **Additional Instructions:**
114
  - Maintain a clear and logical flow throughout the report.
115
  - Use visual aids to present data effectively.
116
  - Ensure smooth transitions between sections for readability.
117
  - Provide a critical analysis of various perspectives.
118
-
119
  {content}
120
  """
121
 
122
 
123
  REFLECTION_PROMPT = """You are a seasoned educator evaluating an essay submission. Provide constructive feedback on the user's research report, focusing on depth, comprehensiveness, and clarity.
124
-
125
  **Evaluation Criteria:**
126
  1. **Coverage of Recent Trends and Advancements:**
127
  - Assess how well the report addresses recent trends and specific advancements.
128
  - Check for detailed and accurate information on each technology.
129
-
130
  2. **Integration and Synergies:**
131
  - Evaluate how effectively the report discusses the integration of technologies and their synergies.
132
  - Look for examples and explanations of how these technologies enhance each other.
133
-
134
  3. **Privacy and Security Challenges:**
135
  - Assess the depth of discussion on privacy and security challenges.
136
  - Evaluate the effectiveness of proposed solutions and mitigation strategies.
137
-
138
  4. **Case Studies and Real-World Applications:**
139
  - Review the inclusion and analysis of case studies.
140
  - Check for relevance, detail, and real-world applicability of examples.
141
-
142
  5. **Future Research Directions:**
143
  - Evaluate the clarity and feasibility of proposed future research directions.
144
  - Assess the potential impact and significance of these directions.
145
-
146
  6. **References and Citations:**
147
  - Ensure that the report includes accurate and comprehensive citations.
148
  - Review the relevance and credibility of referenced sources.
149
-
150
  **Recommendations:**
151
  - Provide specific suggestions for improving depth and clarity.
152
  - Highlight any gaps or areas needing further development.
153
  - Suggest ways to enhance readability and logical flow.
154
-
155
  """
156
 
157
  RESEARCH_PLAN_PROMPT = """As a researcher, your task is to generate effective search queries to gather comprehensive information for the upcoming research report. Provide up to 4 targeted queries to obtain the most relevant and recent data.
158
-
159
  **Search Queries:**
160
  1. **Latest Developments in [Technology]:** Focus on recent advancements and breakthroughs in the technology related to your report.
161
  2. **Technical Details and Innovations:** Seek detailed technical information and innovations for the technology in question.
162
  3. **Case Studies and Real-World Applications:** Find concrete examples and case studies that demonstrate the application of the technology.
163
  4. **Integration and Privacy/Security Challenges:** Explore how different technologies integrate, their potential synergies, and address privacy/security challenges.
164
-
165
  **Instructions:**
166
  - Use credible sources and evaluate the relevance of the information.
167
  - Ensure queries are specific to the technology and research focus.
168
  - Gather information that supports a thorough and comprehensive analysis.
169
-
170
  """
171
 
172
  RESEARCH_CRITIQUE_PROMPT = """You are tasked with gathering updated information to assist in revising the research report. Generate up to 3 focused search queries to find the most relevant and recent data.
173
-
174
  **Search Queries:**
175
  1. **Recent Trends in [Technology]:** Identify the latest trends and advancements in the technology relevant to the report.
176
  2. **Detailed Technical Insights:** Obtain detailed technical information and recent innovations for a thorough understanding.
177
  3. **Privacy and Security Challenges:** Find updated discussions on privacy and security challenges related to integrating the technologies.
178
-
179
  **Instructions:**
180
  - Ensure the queries target high-quality and credible sources.
181
  - Focus on obtaining comprehensive and relevant data.
182
  - Evaluate the information for its relevance and contribution to the report.
183
-
184
  """
185
 
186
 
187
- from langchain_core.pydantic_v1 import BaseModel
188
 
189
  class Queries(BaseModel):
190
  queries: List[str]
191
 
192
- from tavily import TavilyClient
193
- import os
194
- os.environ['TAVILY_API_KEY'] = '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'
195
 
 
 
196
  def plan_node(state: AgentState):
197
  print("reached planner node")
198
  messages = [
199
  SystemMessage(content=PLAN_PROMPT),
200
  HumanMessage(content=state['task'])
201
  ]
202
- print("hi",messages)
203
  response = model.invoke(messages)
204
- print("hi",response)
205
 
206
  return {"plan": response.content}
207
 
@@ -213,13 +188,9 @@ def research_plan_node(state: AgentState):
213
  SystemMessage(content=RESEARCH_PLAN_PROMPT),
214
  HumanMessage(content=state['task'])
215
  ]
216
- print("passed 1")
217
 
218
  try:
219
  response = model.invoke(messages)
220
- print(type(response))
221
- print("list of queries", response)
222
- print("passed 2")
223
 
224
  # Extract the text content from the response
225
  response_text = response.content if hasattr(response, 'content') else str(response)
@@ -231,7 +202,7 @@ def research_plan_node(state: AgentState):
231
  # Perform search based on extracted queries
232
  content = state['content'] or []
233
  for q in queries_list:
234
- response = tavily.search(query=q, max_results=2)
235
  for r in response['results']:
236
  content.append(r['content'])
237
 
@@ -302,7 +273,7 @@ def research_critique_node(state: AgentState):
302
  # Perform search based on extracted queries
303
  content = state['content'] or []
304
  for q in queries_list:
305
- response = tavily.search(query=q, max_results=2)
306
  for r in response['results']:
307
  content.append(r['content'])
308
 
@@ -355,15 +326,7 @@ builder.add_edge("research_critique", "generate")
355
 
356
  graph = builder.compile(checkpointer=memory)
357
 
358
- import gradio as gr
359
- from langgraph.graph import StateGraph, END
360
- from typing import TypedDict, List
361
- from langgraph.checkpoint.sqlite import SqliteSaver
362
- from langchain_core.messages import SystemMessage, HumanMessage
363
- from langchain_openai import ChatOpenAI
364
- from langchain_core.pydantic_v1 import BaseModel
365
- from tavily import TavilyClient
366
- import os
367
 
368
  # (Include all the existing code for AgentState, prompts, and node functions here)
369
 
@@ -454,18 +417,18 @@ def gradio_interface(task, max_revisions):
454
  iface = gr.Interface(
455
  fn=gradio_interface,
456
  inputs=[
457
- gr.Textbox(label="Essay Topic", placeholder="Enter the essay topic or task here"),
458
  gr.Slider(minimum=1, maximum=5, step=1, label="Max Revisions", value=2)
459
  ],
460
  outputs=[
461
- gr.Textbox(label="Final Essay"),
462
  gr.Textbox(label="Planning Output", lines=10),
463
  gr.Textbox(label="Research Output", lines=10),
464
  gr.Textbox(label="Generation Output", lines=10),
465
  gr.Textbox(label="Reflection Output", lines=10)
466
  ],
467
- title="Multi-Agent Essay Writing System",
468
- description="This system uses multiple AI agents to plan, research, write, and revise an essay on the given topic."
469
  )
470
 
471
  iface.launch()
 
4
  from langgraph.checkpoint.sqlite import SqliteSaver
5
  from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, AIMessage, ChatMessage
6
  from langchain_google_genai import ChatGoogleGenerativeAI
7
+ from langchain_core.pydantic_v1 import BaseModel
8
+ import os
9
+ import gradio as gr
10
+ from langgraph.graph import StateGraph, END
11
+ from typing import TypedDict, List
12
+ from langgraph.checkpoint.sqlite import SqliteSaver
13
+ from langchain_core.messages import SystemMessage, HumanMessage
14
+ from langchain_openai import ChatOpenAI
15
+ from langchain_core.pydantic_v1 import BaseModel
16
+ from tavily import TavilyClient
17
+
18
  memory = SqliteSaver.from_conn_string(":memory:")
19
 
20
  class AgentState(TypedDict):
 
27
  max_revisions: int
28
 
29
  from langchain_openai import ChatOpenAI
30
+ try:
31
+ model = ChatGoogleGenerativeAI(model="gemini-1.5-pro-latest", google_api_key="AIzaSyD8EQItv3a2p9PNpdgf4nK7vLStWuzwAcg", convert_system_message_to_human=True, temperature=0.6)
32
+ except Exception as e:
33
+ print("Error",e)
34
  PLAN_PROMPT = """You are an experienced writer tasked with drafting a highly detailed and comprehensive outline for a research report. Your goal is to create an exceptionally structured outline for the user's chosen topic, ensuring it encourages an in-depth examination of recent trends, specific advancements, technical details, and future research directions.
 
35
  **Outline Requirements:**
36
  1. **Executive Summary:**
37
  - Summarize key findings, significance, and implications.
38
  - Highlight main conclusions and recommendations.
 
39
  2. **Introduction:**
40
  - Provide background on the topic.
41
  - State research questions or hypotheses.
42
  - Define the scope and objectives of the report.
 
43
  3. **Recent Trends and Advancements:**
44
  -give resposne according to users topic
 
45
  4. **Integration of Technologies:**
46
  - Discuss how these technologies intersect and enhance each other.
47
  - Provide examples of synergistic effects and combined applications.
48
  - Address integration challenges and potential solutions.
 
49
  5. **Privacy and Security Challenges:**
50
  - Identify key privacy and security issues.
51
  - Discuss mitigation strategies and best practices.
52
  - Explore ethical considerations related to these technologies.
 
53
  6. **Case Studies:**
54
  - Include detailed case studies with specific examples.
55
  - Analyze real-world applications and their outcomes.
56
  - Discuss lessons learned and best practices from each case study.
 
57
  7. **Future Research Directions:**
58
  - Propose areas for further investigation and development.
59
  - Highlight emerging trends and technologies.
60
  - Discuss potential impact and applications of future research.
 
61
  8. **Conclusions:**
62
  - Summarize main findings and insights.
63
  - Reflect on the implications for researchers and practitioners.
64
  - Provide actionable recommendations and future outlook.
 
65
  9. **References:**
66
  - Include a comprehensive list of recent research papers, articles, and other relevant sources.
67
  - Ensure accurate and complete citations to support the analysis.
 
68
  **Additional Instructions:**
69
  - Break down complex topics into clear sub-sections.
70
  - Ensure each section transitions smoothly to the next.
71
  - Use visual aids where applicable (e.g., charts, graphs, tables).
72
  - Address privacy and security systematically throughout the report.
 
73
  """
74
 
75
 
76
  WRITER_PROMPT = """You are an essay assistant specializing in research reports. Produce a comprehensive research report based on the provided outline and user's requirements. Your report should cover recent trends, specific advancements, technical details, and future research directions in depth.
 
77
  **Report Requirements:**
78
  1. **Executive Summary:**
79
  - Summarize key findings, significance, and implications.
80
  - Ensure clarity and brevity while covering essential points.
 
81
  2. **Introduction:**
82
  - Provide detailed background and context.
83
  - State and elaborate on research questions or hypotheses.
 
84
  3. **Recent Trends and Advancements:**
85
  - Present detailed and up-to-date information on each technology.
86
  - Use concrete examples and recent data to support your analysis.
 
87
  4. **Integration of Technologies:**
88
  - Discuss how technologies intersect and enhance each other.
89
  - Include specific examples of successful integration and its benefits.
 
90
  5. **Privacy and Security Challenges:**
91
  - Thoroughly address potential privacy and security issues.
92
  - Provide a balanced view of potential solutions and ongoing research.
 
93
  6. **Case Studies:**
94
  - Include detailed, well-researched case studies.
95
  - Provide concrete examples and analyze outcomes and lessons learned.
 
96
  7. **Future Research Directions:**
97
  - Propose and justify areas for further investigation.
98
  - Discuss potential future applications and their significance.
 
99
  8. **Conclusions:**
100
  - Summarize key insights and recommendations clearly.
101
  - Ensure the conclusions reflect the report’s findings and implications.
 
102
  9. **References:**
103
  - Accurately cite recent research papers and relevant sources.
104
  - Ensure all references are credible and support the report’s content.
 
105
  **Additional Instructions:**
106
  - Maintain a clear and logical flow throughout the report.
107
  - Use visual aids to present data effectively.
108
  - Ensure smooth transitions between sections for readability.
109
  - Provide a critical analysis of various perspectives.
 
110
  {content}
111
  """
112
 
113
 
114
  REFLECTION_PROMPT = """You are a seasoned educator evaluating an essay submission. Provide constructive feedback on the user's research report, focusing on depth, comprehensiveness, and clarity.
 
115
  **Evaluation Criteria:**
116
  1. **Coverage of Recent Trends and Advancements:**
117
  - Assess how well the report addresses recent trends and specific advancements.
118
  - Check for detailed and accurate information on each technology.
 
119
  2. **Integration and Synergies:**
120
  - Evaluate how effectively the report discusses the integration of technologies and their synergies.
121
  - Look for examples and explanations of how these technologies enhance each other.
 
122
  3. **Privacy and Security Challenges:**
123
  - Assess the depth of discussion on privacy and security challenges.
124
  - Evaluate the effectiveness of proposed solutions and mitigation strategies.
 
125
  4. **Case Studies and Real-World Applications:**
126
  - Review the inclusion and analysis of case studies.
127
  - Check for relevance, detail, and real-world applicability of examples.
 
128
  5. **Future Research Directions:**
129
  - Evaluate the clarity and feasibility of proposed future research directions.
130
  - Assess the potential impact and significance of these directions.
 
131
  6. **References and Citations:**
132
  - Ensure that the report includes accurate and comprehensive citations.
133
  - Review the relevance and credibility of referenced sources.
 
134
  **Recommendations:**
135
  - Provide specific suggestions for improving depth and clarity.
136
  - Highlight any gaps or areas needing further development.
137
  - Suggest ways to enhance readability and logical flow.
 
138
  """
139
 
140
  RESEARCH_PLAN_PROMPT = """As a researcher, your task is to generate effective search queries to gather comprehensive information for the upcoming research report. Provide up to 4 targeted queries to obtain the most relevant and recent data.
 
141
  **Search Queries:**
142
  1. **Latest Developments in [Technology]:** Focus on recent advancements and breakthroughs in the technology related to your report.
143
  2. **Technical Details and Innovations:** Seek detailed technical information and innovations for the technology in question.
144
  3. **Case Studies and Real-World Applications:** Find concrete examples and case studies that demonstrate the application of the technology.
145
  4. **Integration and Privacy/Security Challenges:** Explore how different technologies integrate, their potential synergies, and address privacy/security challenges.
 
146
  **Instructions:**
147
  - Use credible sources and evaluate the relevance of the information.
148
  - Ensure queries are specific to the technology and research focus.
149
  - Gather information that supports a thorough and comprehensive analysis.
 
150
  """
151
 
152
  RESEARCH_CRITIQUE_PROMPT = """You are tasked with gathering updated information to assist in revising the research report. Generate up to 3 focused search queries to find the most relevant and recent data.
 
153
  **Search Queries:**
154
  1. **Recent Trends in [Technology]:** Identify the latest trends and advancements in the technology relevant to the report.
155
  2. **Detailed Technical Insights:** Obtain detailed technical information and recent innovations for a thorough understanding.
156
  3. **Privacy and Security Challenges:** Find updated discussions on privacy and security challenges related to integrating the technologies.
 
157
  **Instructions:**
158
  - Ensure the queries target high-quality and credible sources.
159
  - Focus on obtaining comprehensive and relevant data.
160
  - Evaluate the information for its relevance and contribution to the report.
 
161
  """
162
 
163
 
164
+
165
 
166
  class Queries(BaseModel):
167
  queries: List[str]
168
 
 
 
 
169
 
170
+
171
+ client = TavilyClient(api_key="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")
172
  def plan_node(state: AgentState):
173
  print("reached planner node")
174
  messages = [
175
  SystemMessage(content=PLAN_PROMPT),
176
  HumanMessage(content=state['task'])
177
  ]
178
+
179
  response = model.invoke(messages)
 
180
 
181
  return {"plan": response.content}
182
 
 
188
  SystemMessage(content=RESEARCH_PLAN_PROMPT),
189
  HumanMessage(content=state['task'])
190
  ]
 
191
 
192
  try:
193
  response = model.invoke(messages)
 
 
 
194
 
195
  # Extract the text content from the response
196
  response_text = response.content if hasattr(response, 'content') else str(response)
 
202
  # Perform search based on extracted queries
203
  content = state['content'] or []
204
  for q in queries_list:
205
+ response = client.search(query=q, max_results=2)
206
  for r in response['results']:
207
  content.append(r['content'])
208
 
 
273
  # Perform search based on extracted queries
274
  content = state['content'] or []
275
  for q in queries_list:
276
+ response = client.search(query=q, max_results=2)
277
  for r in response['results']:
278
  content.append(r['content'])
279
 
 
326
 
327
  graph = builder.compile(checkpointer=memory)
328
 
329
+
 
 
 
 
 
 
 
 
330
 
331
  # (Include all the existing code for AgentState, prompts, and node functions here)
332
 
 
417
  iface = gr.Interface(
418
  fn=gradio_interface,
419
  inputs=[
420
+ gr.Textbox(label="Report Topic", placeholder="Enter the report topic or task here"),
421
  gr.Slider(minimum=1, maximum=5, step=1, label="Max Revisions", value=2)
422
  ],
423
  outputs=[
424
+ gr.Textbox(label="Final Report"),
425
  gr.Textbox(label="Planning Output", lines=10),
426
  gr.Textbox(label="Research Output", lines=10),
427
  gr.Textbox(label="Generation Output", lines=10),
428
  gr.Textbox(label="Reflection Output", lines=10)
429
  ],
430
+ title="Multi-Agent Report Writing System",
431
+ description="This system uses multiple AI agents to plan, research, write, and revise an research report on the given topic."
432
  )
433
 
434
  iface.launch()