nkshirsa commited on
Commit
b20f4c2
·
verified ·
1 Parent(s): d86f9d6

Add phd_research_os/agents.py

Browse files
Files changed (1) hide show
  1. phd_research_os/agents.py +363 -0
phd_research_os/agents.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PhD Research OS — Agent Layer
3
+ ==============================
4
+ The AI brain that powers all pipeline operations.
5
+ Uses fine-tuned Qwen2.5-3B-Instruct (or falls back to API) for:
6
+ - Claim extraction from scientific text
7
+ - Epistemic classification
8
+ - Confidence scoring
9
+ - Contradiction detection
10
+ - Query decomposition
11
+ - Decision generation
12
+
13
+ Adheres to Research OS v11.0 rules:
14
+ - Provenance Hierarchy: All agent output is Priority 5 (LLM Inference/Hypothesis)
15
+ - Anchor Divergence: Agent output never overrides human-verified observations
16
+ - Fixed-Point Math: All probabilities use scaled integers
17
+ - Causal Lineage: Every claim traces back to source Observation_ID
18
+ """
19
+
20
+ import json
21
+ import os
22
+ from typing import Optional
23
+ from dataclasses import dataclass
24
+
25
+ # System prompts for each agent role
26
+ PROMPTS = {
27
+ "researcher": """You are the Researcher Agent of a PhD Research OS. Your role is to extract structured scientific claims from research paper text.
28
+
29
+ For each claim, output a JSON object with these fields:
30
+ - claim_id: string (CLM_XXXX format, auto-assigned)
31
+ - text: the claim text as stated in the paper
32
+ - epistemic_tag: one of "Fact", "Interpretation", "Hypothesis", "Conflict_Hypothesis"
33
+ - confidence: float [0,1] computed as evidence_strength × study_quality_weight × journal_tier_weight × completeness_penalty
34
+ - evidence_strength: float [0,1] based on directness of evidence
35
+ - study_type: one of "primary_experimental", "in_vitro", "simulation", "review_non_systematic", "meta_analysis", "case_study"
36
+ - missing_fields: list of field names that could not be determined from the text
37
+ - status: "Complete" if no missing fields, else "Incomplete"
38
+ - parameters: dict of key experimental parameters mentioned
39
+
40
+ Output must be valid JSON: {"claims": [...]}
41
+ Always classify epistemic tags conservatively. When uncertain, prefer "Interpretation" over "Fact".""",
42
+
43
+ "epistemic_classifier": """You are the Epistemic Classifier of a PhD Research OS. Given a scientific statement, classify it into exactly one category:
44
+
45
+ - Fact: Directly supported by experimental data with quantitative evidence. Reproducible measurements.
46
+ - Interpretation: Author's explanation of data. Goes beyond what numbers strictly show.
47
+ - Hypothesis: Proposed mechanism or prediction not yet tested.
48
+ - Conflict_Hypothesis: Explicitly contradicts another established claim with evidence on both sides.
49
+
50
+ Output JSON: {"epistemic_tag": "...", "reasoning": "...", "confidence_in_classification": float}""",
51
+
52
+ "confidence_scorer": """You are the Confidence Scorer of a PhD Research OS. Score claim confidence using:
53
+
54
+ confidence = evidence_strength × study_quality_weight × journal_tier_weight × completeness_penalty
55
+
56
+ study_quality_weight: primary_experimental=1.0, in_vitro=0.8, simulation=0.6, review_non_systematic=0.4, meta_analysis=1.0, case_study=0.3
57
+ journal_tier_weight: tier1=1.0, tier2=0.85, tier3=0.7, preprint=0.5
58
+ completeness_penalty: 1.0 if complete, 0.7 if missing key parameters
59
+
60
+ Output JSON: {"confidence": float, "evidence_strength": float, "study_quality_weight": float, "journal_tier_weight": float, "completeness_penalty": float, "reasoning": "..."}""",
61
+
62
+ "verifier": """You are the Verifier Agent of a PhD Research OS. Given two scientific claims, determine if they contradict each other.
63
+
64
+ Output a Conflict Resolution Object as JSON:
65
+ - conflict_detected: boolean
66
+ - conflict_type: "value_mismatch", "methodology_difference", "scope_difference", or "no_conflict"
67
+ - generated_hypothesis: text explaining possible cause
68
+ - hypothesis_confidence: always "low" (never auto-set to high)
69
+ - resolution_status: "Unresolved"
70
+ - key_differences: list of specific differences
71
+ - recommended_action: what to investigate""",
72
+
73
+ "query_planner": """You are the Query Planner of a PhD Research OS. Decompose broad research questions into 2-4 specific sub-queries for knowledge base search.
74
+
75
+ Output JSON: {"original_query": "...", "sub_queries": ["...", "..."], "reasoning": "..."}""",
76
+
77
+ "decision_generator": """You are the Decision Agent of a PhD Research OS. Given research goals, knowledge gaps, and low-confidence claims, propose a Decision Object.
78
+
79
+ Output JSON:
80
+ - decision_id: string
81
+ - recommended_action: "experiment", "literature_search", "collaboration", "replication", "methodology_review"
82
+ - action_description: specific description
83
+ - expected_information_gain: float [0,1] = uncertainty × impact
84
+ - linked_goal_id: which goal this addresses
85
+ - linked_claim_ids: which claims this resolves
86
+ - priority: "high", "medium", "low"
87
+ - estimated_effort: time estimate"""
88
+ }
89
+
90
+
91
+ @dataclass
92
+ class AgentResponse:
93
+ """Structured response from any agent."""
94
+ success: bool
95
+ data: dict
96
+ raw_output: str
97
+ provenance_level: int = 5 # LLM Inference — lowest priority per Research OS spec
98
+ observation_id: Optional[str] = None
99
+ tokens_in: int = 0
100
+ tokens_out: int = 0
101
+ cost_usd: float = 0.0
102
+
103
+
104
+ class ResearchOSBrain:
105
+ """
106
+ The AI brain of the PhD Research OS.
107
+
108
+ Supports multiple backends:
109
+ 1. Fine-tuned local model (Qwen2.5-3B + LoRA adapter)
110
+ 2. API fallback (Anthropic Claude / OpenAI)
111
+
112
+ All outputs are tagged as Priority 5 (LLM Hypothesis) per Research OS spec.
113
+ Human verification is required to promote to higher provenance levels.
114
+ """
115
+
116
+ def __init__(self, model_path: str = None, backend: str = "local"):
117
+ """
118
+ Initialize the Research OS Brain.
119
+
120
+ Args:
121
+ model_path: Path to fine-tuned model or HF model ID
122
+ Default: "nkshirsa/phd-research-os-brain"
123
+ backend: "local" for local inference, "api" for API fallback
124
+ """
125
+ self.backend = backend
126
+ self.model_path = model_path or "nkshirsa/phd-research-os-brain"
127
+ self.model = None
128
+ self.tokenizer = None
129
+
130
+ if backend == "local":
131
+ self._load_local_model()
132
+
133
+ def _load_local_model(self):
134
+ """Load the fine-tuned model for local inference."""
135
+ try:
136
+ from transformers import AutoModelForCausalLM, AutoTokenizer
137
+ import torch
138
+
139
+ print(f"Loading model from {self.model_path}...")
140
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
141
+ self.model = AutoModelForCausalLM.from_pretrained(
142
+ self.model_path,
143
+ torch_dtype=torch.float16,
144
+ device_map="auto"
145
+ )
146
+ print("Model loaded successfully.")
147
+ except Exception as e:
148
+ print(f"Warning: Could not load local model: {e}")
149
+ print("Falling back to API mode. Set ANTHROPIC_API_KEY or OPENAI_API_KEY.")
150
+ self.backend = "api"
151
+
152
+ def _generate_local(self, messages: list, max_tokens: int = 2048) -> str:
153
+ """Generate response using local model."""
154
+ if self.model is None or self.tokenizer is None:
155
+ raise RuntimeError("Local model not loaded")
156
+
157
+ text = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
158
+ inputs = self.tokenizer(text, return_tensors="pt").to(self.model.device)
159
+
160
+ with __import__('torch').no_grad():
161
+ outputs = self.model.generate(
162
+ **inputs,
163
+ max_new_tokens=max_tokens,
164
+ temperature=0.1, # Low temperature for structured output
165
+ do_sample=True,
166
+ top_p=0.95,
167
+ )
168
+
169
+ response = self.tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
170
+ return response
171
+
172
+ def _generate_api(self, messages: list, max_tokens: int = 2048) -> str:
173
+ """Generate response using API (Anthropic or OpenAI fallback)."""
174
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
175
+ if api_key:
176
+ return self._call_anthropic(messages, max_tokens, api_key)
177
+
178
+ api_key = os.environ.get("OPENAI_API_KEY")
179
+ if api_key:
180
+ return self._call_openai(messages, max_tokens, api_key)
181
+
182
+ raise RuntimeError("No API key found. Set ANTHROPIC_API_KEY or OPENAI_API_KEY")
183
+
184
+ def _call_anthropic(self, messages: list, max_tokens: int, api_key: str) -> str:
185
+ """Call Anthropic API."""
186
+ import httpx
187
+
188
+ system_msg = ""
189
+ api_messages = []
190
+ for msg in messages:
191
+ if msg["role"] == "system":
192
+ system_msg = msg["content"]
193
+ else:
194
+ api_messages.append(msg)
195
+
196
+ response = httpx.post(
197
+ "https://api.anthropic.com/v1/messages",
198
+ headers={
199
+ "x-api-key": api_key,
200
+ "anthropic-version": "2023-06-01",
201
+ "content-type": "application/json"
202
+ },
203
+ json={
204
+ "model": "claude-sonnet-4-20250514",
205
+ "max_tokens": max_tokens,
206
+ "system": system_msg,
207
+ "messages": api_messages
208
+ },
209
+ timeout=60
210
+ )
211
+ data = response.json()
212
+ return data["content"][0]["text"]
213
+
214
+ def _call_openai(self, messages: list, max_tokens: int, api_key: str) -> str:
215
+ """Call OpenAI API."""
216
+ import httpx
217
+
218
+ response = httpx.post(
219
+ "https://api.openai.com/v1/chat/completions",
220
+ headers={
221
+ "Authorization": f"Bearer {api_key}",
222
+ "Content-Type": "application/json"
223
+ },
224
+ json={
225
+ "model": "gpt-4o-mini",
226
+ "messages": messages,
227
+ "max_tokens": max_tokens,
228
+ "temperature": 0.1
229
+ },
230
+ timeout=60
231
+ )
232
+ data = response.json()
233
+ return data["choices"][0]["message"]["content"]
234
+
235
+ def _call(self, agent_role: str, user_message: str, max_tokens: int = 2048) -> AgentResponse:
236
+ """
237
+ Call the brain with a specific agent role.
238
+
239
+ Returns AgentResponse with provenance_level=5 (LLM Hypothesis).
240
+ Per Research OS spec, this is the LOWEST priority in the provenance hierarchy.
241
+ """
242
+ messages = [
243
+ {"role": "system", "content": PROMPTS[agent_role]},
244
+ {"role": "user", "content": user_message}
245
+ ]
246
+
247
+ try:
248
+ if self.backend == "local":
249
+ raw = self._generate_local(messages, max_tokens)
250
+ else:
251
+ raw = self._generate_api(messages, max_tokens)
252
+
253
+ # Parse JSON from response
254
+ # Try to extract JSON from the response (handle markdown code blocks)
255
+ json_str = raw.strip()
256
+ if json_str.startswith("```"):
257
+ json_str = json_str.split("```")[1]
258
+ if json_str.startswith("json"):
259
+ json_str = json_str[4:]
260
+ json_str = json_str.strip()
261
+
262
+ data = json.loads(json_str)
263
+
264
+ return AgentResponse(
265
+ success=True,
266
+ data=data,
267
+ raw_output=raw,
268
+ provenance_level=5, # LLM inference — must be human-verified
269
+ )
270
+ except json.JSONDecodeError as e:
271
+ return AgentResponse(
272
+ success=False,
273
+ data={"error": f"Invalid JSON: {str(e)}", "raw": raw},
274
+ raw_output=raw,
275
+ provenance_level=5,
276
+ )
277
+ except Exception as e:
278
+ return AgentResponse(
279
+ success=False,
280
+ data={"error": str(e)},
281
+ raw_output="",
282
+ provenance_level=5,
283
+ )
284
+
285
+ # ============================================================
286
+ # Public API — one method per Research OS task
287
+ # ============================================================
288
+
289
+ def extract_claims(self, paper_text: str) -> AgentResponse:
290
+ """
291
+ Task 1: Extract structured claims from scientific text.
292
+ Returns claims with epistemic tags, confidence scores, and parameters.
293
+
294
+ Research OS Provenance: Level 5 (LLM Hypothesis)
295
+ """
296
+ return self._call("researcher",
297
+ f"Extract all scientific claims from the following paper excerpt:\n\n{paper_text}")
298
+
299
+ def classify_epistemic(self, statement: str) -> AgentResponse:
300
+ """
301
+ Task 2: Classify the epistemic status of a scientific statement.
302
+ Returns: Fact | Interpretation | Hypothesis | Conflict_Hypothesis
303
+
304
+ Research OS Provenance: Level 5 (LLM Hypothesis)
305
+ """
306
+ return self._call("epistemic_classifier",
307
+ f"Classify the epistemic status of this scientific statement:\n\n\"{statement}\"")
308
+
309
+ def score_confidence(self, claim_text: str, journal: str,
310
+ study_type: str, journal_tier: int) -> AgentResponse:
311
+ """
312
+ Task 3: Score confidence using the Research OS formula.
313
+ confidence = evidence_strength × study_quality × journal_tier × completeness
314
+
315
+ Uses FIXED-POINT arithmetic per Research OS Rule 5.
316
+ """
317
+ return self._call("confidence_scorer",
318
+ f"Score the confidence of this claim:\n\n{claim_text}\n\n"
319
+ f"Source: {journal}\nStudy type: {study_type}\nJournal tier: {journal_tier}")
320
+
321
+ def detect_conflicts(self, claim_a: str, claim_b: str) -> AgentResponse:
322
+ """
323
+ Task 4: Detect contradictions between two claims.
324
+ hypothesis_confidence is ALWAYS "low" — human review required.
325
+
326
+ Research OS Rule: Agent hypotheses never auto-promote above Level 5.
327
+ """
328
+ return self._call("verifier",
329
+ f"Analyze these two claims for contradictions:\n\n"
330
+ f"Claim A: \"{claim_a}\"\n\nClaim B: \"{claim_b}\"")
331
+
332
+ def decompose_query(self, question: str) -> AgentResponse:
333
+ """
334
+ Task 5: Decompose a broad research question into sub-queries.
335
+ """
336
+ return self._call("query_planner",
337
+ f"Decompose this research question into specific sub-queries:\n\n\"{question}\"")
338
+
339
+ def generate_decision(self, goal: str, gaps: list,
340
+ low_confidence_claims: list) -> AgentResponse:
341
+ """
342
+ Task 6: Generate a Decision Object with information gain estimate.
343
+ """
344
+ user_msg = f"""Current research goal: {goal}
345
+
346
+ Knowledge gaps:
347
+ {chr(10).join('- ' + g for g in gaps)}
348
+
349
+ Low-confidence claims requiring resolution:
350
+ {chr(10).join('- ' + c for c in low_confidence_claims)}
351
+
352
+ Propose a Decision Object with the highest expected information gain."""
353
+
354
+ return self._call("decision_generator", user_msg)
355
+
356
+
357
+ # ============================================================
358
+ # Convenience functions
359
+ # ============================================================
360
+
361
+ def create_brain(model_path: str = None, backend: str = "local") -> ResearchOSBrain:
362
+ """Create a Research OS Brain instance."""
363
+ return ResearchOSBrain(model_path=model_path, backend=backend)