-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathproblem_investigator.py
More file actions
510 lines (466 loc) · 19.1 KB
/
Copy pathproblem_investigator.py
File metadata and controls
510 lines (466 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
from typing import Dict, Any, List
from datetime import datetime
import json
from .data_structures import AnalysisResult
from .knowledge_base import knowledge_base
from ..llm import LLMInterface
class ProblemInvestigator:
"""Expert agent for investigating research problems and defining analytical approaches"""
def __init__(self, rag_system):
self.rag_system = rag_system
self.llm = LLMInterface()
def _run_llm(self, prompt: str) -> Dict[str, Any]:
"""Run LLM with retry mechanism for network errors"""
max_retries = 3
retry_delay = 5 # seconds
for attempt in range(max_retries):
try:
print(f"🔄 LLM attempt {attempt + 1}/{max_retries}")
system_prompt = "You are an expert in single-cell perturbation research. Provide your response in valid JSON format."
response = self.llm.generate(prompt, system_prompt)
content = response.get("content") or ""
# Parse the response content as JSON
try:
return json.loads(content)
except json.JSONDecodeError:
# If direct parsing fails, try to extract JSON from markdown code blocks
import re
json_match = re.search(r'```json\n(.*?)\n```', content, re.DOTALL)
if json_match:
return json.loads(json_match.group(1))
else:
# Return the raw content if JSON parsing fails
return {"content": content, "error": "Failed to parse JSON response"}
except Exception as e:
error_msg = str(e)
if "Connection broken" in error_msg or "InvalidChunkLength" in error_msg:
if attempt < max_retries - 1:
print(f"⚠️ Network error (attempt {attempt + 1}): {error_msg}")
print(f"🔄 Retrying in {retry_delay} seconds...")
import time
time.sleep(retry_delay)
retry_delay *= 2 # 指数退避
continue
else:
print(f"❌ Max retries reached, using fallback response")
# 返回fallback响应
return {
"research_questions": [
"How do perturbations affect gene expression?",
"What are the key regulatory mechanisms?"
],
"analytical_approaches": [
"Differential expression analysis",
"Pathway enrichment analysis"
],
"error": "LLM connection failed, using fallback"
}
else:
# 其他错误直接抛出
raise Exception(f"LLM generation failed: {error_msg}")
# 如果所有重试都失败
return {"content": "LLM generation failed after all retries", "error": "Connection issues"}
def investigate_problem(self, task_description: str, dataset_info: Dict[str, Any],
retrieved_papers: List[Dict[str, Any]]) -> AnalysisResult:
"""
Investigate research problem and define analytical approaches using knowledge base
Args:
task_description: Description of the research task
dataset_info: Dictionary containing dataset metadata
retrieved_papers: List of relevant papers from vector database
Returns:
AnalysisResult with problem investigation
"""
# 使用knowledge base而不是重复搜索
knowledge_items = knowledge_base.search_both_databases(
knowledge_type="papers",
query=task_description,
limit=10
)
# 获取实现指南信息
implementation_items = knowledge_base.search_both_databases(
knowledge_type="implementation_guides",
query=task_description,
limit=5
)
# 获取评估框架信息
evaluation_items = knowledge_base.search_both_databases(
knowledge_type="evaluation_frameworks",
query=task_description,
limit=5
)
# 合并所有论文信息
all_papers = retrieved_papers + [
{
"title": item.content.get("title", ""),
"abstract": item.content.get("content", item.content.get("snippet", "")),
"metadata": item.metadata,
"relevance_score": item.relevance_score
}
for item in knowledge_items
]
# 合并实现指南信息
implementation_guides = [item.content for item in implementation_items]
# 合并评估框架信息
evaluation_frameworks = [item.content for item in evaluation_items]
# Format prompt with task information and retrieved papers
prompt = self._format_prompt_with_implementation_guides(
task_description, dataset_info, all_papers, implementation_guides, evaluation_frameworks
)
# Run investigation (implementation depends on your LLM backend)
investigation_content = self._run_llm(prompt)
return AnalysisResult(
content=investigation_content,
confidence_score=1.0, # 临时设置,后续会由其他模块计算
timestamp=datetime.now(),
metadata={
"agent": "Problem Investigator",
"knowledge_base_usage": {
"papers_count": len(knowledge_items),
"implementation_guides_count": len(implementation_items),
"evaluation_frameworks_count": len(evaluation_items),
"total_retrieved": len(all_papers)
}
}
)
def _format_prompt(self, task_description: str, dataset_info: Dict[str, Any],
retrieved_papers: List[Dict[str, Any]]) -> str:
"""Format prompt for problem investigation"""
papers_context = "\n".join([
f"- {paper.get('title', 'No title')}: {paper.get('abstract', paper.get('content', paper.get('snippet', 'No content')))[:200]}..."
for paper in retrieved_papers[:5]
])
return f"""You are an expert in biological research problem analysis with extensive experience in designing computational solutions for biological applications. Your task is to provide a comprehensive investigation of the research problem and design a solution approach, focusing on problem definition, key challenges, research questions, and analysis methods.
1. Define Research Problem:
- Formally define the problem in biological context
- Identify key biological variables and their relationships
- Specify input-output mappings and biological constraints
- Define evaluation criteria with biological significance
- Establish success metrics with biological validation
2. Analyze Key Challenges:
- Identify biological and technical challenges
- Assess data quality and biological variability
- Evaluate computational complexity and scalability
- Consider biological interpretability requirements
- Address validation and reproducibility concerns
3. Formulate Research Questions:
- Define primary research questions with biological focus
- Identify key hypotheses to be tested
- Specify biological mechanisms to be investigated
- Outline experimental validation requirements
- Establish biological significance criteria
4. Design Analysis Methods:
- Propose computational approaches with biological relevance
- Design validation strategies with biological context
- Specify analysis pipelines with biological interpretation
- Plan experimental validation with biological controls
- Establish reproducibility standards with biological validation
Task Description:
{task_description}
Dataset Information:
{json.dumps(dataset_info, indent=2)}
Relevant Literature:
{papers_context}
Please provide a comprehensive investigation in the following JSON format:
{{
"problem_definition": {{
"formal_definition": {{
"biological_context": "string",
"input_output_mapping": "string",
"biological_constraints": ["string"],
"evaluation_criteria": ["string"],
"success_metrics": ["string"]
}},
"key_variables": {{
"biological": ["string"],
"technical": ["string"],
"relationships": ["string"],
"constraints": ["string"],
"validation_requirements": ["string"]
}},
"scope": {{
"biological_scope": "string",
"technical_scope": "string",
"limitations": ["string"],
"assumptions": ["string"],
"biological_validation": "string"
}}
}},
"key_challenges": {{
"biological": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"biological_considerations": "string"
}},
"technical": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"implementation_requirements": "string"
}},
"data_quality": {{
"issues": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"biological_validation": "string"
}},
"computational": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"resource_requirements": "string"
}},
"interpretability": {{
"requirements": ["string"],
"challenges": ["string"],
"solutions": ["string"],
"validation": "string",
"biological_validation": "string"
}}
}},
"research_questions": {{
"primary": {{
"questions": ["string"],
"hypotheses": ["string"],
"biological_significance": "string",
"validation_approach": "string",
"expected_outcomes": ["string"]
}},
"secondary": {{
"questions": ["string"],
"hypotheses": ["string"],
"biological_significance": "string",
"validation_approach": "string",
"expected_outcomes": ["string"]
}},
"biological_mechanisms": {{
"mechanisms": ["string"],
"investigation_approach": "string",
"validation_methods": ["string"],
"expected_insights": ["string"],
"biological_validation": "string"
}},
"experimental_validation": {{
"requirements": ["string"],
"methods": ["string"],
"controls": ["string"],
"metrics": ["string"],
"biological_validation": "string"
}}
}},
"analysis_methods": {{
"computational_approaches": {{
"methods": ["string"],
"rationale": "string",
"implementation": "string",
"validation": "string",
"biological_validation": "string"
}},
"validation_strategies": {{
"strategies": ["string"],
"rationale": "string",
"implementation": "string",
"metrics": ["string"],
"biological_validation": "string"
}},
"analysis_pipelines": {{
"pipelines": ["string"],
"components": ["string"],
"workflow": "string",
"validation": "string",
"biological_interpretation": "string"
}},
"experimental_validation": {{
"methods": ["string"],
"controls": ["string"],
"metrics": ["string"],
"analysis": "string",
"biological_validation": "string"
}},
"reproducibility": {{
"standards": ["string"],
"requirements": ["string"],
"validation": "string",
"documentation": "string",
"biological_validation": "string"
}}
}}
}}"""
def _format_prompt_with_implementation_guides(self, task_description: str, dataset_info: Dict[str, Any],
papers: List[Dict[str, Any]], implementation_guides: List[Dict[str, Any]],
evaluation_frameworks: List[Dict[str, Any]]) -> str:
"""Format prompt for problem investigation with decision support"""
papers_context = "\n".join([
f"- {paper.get('title', 'No title')}: {paper.get('abstract', paper.get('content', paper.get('snippet', 'No content')))[:200]}..."
for paper in papers[:5]
])
return f"""You are an expert in biological research problem analysis with extensive experience in designing computational solutions for biological applications. Your task is to provide a comprehensive investigation of the research problem and design a solution approach, focusing on problem definition, key challenges, research questions, and analysis methods.
1. Define Research Problem:
- Formally define the problem in biological context
- Identify key biological variables and their relationships
- Specify input-output mappings and biological constraints
- Define evaluation criteria with biological significance
- Establish success metrics with biological validation
2. Analyze Key Challenges:
- Identify biological and technical challenges
- Assess data quality and biological variability
- Evaluate computational complexity and scalability
- Consider biological interpretability requirements
- Address validation and reproducibility concerns
3. Formulate Research Questions:
- Define primary research questions with biological focus
- Identify key hypotheses to be tested
- Specify biological mechanisms to be investigated
- Outline experimental validation requirements
- Establish biological significance criteria
4. Design Analysis Methods:
- Propose computational approaches with biological relevance
- Design validation strategies with biological context
- Specify analysis pipelines with biological interpretation
- Plan experimental validation with biological controls
- Establish reproducibility standards with biological validation
Task Description:
{task_description}
Dataset Information:
{json.dumps(dataset_info, indent=2)}
Relevant Literature:
{papers_context}
Implementation Guides:
{json.dumps(implementation_guides, indent=2)}
Evaluation Frameworks:
{json.dumps(evaluation_frameworks, indent=2)}
Please provide a comprehensive investigation in the following JSON format:
{{
"problem_definition": {{
"formal_definition": {{
"biological_context": "string",
"input_output_mapping": "string",
"biological_constraints": ["string"],
"evaluation_criteria": ["string"],
"success_metrics": ["string"]
}},
"key_variables": {{
"biological": ["string"],
"technical": ["string"],
"relationships": ["string"],
"constraints": ["string"],
"validation_requirements": ["string"]
}},
"scope": {{
"biological_scope": "string",
"technical_scope": "string",
"limitations": ["string"],
"assumptions": ["string"],
"biological_validation": "string"
}}
}},
"key_challenges": {{
"biological": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"biological_considerations": "string"
}},
"technical": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"implementation_requirements": "string"
}},
"data_quality": {{
"issues": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"biological_validation": "string"
}},
"computational": {{
"challenges": ["string"],
"impact": "string",
"mitigation": ["string"],
"validation": "string",
"resource_requirements": "string"
}},
"interpretability": {{
"requirements": ["string"],
"challenges": ["string"],
"solutions": ["string"],
"validation": "string",
"biological_validation": "string"
}}
}},
"research_questions": {{
"primary": {{
"questions": ["string"],
"hypotheses": ["string"],
"biological_significance": "string",
"validation_approach": "string",
"expected_outcomes": ["string"]
}},
"secondary": {{
"questions": ["string"],
"hypotheses": ["string"],
"biological_significance": "string",
"validation_approach": "string",
"expected_outcomes": ["string"]
}},
"biological_mechanisms": {{
"mechanisms": ["string"],
"investigation_approach": "string",
"validation_methods": ["string"],
"expected_insights": ["string"],
"biological_validation": "string"
}},
"experimental_validation": {{
"requirements": ["string"],
"methods": ["string"],
"controls": ["string"],
"metrics": ["string"],
"biological_validation": "string"
}}
}},
"analysis_methods": {{
"computational_approaches": {{
"methods": ["string"],
"rationale": "string",
"implementation": "string",
"validation": "string",
"biological_validation": "string"
}},
"validation_strategies": {{
"strategies": ["string"],
"rationale": "string",
"implementation": "string",
"metrics": ["string"],
"biological_validation": "string"
}},
"analysis_pipelines": {{
"pipelines": ["string"],
"components": ["string"],
"workflow": "string",
"validation": "string",
"biological_interpretation": "string"
}},
"experimental_validation": {{
"methods": ["string"],
"controls": ["string"],
"metrics": ["string"],
"analysis": "string",
"biological_validation": "string"
}},
"reproducibility": {{
"standards": ["string"],
"requirements": ["string"],
"validation": "string",
"documentation": "string",
"biological_validation": "string"
}}
}}
}}"""