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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Agentic AI Patterns Implementation for Scientific Q&A
|
| 3 |
+
Based on 5 proven agentic patterns for better LLM performance
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import asyncio
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
from typing import Dict, List, Any, Optional, Tuple
|
| 10 |
+
from openai import OpenAI
|
| 11 |
+
import requests
|
| 12 |
+
import time
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
class OpenAlexTool:
|
| 16 |
+
"""OpenAlex API integration for scientific literature search"""
|
| 17 |
+
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.base_url = "https://api.openalex.org"
|
| 20 |
+
self.session = requests.Session()
|
| 21 |
+
self.session.headers.update({
|
| 22 |
+
'User-Agent': 'AgenticAI-ScientificQA/1.0 (mailto:research@university.edu)'
|
| 23 |
+
})
|
| 24 |
+
|
| 25 |
+
def search_papers(self, query: str, max_results: int = 10) -> List[Dict]:
|
| 26 |
+
"""Search for scientific papers using OpenAlex"""
|
| 27 |
+
try:
|
| 28 |
+
url = f"{self.base_url}/works"
|
| 29 |
+
params = {
|
| 30 |
+
'search': query,
|
| 31 |
+
'per-page': min(max_results, 25),
|
| 32 |
+
'sort': 'relevance_score:desc'
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
time.sleep(0.1) # Rate limiting
|
| 36 |
+
response = self.session.get(url, params=params, timeout=30)
|
| 37 |
+
|
| 38 |
+
if response.status_code == 200:
|
| 39 |
+
data = response.json()
|
| 40 |
+
results = []
|
| 41 |
+
|
| 42 |
+
for work in data.get('results', []):
|
| 43 |
+
processed_work = {
|
| 44 |
+
'title': work.get('display_name', ''),
|
| 45 |
+
'year': work.get('publication_year'),
|
| 46 |
+
'citations': work.get('cited_by_count', 0),
|
| 47 |
+
'doi': work.get('doi', ''),
|
| 48 |
+
'authors': self._extract_authors(work.get('authorships', [])),
|
| 49 |
+
'abstract': self._reconstruct_abstract(work.get('abstract_inverted_index', {})),
|
| 50 |
+
'url': work.get('id', ''),
|
| 51 |
+
'open_access': work.get('open_access', {}).get('is_oa', False)
|
| 52 |
+
}
|
| 53 |
+
results.append(processed_work)
|
| 54 |
+
|
| 55 |
+
return results
|
| 56 |
+
else:
|
| 57 |
+
return []
|
| 58 |
+
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"OpenAlex search error: {e}")
|
| 61 |
+
return []
|
| 62 |
+
|
| 63 |
+
def _extract_authors(self, authorships: List[Dict]) -> List[str]:
|
| 64 |
+
"""Extract author names from authorships"""
|
| 65 |
+
authors = []
|
| 66 |
+
for authorship in authorships[:3]: # First 3 authors
|
| 67 |
+
author = authorship.get('author', {})
|
| 68 |
+
name = author.get('display_name', 'Unknown')
|
| 69 |
+
authors.append(name)
|
| 70 |
+
return authors
|
| 71 |
+
|
| 72 |
+
def _reconstruct_abstract(self, inverted_index: Dict) -> str:
|
| 73 |
+
"""Reconstruct abstract from inverted index"""
|
| 74 |
+
if not inverted_index:
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
word_positions = []
|
| 78 |
+
for word, positions in inverted_index.items():
|
| 79 |
+
for pos in positions:
|
| 80 |
+
word_positions.append((pos, word))
|
| 81 |
+
|
| 82 |
+
word_positions.sort()
|
| 83 |
+
abstract_words = [word for _, word in word_positions]
|
| 84 |
+
|
| 85 |
+
return ' '.join(abstract_words)[:500] # Limit length
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class AgenticPatterns:
|
| 89 |
+
"""Implementation of 5 Agentic AI Patterns for Scientific Q&A"""
|
| 90 |
+
|
| 91 |
+
def __init__(self, api_key: str):
|
| 92 |
+
try:
|
| 93 |
+
self.client = OpenAI(api_key=api_key)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
# Fallback for older OpenAI versions
|
| 96 |
+
import openai
|
| 97 |
+
openai.api_key = api_key
|
| 98 |
+
self.client = openai
|
| 99 |
+
self.openalex = OpenAlexTool()
|
| 100 |
+
|
| 101 |
+
async def pure_llm(self, question: str) -> Dict[str, Any]:
|
| 102 |
+
"""Pattern 0: Pure LLM without any agentic enhancement"""
|
| 103 |
+
start_time = time.time()
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
response = self.client.chat.completions.create(
|
| 107 |
+
model="gpt-4o-mini",
|
| 108 |
+
messages=[
|
| 109 |
+
{"role": "system", "content": "You are a helpful scientific assistant. Answer questions clearly and accurately."},
|
| 110 |
+
{"role": "user", "content": question}
|
| 111 |
+
],
|
| 112 |
+
temperature=0.7,
|
| 113 |
+
max_tokens=1000
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
answer = response.choices[0].message.content
|
| 117 |
+
processing_time = time.time() - start_time
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"pattern": "Pure LLM",
|
| 121 |
+
"answer": answer,
|
| 122 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 123 |
+
"steps": ["Direct LLM response"],
|
| 124 |
+
"confidence": "N/A",
|
| 125 |
+
"sources": []
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
except Exception as e:
|
| 129 |
+
return {
|
| 130 |
+
"pattern": "Pure LLM",
|
| 131 |
+
"answer": f"Error: {str(e)}",
|
| 132 |
+
"processing_time": "0s",
|
| 133 |
+
"steps": ["Error occurred"],
|
| 134 |
+
"confidence": "N/A",
|
| 135 |
+
"sources": []
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
async def reflection_pattern(self, question: str) -> Dict[str, Any]:
|
| 139 |
+
"""Pattern 1: Reflection - Agent checks its own work"""
|
| 140 |
+
start_time = time.time()
|
| 141 |
+
steps = []
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
# Step 1: Initial response
|
| 145 |
+
steps.append("Generating initial response")
|
| 146 |
+
initial_response = self.client.chat.completions.create(
|
| 147 |
+
model="gpt-4o-mini",
|
| 148 |
+
messages=[
|
| 149 |
+
{"role": "system", "content": "You are a scientific assistant. Provide a detailed answer to the question."},
|
| 150 |
+
{"role": "user", "content": question}
|
| 151 |
+
],
|
| 152 |
+
temperature=0.7,
|
| 153 |
+
max_tokens=800
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
initial_answer = initial_response.choices[0].message.content
|
| 157 |
+
|
| 158 |
+
# Step 2: Self-reflection and critique
|
| 159 |
+
steps.append("Reflecting on initial response")
|
| 160 |
+
reflection_prompt = f"""
|
| 161 |
+
Review this scientific answer for accuracy, completeness, and clarity:
|
| 162 |
+
|
| 163 |
+
Question: {question}
|
| 164 |
+
Answer: {initial_answer}
|
| 165 |
+
|
| 166 |
+
Provide:
|
| 167 |
+
1. What's good about this answer
|
| 168 |
+
2. What could be improved
|
| 169 |
+
3. Any potential errors or missing information
|
| 170 |
+
4. Confidence score (1-10)
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
reflection_response = self.client.chat.completions.create(
|
| 174 |
+
model="gpt-4o-mini",
|
| 175 |
+
messages=[
|
| 176 |
+
{"role": "system", "content": "You are a critical reviewer of scientific content."},
|
| 177 |
+
{"role": "user", "content": reflection_prompt}
|
| 178 |
+
],
|
| 179 |
+
temperature=0.3,
|
| 180 |
+
max_tokens=500
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
reflection = reflection_response.choices[0].message.content
|
| 184 |
+
|
| 185 |
+
# Step 3: Improved response based on reflection
|
| 186 |
+
steps.append("Generating improved response")
|
| 187 |
+
improvement_prompt = f"""
|
| 188 |
+
Based on this reflection, provide an improved answer:
|
| 189 |
+
|
| 190 |
+
Original Question: {question}
|
| 191 |
+
Original Answer: {initial_answer}
|
| 192 |
+
Reflection: {reflection}
|
| 193 |
+
|
| 194 |
+
Provide a refined, more accurate answer:
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
final_response = self.client.chat.completions.create(
|
| 198 |
+
model="gpt-4o-mini",
|
| 199 |
+
messages=[
|
| 200 |
+
{"role": "system", "content": "You are a scientific assistant providing refined answers."},
|
| 201 |
+
{"role": "user", "content": improvement_prompt}
|
| 202 |
+
],
|
| 203 |
+
temperature=0.5,
|
| 204 |
+
max_tokens=1000
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
final_answer = final_response.choices[0].message.content
|
| 208 |
+
|
| 209 |
+
# Extract confidence score
|
| 210 |
+
confidence_match = re.search(r'confidence.*?(\d+)', reflection.lower())
|
| 211 |
+
confidence = confidence_match.group(1) if confidence_match else "7"
|
| 212 |
+
|
| 213 |
+
processing_time = time.time() - start_time
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
"pattern": "Reflection",
|
| 217 |
+
"answer": final_answer,
|
| 218 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 219 |
+
"steps": steps,
|
| 220 |
+
"confidence": f"{confidence}/10",
|
| 221 |
+
"reflection": reflection,
|
| 222 |
+
"sources": []
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
except Exception as e:
|
| 226 |
+
return {
|
| 227 |
+
"pattern": "Reflection",
|
| 228 |
+
"answer": f"Error: {str(e)}",
|
| 229 |
+
"processing_time": "0s",
|
| 230 |
+
"steps": steps,
|
| 231 |
+
"confidence": "N/A",
|
| 232 |
+
"sources": []
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
async def planning_pattern(self, question: str) -> Dict[str, Any]:
|
| 236 |
+
"""Pattern 2: Planning - Agent creates and follows a plan"""
|
| 237 |
+
start_time = time.time()
|
| 238 |
+
steps = []
|
| 239 |
+
|
| 240 |
+
try:
|
| 241 |
+
# Step 1: Create a plan
|
| 242 |
+
steps.append("Creating research plan")
|
| 243 |
+
planning_prompt = f"""
|
| 244 |
+
Create a step-by-step research plan to answer this scientific question:
|
| 245 |
+
{question}
|
| 246 |
+
|
| 247 |
+
Provide a numbered list of 3-5 specific steps to thoroughly research and answer this question.
|
| 248 |
+
Each step should be actionable and specific.
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
plan_response = self.client.chat.completions.create(
|
| 252 |
+
model="gpt-4o-mini",
|
| 253 |
+
messages=[
|
| 254 |
+
{"role": "system", "content": "You are a research planner. Create systematic research plans."},
|
| 255 |
+
{"role": "user", "content": planning_prompt}
|
| 256 |
+
],
|
| 257 |
+
temperature=0.3,
|
| 258 |
+
max_tokens=400
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
plan = plan_response.choices[0].message.content
|
| 262 |
+
|
| 263 |
+
# Step 2: Execute the plan
|
| 264 |
+
steps.append("Executing research plan")
|
| 265 |
+
execution_prompt = f"""
|
| 266 |
+
Follow this research plan to answer the question:
|
| 267 |
+
|
| 268 |
+
Question: {question}
|
| 269 |
+
Plan: {plan}
|
| 270 |
+
|
| 271 |
+
Execute each step systematically and provide a comprehensive answer based on your planned approach.
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
execution_response = self.client.chat.completions.create(
|
| 275 |
+
model="gpt-4o-mini",
|
| 276 |
+
messages=[
|
| 277 |
+
{"role": "system", "content": "You are a systematic researcher following a detailed plan."},
|
| 278 |
+
{"role": "user", "content": execution_prompt}
|
| 279 |
+
],
|
| 280 |
+
temperature=0.6,
|
| 281 |
+
max_tokens=1200
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
answer = execution_response.choices[0].message.content
|
| 285 |
+
|
| 286 |
+
processing_time = time.time() - start_time
|
| 287 |
+
|
| 288 |
+
return {
|
| 289 |
+
"pattern": "Planning",
|
| 290 |
+
"answer": answer,
|
| 291 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 292 |
+
"steps": steps,
|
| 293 |
+
"plan": plan,
|
| 294 |
+
"confidence": "8/10",
|
| 295 |
+
"sources": []
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
except Exception as e:
|
| 299 |
+
return {
|
| 300 |
+
"pattern": "Planning",
|
| 301 |
+
"answer": f"Error: {str(e)}",
|
| 302 |
+
"processing_time": "0s",
|
| 303 |
+
"steps": steps,
|
| 304 |
+
"confidence": "N/A",
|
| 305 |
+
"sources": []
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
async def tool_use_pattern(self, question: str) -> Dict[str, Any]:
|
| 309 |
+
"""Pattern 3: Tool Use - Agent uses OpenAlex to find relevant papers"""
|
| 310 |
+
start_time = time.time()
|
| 311 |
+
steps = []
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
# Step 1: Analyze question for search terms
|
| 315 |
+
steps.append("Extracting search terms")
|
| 316 |
+
search_prompt = f"""
|
| 317 |
+
Extract 2-3 key scientific search terms from this question for academic paper search:
|
| 318 |
+
{question}
|
| 319 |
+
|
| 320 |
+
Provide only the search terms, separated by spaces, optimized for finding relevant scientific papers.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
search_response = self.client.chat.completions.create(
|
| 324 |
+
model="gpt-4o-mini",
|
| 325 |
+
messages=[
|
| 326 |
+
{"role": "system", "content": "You extract optimal search terms for scientific literature."},
|
| 327 |
+
{"role": "user", "content": search_prompt}
|
| 328 |
+
],
|
| 329 |
+
temperature=0.2,
|
| 330 |
+
max_tokens=50
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
search_terms = search_response.choices[0].message.content.strip()
|
| 334 |
+
|
| 335 |
+
# Step 2: Search for relevant papers
|
| 336 |
+
steps.append(f"Searching papers with: '{search_terms}'")
|
| 337 |
+
papers = self.openalex.search_papers(search_terms, max_results=5)
|
| 338 |
+
|
| 339 |
+
# Step 3: Synthesize answer with paper evidence
|
| 340 |
+
steps.append("Synthesizing answer with literature evidence")
|
| 341 |
+
|
| 342 |
+
papers_context = ""
|
| 343 |
+
if papers:
|
| 344 |
+
papers_context = "\n\nRelevant Research Papers:\n"
|
| 345 |
+
for i, paper in enumerate(papers[:3], 1):
|
| 346 |
+
papers_context += f"{i}. {paper['title']} ({paper['year']}) - {paper['citations']} citations\n"
|
| 347 |
+
if paper['abstract']:
|
| 348 |
+
papers_context += f" Abstract: {paper['abstract'][:200]}...\n"
|
| 349 |
+
|
| 350 |
+
synthesis_prompt = f"""
|
| 351 |
+
Answer this scientific question using the provided research papers as evidence:
|
| 352 |
+
|
| 353 |
+
Question: {question}
|
| 354 |
+
{papers_context}
|
| 355 |
+
|
| 356 |
+
Provide a comprehensive answer that:
|
| 357 |
+
1. Directly addresses the question
|
| 358 |
+
2. References relevant findings from the papers
|
| 359 |
+
3. Acknowledges any limitations in current research
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
synthesis_response = self.client.chat.completions.create(
|
| 363 |
+
model="gpt-4o-mini",
|
| 364 |
+
messages=[
|
| 365 |
+
{"role": "system", "content": "You are a scientific researcher synthesizing evidence from literature."},
|
| 366 |
+
{"role": "user", "content": synthesis_prompt}
|
| 367 |
+
],
|
| 368 |
+
temperature=0.6,
|
| 369 |
+
max_tokens=1200
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
answer = synthesis_response.choices[0].message.content
|
| 373 |
+
|
| 374 |
+
processing_time = time.time() - start_time
|
| 375 |
+
|
| 376 |
+
return {
|
| 377 |
+
"pattern": "Tool Use (OpenAlex)",
|
| 378 |
+
"answer": answer,
|
| 379 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 380 |
+
"steps": steps,
|
| 381 |
+
"search_terms": search_terms,
|
| 382 |
+
"papers_found": len(papers),
|
| 383 |
+
"confidence": "9/10" if papers else "6/10",
|
| 384 |
+
"sources": [{"title": p["title"], "year": p["year"], "citations": p["citations"]} for p in papers[:3]]
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
except Exception as e:
|
| 388 |
+
return {
|
| 389 |
+
"pattern": "Tool Use (OpenAlex)",
|
| 390 |
+
"answer": f"Error: {str(e)}",
|
| 391 |
+
"processing_time": "0s",
|
| 392 |
+
"steps": steps,
|
| 393 |
+
"confidence": "N/A",
|
| 394 |
+
"sources": []
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
async def multi_agent_pattern(self, question: str) -> Dict[str, Any]:
|
| 398 |
+
"""Pattern 4: Multi-Agent - Multiple specialized agents collaborate"""
|
| 399 |
+
start_time = time.time()
|
| 400 |
+
steps = []
|
| 401 |
+
|
| 402 |
+
try:
|
| 403 |
+
# Agent 1: Research Specialist
|
| 404 |
+
steps.append("Research Specialist analyzing question")
|
| 405 |
+
research_prompt = f"""
|
| 406 |
+
As a Research Specialist, analyze this scientific question and provide:
|
| 407 |
+
1. Key research areas involved
|
| 408 |
+
2. Important concepts to address
|
| 409 |
+
3. Potential methodologies relevant to the question
|
| 410 |
+
|
| 411 |
+
Question: {question}
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
research_response = self.client.chat.completions.create(
|
| 415 |
+
model="gpt-4o-mini",
|
| 416 |
+
messages=[
|
| 417 |
+
{"role": "system", "content": "You are a Research Specialist with expertise in scientific methodology."},
|
| 418 |
+
{"role": "user", "content": research_prompt}
|
| 419 |
+
],
|
| 420 |
+
temperature=0.4,
|
| 421 |
+
max_tokens=400
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
research_analysis = research_response.choices[0].message.content
|
| 425 |
+
|
| 426 |
+
# Agent 2: Domain Expert
|
| 427 |
+
steps.append("Domain Expert providing specialized knowledge")
|
| 428 |
+
expert_prompt = f"""
|
| 429 |
+
As a Domain Expert, provide specialized knowledge for this question:
|
| 430 |
+
{question}
|
| 431 |
+
|
| 432 |
+
Research Analysis: {research_analysis}
|
| 433 |
+
|
| 434 |
+
Focus on:
|
| 435 |
+
1. Current state of knowledge in this area
|
| 436 |
+
2. Key findings and established facts
|
| 437 |
+
3. Recent developments or controversies
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
expert_response = self.client.chat.completions.create(
|
| 441 |
+
model="gpt-4o-mini",
|
| 442 |
+
messages=[
|
| 443 |
+
{"role": "system", "content": "You are a Domain Expert with deep specialized knowledge."},
|
| 444 |
+
{"role": "user", "content": expert_prompt}
|
| 445 |
+
],
|
| 446 |
+
temperature=0.5,
|
| 447 |
+
max_tokens=500
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
expert_knowledge = expert_response.choices[0].message.content
|
| 451 |
+
|
| 452 |
+
# Agent 3: Critical Reviewer
|
| 453 |
+
steps.append("Critical Reviewer evaluating perspectives")
|
| 454 |
+
reviewer_prompt = f"""
|
| 455 |
+
As a Critical Reviewer, evaluate these perspectives on the question:
|
| 456 |
+
{question}
|
| 457 |
+
|
| 458 |
+
Research Analysis: {research_analysis}
|
| 459 |
+
Expert Knowledge: {expert_knowledge}
|
| 460 |
+
|
| 461 |
+
Provide:
|
| 462 |
+
1. Strengths of each perspective
|
| 463 |
+
2. Potential gaps or limitations
|
| 464 |
+
3. Areas of uncertainty
|
| 465 |
+
"""
|
| 466 |
+
|
| 467 |
+
reviewer_response = self.client.chat.completions.create(
|
| 468 |
+
model="gpt-4o-mini",
|
| 469 |
+
messages=[
|
| 470 |
+
{"role": "system", "content": "You are a Critical Reviewer who evaluates scientific arguments."},
|
| 471 |
+
{"role": "user", "content": reviewer_prompt}
|
| 472 |
+
],
|
| 473 |
+
temperature=0.3,
|
| 474 |
+
max_tokens=400
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
critical_review = reviewer_response.choices[0].message.content
|
| 478 |
+
|
| 479 |
+
# Agent 4: Synthesizer
|
| 480 |
+
steps.append("Synthesizer creating final answer")
|
| 481 |
+
synthesis_prompt = f"""
|
| 482 |
+
Synthesize all agent perspectives into a comprehensive answer:
|
| 483 |
+
|
| 484 |
+
Question: {question}
|
| 485 |
+
|
| 486 |
+
Research Specialist: {research_analysis}
|
| 487 |
+
Domain Expert: {expert_knowledge}
|
| 488 |
+
Critical Reviewer: {critical_review}
|
| 489 |
+
|
| 490 |
+
Provide a balanced, comprehensive answer that incorporates insights from all agents.
|
| 491 |
+
"""
|
| 492 |
+
|
| 493 |
+
synthesis_response = self.client.chat.completions.create(
|
| 494 |
+
model="gpt-4o-mini",
|
| 495 |
+
messages=[
|
| 496 |
+
{"role": "system", "content": "You are a Synthesizer who combines multiple expert perspectives."},
|
| 497 |
+
{"role": "user", "content": synthesis_prompt}
|
| 498 |
+
],
|
| 499 |
+
temperature=0.6,
|
| 500 |
+
max_tokens=1000
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
final_answer = synthesis_response.choices[0].message.content
|
| 504 |
+
|
| 505 |
+
processing_time = time.time() - start_time
|
| 506 |
+
|
| 507 |
+
return {
|
| 508 |
+
"pattern": "Multi-Agent",
|
| 509 |
+
"answer": final_answer,
|
| 510 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 511 |
+
"steps": steps,
|
| 512 |
+
"agents_used": ["Research Specialist", "Domain Expert", "Critical Reviewer", "Synthesizer"],
|
| 513 |
+
"confidence": "9/10",
|
| 514 |
+
"sources": []
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
except Exception as e:
|
| 518 |
+
return {
|
| 519 |
+
"pattern": "Multi-Agent",
|
| 520 |
+
"answer": f"Error: {str(e)}",
|
| 521 |
+
"processing_time": "0s",
|
| 522 |
+
"steps": steps,
|
| 523 |
+
"confidence": "N/A",
|
| 524 |
+
"sources": []
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
async def chain_of_thought_pattern(self, question: str) -> Dict[str, Any]:
|
| 528 |
+
"""Pattern 5: Chain of Thought - Step-by-step reasoning"""
|
| 529 |
+
start_time = time.time()
|
| 530 |
+
steps = []
|
| 531 |
+
|
| 532 |
+
try:
|
| 533 |
+
steps.append("Breaking down question into reasoning steps")
|
| 534 |
+
|
| 535 |
+
cot_prompt = f"""
|
| 536 |
+
Answer this scientific question using step-by-step reasoning. Show your thinking process clearly.
|
| 537 |
+
|
| 538 |
+
Question: {question}
|
| 539 |
+
|
| 540 |
+
Please think through this step by step:
|
| 541 |
+
|
| 542 |
+
Step 1: Understand what the question is asking
|
| 543 |
+
Step 2: Identify the key scientific concepts involved
|
| 544 |
+
Step 3: Consider what we know about these concepts
|
| 545 |
+
Step 4: Apply logical reasoning to connect the concepts
|
| 546 |
+
Step 5: Draw conclusions based on the reasoning
|
| 547 |
+
Step 6: Consider any limitations or uncertainties
|
| 548 |
+
|
| 549 |
+
Show your reasoning for each step, then provide a final answer.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
cot_response = self.client.chat.completions.create(
|
| 553 |
+
model="gpt-4o-mini",
|
| 554 |
+
messages=[
|
| 555 |
+
{"role": "system", "content": "You are a scientific reasoner who thinks step-by-step and shows your reasoning process clearly."},
|
| 556 |
+
{"role": "user", "content": cot_prompt}
|
| 557 |
+
],
|
| 558 |
+
temperature=0.4,
|
| 559 |
+
max_tokens=1500
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
answer = cot_response.choices[0].message.content
|
| 563 |
+
|
| 564 |
+
processing_time = time.time() - start_time
|
| 565 |
+
|
| 566 |
+
return {
|
| 567 |
+
"pattern": "Chain of Thought",
|
| 568 |
+
"answer": answer,
|
| 569 |
+
"processing_time": f"{processing_time:.2f}s",
|
| 570 |
+
"steps": steps,
|
| 571 |
+
"reasoning_approach": "Step-by-step logical reasoning",
|
| 572 |
+
"confidence": "8/10",
|
| 573 |
+
"sources": []
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
except Exception as e:
|
| 577 |
+
return {
|
| 578 |
+
"pattern": "Chain of Thought",
|
| 579 |
+
"answer": f"Error: {str(e)}",
|
| 580 |
+
"processing_time": "0s",
|
| 581 |
+
"steps": steps,
|
| 582 |
+
"confidence": "N/A",
|
| 583 |
+
"sources": []
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
async def run_all_patterns(self, question: str) -> Dict[str, Any]:
|
| 587 |
+
"""Run all patterns simultaneously for comparison"""
|
| 588 |
+
start_time = time.time()
|
| 589 |
+
|
| 590 |
+
# Run all patterns concurrently
|
| 591 |
+
tasks = [
|
| 592 |
+
self.pure_llm(question),
|
| 593 |
+
self.reflection_pattern(question),
|
| 594 |
+
self.planning_pattern(question),
|
| 595 |
+
self.tool_use_pattern(question),
|
| 596 |
+
self.multi_agent_pattern(question),
|
| 597 |
+
self.chain_of_thought_pattern(question)
|
| 598 |
+
]
|
| 599 |
+
|
| 600 |
+
results = await asyncio.gather(*tasks)
|
| 601 |
+
|
| 602 |
+
total_time = time.time() - start_time
|
| 603 |
+
|
| 604 |
+
return {
|
| 605 |
+
"comparison_mode": True,
|
| 606 |
+
"total_processing_time": f"{total_time:.2f}s",
|
| 607 |
+
"results": {
|
| 608 |
+
"pure_llm": results[0],
|
| 609 |
+
"reflection": results[1],
|
| 610 |
+
"planning": results[2],
|
| 611 |
+
"tool_use": results[3],
|
| 612 |
+
"multi_agent": results[4],
|
| 613 |
+
"chain_of_thought": results[5]
|
| 614 |
+
},
|
| 615 |
+
"summary": {
|
| 616 |
+
"fastest": min(results, key=lambda x: float(x["processing_time"].replace('s', '')) if x["processing_time"] != "0s" else float('inf'))["pattern"],
|
| 617 |
+
"highest_confidence": max(results, key=lambda x: int(x["confidence"].split('/')[0]) if x["confidence"] != "N/A" else 0)["pattern"],
|
| 618 |
+
"most_sources": max(results, key=lambda x: len(x.get("sources", [])))["pattern"]
|
| 619 |
+
}
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
# Example questions for testing
|
| 624 |
+
EXAMPLE_QUESTIONS = [
|
| 625 |
+
"What are the main mechanisms behind CRISPR-Cas9 gene editing and what are its current limitations?",
|
| 626 |
+
"How does climate change affect ocean acidification and marine ecosystems?",
|
| 627 |
+
"What is the relationship between gut microbiome diversity and human immune system function?",
|
| 628 |
+
"Explain the current understanding of dark matter and dark energy in cosmology.",
|
| 629 |
+
"What are the key differences between mRNA vaccines and traditional vaccines in terms of mechanism and efficacy?"
|
| 630 |
+
]
|
| 631 |
+
|