Quazim0t0 commited on
Commit
226d94f
·
verified ·
1 Parent(s): b337a43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -107
app.py CHANGED
@@ -1,27 +1,20 @@
1
- """qResearch v3.0: Dual-Agent Research System"""
2
 
3
  import os
4
  import gradio as gr
5
- from dotenv import load_dotenv
6
  from smolagents import CodeAgent, HfApiModel, Tool
7
 
8
- # Initialize environment
9
- load_dotenv(override=True)
10
-
11
  class DuckDuckGoSearchTool(Tool):
12
- """Web search tool for primary research"""
13
  name = "web_search"
14
- description = "Performs privacy-focused web searches using DuckDuckGo"
15
  inputs = {
16
- "query": {
17
- "type": "string",
18
- "description": "Research query"
19
- },
20
  "max_results": {
21
  "type": "integer",
22
- "description": "Number of results (3-10)",
23
  "default": 5,
24
- "nullable": True # Critical fix here
25
  }
26
  }
27
  output_type = "string"
@@ -29,132 +22,65 @@ class DuckDuckGoSearchTool(Tool):
29
  def forward(self, query: str, max_results: int = 5) -> str:
30
  from duckduckgo_search import DDGS
31
  with DDGS() as ddgs:
32
- results = list(ddgs.text(query, max_results=max_results))
33
- return "\n".join([f"{idx+1}. {r['title']} ({r['href']}): {r['body']}"
34
- for idx, r in enumerate(results)])
35
 
36
  class ResearchSystem:
37
  def __init__(self):
38
  # Initialize model FIRST
39
  self.model = HfApiModel(
40
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
41
- custom_role_conversions={"tool-call": "assistant", "tool-response": "user"},
 
 
 
42
  use_auth_token=False,
43
  trust_remote_code=True
44
  )
45
-
46
- def __init__(self):
47
- # Initialize Researcher Agent
48
  self.researcher = CodeAgent(
49
  tools=[DuckDuckGoSearchTool()],
50
  model=self.model,
51
- system_message="""You are a Senior Research Analyst. Your tasks: # Changed parameter name
52
- 1. Conduct comprehensive web research using available tools
53
- 2. Synthesize findings into a detailed draft report
54
- 3. Include all relevant sources and data points
55
- 4. Maintain raw factual accuracy without formatting"""
56
  )
57
 
58
- # Initialize Formatter Agent
59
  self.formatter = CodeAgent(
60
  tools=[],
61
  model=self.model,
62
- system_message="""You are an MLA Formatting Specialist. Your tasks: # Changed parameter name
63
- 1. Receive raw research content
64
- 2. Apply proper MLA 9th edition formatting
65
- 3. Verify citation integrity
66
- 4. Structure content with:
67
- - Header block
68
- - Title capitalization
69
- - In-text citations
70
- - Works Cited section
71
- 5. Ensure academic tone and clarity"""
72
- )
73
-
74
- def _process_research(self, query: str) -> str:
75
- """Execute two-stage research process"""
76
- # Stage 1: Initial research
77
- raw_response = self.researcher.run(
78
- task=f"Conduct research about: {query}",
79
- temperature=0.7
80
- )
81
-
82
- # Stage 2: MLA formatting
83
- formatted_response = self.formatter.run(
84
- task=f"Format this research into MLA:\n{raw_response}",
85
- temperature=0.3
86
  )
87
-
88
- return formatted_response
89
 
90
  def create_interface(self):
91
- with gr.Blocks(theme=gr.themes.Soft(), title="qResearch v3") as interface:
92
- gr.Markdown("# qResearch Dual-Agent System\n*Research → Analysis → MLA Formatting*")
93
-
94
- with gr.Row():
95
- with gr.Column(scale=2):
96
- chat_history = gr.Chatbot(
97
- label="Agent Communication",
98
- avatar_images={
99
- "user": "👤",
100
- "assistant": "🤖",
101
- "Researcher": "🔍",
102
- "Formatter": "✒️"
103
- },
104
- height=500
105
- )
106
-
107
- with gr.Column(scale=1):
108
- research_steps = gr.JSON(
109
- label="Processing Steps",
110
- value={"Current Stage": "Awaiting Input"}
111
- )
112
 
113
  with gr.Row():
114
- input_box = gr.Textbox(
115
- placeholder="Enter research topic...",
116
- lines=2,
117
- label="Research Query"
118
- )
119
  submit_btn = gr.Button("Start Research", variant="primary")
120
 
121
  submit_btn.click(
122
- self._handle_query,
123
  inputs=[input_box],
124
- outputs=[chat_history, research_steps]
125
  )
126
 
127
  return interface
128
 
129
- def _handle_query(self, query: str):
130
  try:
131
- # Initial researcher agent processing
132
- researcher_msg = gr.ChatMessage(role="Researcher", content=f"Beginning research: {query}")
133
-
134
- # Get formatted response
135
- formatted_response = self._process_research(query)
136
-
137
- # Formatter agent response
138
- formatter_msg = gr.ChatMessage(role="Formatter", content=formatted_response)
139
-
140
  return [
141
- researcher_msg,
142
- formatter_msg
143
- ], {
144
- "Completed Stages": ["Research Collection", "MLA Formatting"],
145
- "Current Status": "Research Complete"
146
- }
147
-
148
  except Exception as e:
149
- error_msg = gr.ChatMessage(role="System", content=f"Error: {str(e)}")
150
- return [error_msg], {"Error": str(e)}
151
 
152
  if __name__ == "__main__":
153
- research_system = ResearchSystem()
154
- interface = research_system.create_interface()
155
- interface.launch(
156
- server_name="0.0.0.0",
157
- server_port=7860,
158
- share=False,
159
- show_error=True
160
- )
 
1
+ """qResearch: Dual-Agent Research System"""
2
 
3
  import os
4
  import gradio as gr
 
5
  from smolagents import CodeAgent, HfApiModel, Tool
6
 
 
 
 
7
  class DuckDuckGoSearchTool(Tool):
8
+ """Web search tool with proper input validation"""
9
  name = "web_search"
10
+ description = "Performs web searches using DuckDuckGo"
11
  inputs = {
12
+ "query": {"type": "string", "description": "Search query"},
 
 
 
13
  "max_results": {
14
  "type": "integer",
15
+ "description": "Number of results (1-10)",
16
  "default": 5,
17
+ "nullable": True
18
  }
19
  }
20
  output_type = "string"
 
22
  def forward(self, query: str, max_results: int = 5) -> str:
23
  from duckduckgo_search import DDGS
24
  with DDGS() as ddgs:
25
+ results = ddgs.text(query, max_results=max_results)
26
+ return "\n".join([f"{i+1}. {r['title']}: {r['body']} ({r['href']})"
27
+ for i, r in enumerate(results)])
28
 
29
  class ResearchSystem:
30
  def __init__(self):
31
  # Initialize model FIRST
32
  self.model = HfApiModel(
33
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
34
+ custom_role_conversions={
35
+ "tool-call": "assistant",
36
+ "tool-response": "user"
37
+ },
38
  use_auth_token=False,
39
  trust_remote_code=True
40
  )
41
+
42
+ # Initialize agents AFTER model
 
43
  self.researcher = CodeAgent(
44
  tools=[DuckDuckGoSearchTool()],
45
  model=self.model,
46
+ system_message="""Senior Research Analyst. Conduct comprehensive web research and compile raw findings."""
 
 
 
 
47
  )
48
 
 
49
  self.formatter = CodeAgent(
50
  tools=[],
51
  model=self.model,
52
+ system_message="""MLA Formatting Specialist. Convert raw research into properly formatted MLA documents."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  )
 
 
54
 
55
  def create_interface(self):
56
+ with gr.Blocks(title="qResearch") as interface:
57
+ gr.Markdown("# qResearch\n*Research → Analysis → MLA Formatting*")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  with gr.Row():
60
+ chat = gr.Chatbot(label="Research Process", height=500)
61
+ input_box = gr.Textbox(label="Enter Query", placeholder="Research topic...")
 
 
 
62
  submit_btn = gr.Button("Start Research", variant="primary")
63
 
64
  submit_btn.click(
65
+ self.process_query,
66
  inputs=[input_box],
67
+ outputs=[chat]
68
  )
69
 
70
  return interface
71
 
72
+ def process_query(self, query: str):
73
  try:
74
+ raw_research = self.researcher.run(query)
75
+ formatted = self.formatter.run(f"Format this research:\n{raw_research}")
 
 
 
 
 
 
 
76
  return [
77
+ gr.ChatMessage(role="user", content=query),
78
+ gr.ChatMessage(role="Researcher", content=raw_research),
79
+ gr.ChatMessage(role="Formatter", content=formatted)
80
+ ]
 
 
 
81
  except Exception as e:
82
+ return [gr.ChatMessage(role="Error", content=str(e))]
 
83
 
84
  if __name__ == "__main__":
85
+ system = ResearchSystem()
86
+ system.create_interface().launch(server_port=7860)