GuXiaopeng commited on
Commit
2e23d9f
·
verified ·
1 Parent(s): 717a03f

Update core/pipeline_agent.py

Browse files
Files changed (1) hide show
  1. core/pipeline_agent.py +213 -334
core/pipeline_agent.py CHANGED
@@ -14,7 +14,7 @@ import sys
14
  import logging
15
  from tenacity import retry, stop_after_attempt, wait_random_exponential, wait_exponential, retry_if_exception_type
16
 
17
- # 配置全局日志
18
  logging.basicConfig(
19
  level=logging.INFO,
20
  format="%(asctime)s [%(levelname)s] %(message)s",
@@ -27,19 +27,8 @@ try:
27
  except ImportError:
28
  LANGDETECT_AVAILABLE = False
29
 
30
- from app_config import APP_CONFIG
31
-
32
-
33
- def count_words_adaptive(text, lang_hint="en"):
34
- """语言感知的字数/字符数统计"""
35
- if not text:
36
- return 0
37
- if lang_hint in ["zh", "ru", "kk"]:
38
- chars = re.findall(r'[\u4e00-\u9fff\u0400-\u052F]', text)
39
- return len(chars)
40
- else:
41
- return len(text.split())
42
-
43
 
44
  class SSciPipelineAgent:
45
  def __init__(self, ds_key, s2_key=""):
@@ -52,7 +41,7 @@ class SSciPipelineAgent:
52
  self.openalex_key = st.secrets.get("OA_API_KEY", "")
53
  except:
54
  self.openalex_key = os.environ.get("OA_API_KEY", "")
55
-
56
  self.ds_calls = 0
57
  self.oa_calls = 0
58
  self.s2_calls = 0
@@ -61,24 +50,24 @@ class SSciPipelineAgent:
61
  self.citation_map = {}
62
  self.used_citations = set()
63
  self.lock = threading.RLock()
64
-
65
  self.lit_target_papers = APP_CONFIG["lit_target_papers"]
66
  self.lit_per_page = APP_CONFIG["lit_per_page"]
67
  self.lit_max_workers = APP_CONFIG["lit_max_workers"]
68
  self.lit_max_page_batches = APP_CONFIG["lit_max_page_batches"]
69
  self.chunk_words_default = APP_CONFIG["chunk_words_default"]
70
  self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]
71
-
72
  self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]
73
  self.openalex_api_url = APP_CONFIG["openalex_api_url"]
74
  self.s2_api_url = APP_CONFIG["s2_api_url"]
75
-
76
  self.global_memory = {
77
  "hypotheses": "", "variables": "", "model_summary": "",
78
  "method_summary": "", "abstract_anchor": "", "conclusion_anchor": "",
79
  "core_golden_metadata": []
80
  }
81
-
82
  try:
83
  self.tokenizer = tiktoken.get_encoding("cl100k_base")
84
  except:
@@ -86,28 +75,34 @@ class SSciPipelineAgent:
86
 
87
  def _extract_json_from_text(self, text):
88
  """无敌 JSON 提取器:外科手术式提取,彻底无视大模型废话前缀和 Markdown 包装"""
89
- if not text:
90
- return None
91
-
92
  text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
93
-
 
 
 
 
 
94
  start_dict = text.find('{')
95
  end_dict = text.rfind('}')
96
  start_list = text.find('[')
97
  end_list = text.rfind(']')
98
-
99
  dict_len = end_dict - start_dict if start_dict != -1 and end_dict != -1 else -1
100
  list_len = end_list - start_list if start_list != -1 and end_list != -1 else -1
101
-
102
  if dict_len == -1 and list_len == -1:
103
  return None
104
-
105
  try:
 
106
  if dict_len > list_len:
107
- json_str = text[start_dict:end_dict + 1]
108
  return json.loads(json_str)
109
  else:
110
- json_str = text[start_list:end_list + 1]
111
  return json.loads(json_str)
112
  except Exception as e:
113
  logging.error(f"❌ JSON 外科提取彻底失败: {e} | 原文片段: {text[:200]}...")
@@ -125,8 +120,7 @@ class SSciPipelineAgent:
125
  }
126
 
127
  def load_state(self, state_dict):
128
- if not state_dict:
129
- return
130
  with self.lock:
131
  self.ds_calls = state_dict.get("ds_calls", 0)
132
  self.oa_calls = state_dict.get("oa_calls", 0)
@@ -140,249 +134,204 @@ class SSciPipelineAgent:
140
  return max(2, int(target_words / words_per_para))
141
 
142
  def _translate_text(self, text, target_lang, max_tokens=2000):
143
- if not text.strip():
144
- return ""
145
  sys_prompt = f"Translate the following text into {target_lang}. Preserve all formatting, line breaks, and [CITE-XX] tags exactly. Output ONLY the translation."
146
  return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2, model_name="deepseek-chat")
147
 
148
- @retry(
149
- stop=stop_after_attempt(3),
150
- wait=wait_exponential(multiplier=1, min=2, max=10),
151
- retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError))
152
- )
153
  def _requests_get_with_retry(self, url, headers=None, params=None, timeout=15):
154
  resp = requests.get(url, headers=headers, params=params, timeout=timeout)
155
  if resp.status_code == 429:
156
  logging.warning(f"⚠️ [API 限流] 触发 429,当前线程进入随机休眠退避。URL: {url}")
157
  resp.raise_for_status()
 
 
 
 
 
158
  if resp.status_code != 200:
159
  logging.error(f"❌ [API 错误] 状态码: {resp.status_code}, 响应: {resp.text}")
160
  resp.raise_for_status()
161
  return resp
162
 
163
  def _is_english_dominant(self, text):
164
- if not text:
165
- return False
166
  if LANGDETECT_AVAILABLE:
167
- try:
168
- return detect(text) == 'en'
169
- except:
170
- pass
171
  alpha_chars = sum(1 for c in str(text) if c.isalpha())
172
- if alpha_chars == 0:
173
- return False
174
  return (len(re.findall(r'[a-zA-Z]', str(text))) / alpha_chars) > 0.8
175
 
176
  def _extract_memory_from_text(self, text, section_name):
177
  lower_sec = section_name.lower()
178
  if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):
179
  hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)
180
- if hypo_matches:
181
- self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])
182
  if any(kw in lower_sec for kw in ["method", "measure", "variable"]):
183
  var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)
184
- if var_matches:
185
- self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])
186
  if "model" in lower_sec or "figure" in lower_sec:
187
  model_match = re.search(r'(Figure\s*\d+[^\.]+\.)', text, re.IGNORECASE)
188
- if model_match:
189
- self.global_memory["model_summary"] = model_match.group(1)
190
  if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):
191
  method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)
192
- if method_match:
193
- self.global_memory["method_summary"] = method_match.group(1)
194
 
195
  def _count_tokens(self, text):
196
  return len(self.tokenizer.encode(text))
197
 
198
  def _truncate_context(self, text, max_tokens):
199
  tokens = self.tokenizer.encode(text)
200
- if len(tokens) <= max_tokens:
201
- return text
202
  return self.tokenizer.decode(tokens[:max_tokens])
203
 
204
  def _build_memory_context(self, section_name="", max_tokens=2500):
205
  memory_parts = []
206
- if self.global_memory["abstract_anchor"]:
207
- memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")
208
- if self.global_memory["conclusion_anchor"]:
209
- memory_parts.append(f"【PAPER ANCHOR - EXPECTED CONCLUSION】\n{self.global_memory['conclusion_anchor']}")
210
- if self.global_memory["hypotheses"]:
211
- memory_parts.append(f"【ESTABLISHED HYPOTHESES】\n{self.global_memory['hypotheses']}")
212
- if self.global_memory["variables"]:
213
- memory_parts.append(f"【CORE CONSTRUCT DEFINITIONS】\n{self.global_memory['variables']}")
214
- if self.global_memory["model_summary"]:
215
- memory_parts.append(f"【RESEARCH MODEL】\n{self.global_memory['model_summary']}")
216
- if self.global_memory["method_summary"]:
217
- memory_parts.append(f"【METHODOLOGICAL SUMMARY】\n{self.global_memory['method_summary']}")
218
-
219
  golden_meta = self.global_memory.get("core_golden_metadata", [])
220
  if isinstance(golden_meta, list) and section_name:
221
  lower_sec = section_name.lower()
222
  injected_data = []
223
-
224
  if any(kw in lower_sec for kw in ["introduction", "background"]):
225
  for p in golden_meta:
226
- if isinstance(p, dict) and p.get('future_gaps'):
227
- injected_data.append(f"[{p.get('title', 'Ref')}] Future Gaps: {p['future_gaps']}")
228
- if injected_data:
229
- memory_parts.append("【TARGETED INJECTION: CORE LITERATURE GAPS (FOR RESEARCH GAP FORMULATION)】\n" + "\n".join(injected_data))
230
-
231
  elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
232
  for p in golden_meta:
233
  if isinstance(p, dict):
234
- if p.get('theoretical_lens'):
235
- injected_data.append(f"[{p.get('title', 'Ref')}] Theoretical Lens: {p['theoretical_lens']}")
236
- if p.get('causal_pathways'):
237
- injected_data.append(f"[{p.get('title', 'Ref')}] Pathways: {p['causal_pathways']}")
238
- if injected_data:
239
- memory_parts.append("【TARGETED INJECTION: CORE LITERATURE THEORIES & PATHWAYS (USE FOR HYPOTHESIS DEDUCTION)】\n" + "\n".join(injected_data))
240
-
241
  elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
242
  for p in golden_meta:
243
- if isinstance(p, dict) and p.get('variables_and_measurements'):
244
- injected_data.append(f"[{p.get('title', 'Ref')}] Measurements: {p['variables_and_measurements']}")
245
- if injected_data:
246
- memory_parts.append("【TARGETED INJECTION: CORE LITERATURE MEASUREMENTS (USE FOR SCALE ADAPTATION DEFENSE)】\n" + "\n".join(injected_data))
247
-
248
  elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication", "result", "analysis"]):
249
  for p in golden_meta:
250
- if isinstance(p, dict) and p.get('causal_pathways'):
251
- injected_data.append(f"[{p.get('title', 'Ref')}] Confirmed Pathways: {p['causal_pathways']}")
252
- if injected_data:
253
- memory_parts.append("【TARGETED INJECTION: CORE LITERATURE FINDINGS (COMPARE OUR RESULTS AGAINST THESE)】\n" + "\n".join(injected_data))
254
 
255
  full = "\n\n".join(memory_parts)
256
- if self._count_tokens(full) > max_tokens:
257
- return self._truncate_context(full, max_tokens)
258
  return full
259
 
260
  def call_deepseek(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3, model_name="deepseek-reasoner"):
261
  logging.info(f"🚀 [DeepSeek API] 准备调用 {model_name}, 提示词预计 Tokens: {self._count_tokens(user_prompt)}")
262
  for attempt in range(3):
263
- with self.lock:
264
- self.ds_calls += 1
265
  current_model = model_name
266
  if attempt == 2 and model_name == "deepseek-reasoner":
267
  current_model = "deepseek-chat"
268
- temp = 0.3
269
  logging.warning("⚠️ [算力降级] Reasoner 节点拥挤,强制降级为 deepseek-chat 执行本节点!")
270
-
271
  payload = {
272
- "model": current_model,
273
- "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
274
- "max_tokens": max_tokens,
275
- "stream": True
276
  }
277
  if current_model != "deepseek-reasoner":
278
  payload["temperature"] = temp
279
-
280
  full_content = ""
281
  try:
282
  with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 180)) as response:
283
  if response.status_code != 200:
284
  error_msg = f"DeepSeek API 拒绝访问 (状态码: {response.status_code})。详情: {response.text}"
285
  logging.error(f"❌ 尝试 {attempt+1}/3 失败: {error_msg}")
286
- if attempt == 2:
287
  st.toast(f"❌ API 彻底熔断: {error_msg}", icon="🚨")
288
  raise requests.exceptions.HTTPError(error_msg)
289
- time.sleep(3 ** attempt + random.uniform(0, 1))
290
  continue
291
-
292
  for line in response.iter_lines():
293
  if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':
294
  try:
295
  delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})
296
  content = delta.get('content', '')
297
- if content:
298
- full_content += content
299
- except Exception:
300
- pass
301
  return full_content.strip()
302
  except Exception as e:
303
  logging.error(f"❌ [网络异常] 尝试 {attempt+1}/3 失败: {e}")
304
- if attempt == 2:
305
- raise e
306
- time.sleep(3 ** attempt + random.uniform(0, 1))
307
 
308
  def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name="deepseek-reasoner"):
309
  temp = 0.3 if model_name == "deepseek-chat" else 0.2
310
  for attempt in range(3):
311
- with self.lock:
312
- self.ds_calls += 1
313
  current_model = model_name
314
  if attempt >= 1 and model_name == "deepseek-reasoner":
315
  current_model = "deepseek-chat"
316
- temp = 0.3
317
  logging.warning(f"⚠️ [流式降级] {model_name} 连接失败,强制切换至 deepseek-chat。")
318
 
319
  payload = {
320
- "model": current_model,
321
- "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
322
- "max_tokens": max_tokens,
323
  "stream": True
324
  }
325
  if current_model != "deepseek-reasoner":
326
  payload["temperature"] = temp
327
-
328
  in_think_block = False
329
  try:
330
  with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 300)) as response:
331
  if response.status_code != 200:
332
  logging.error(f"❌ [流式 API 错误] 状态码: {response.status_code}, 响应: {response.text}")
333
- if attempt == 2:
334
- response.raise_for_status()
335
- time.sleep(2 + random.uniform(0, 1))
336
- continue
337
 
338
  for line in response.iter_lines():
339
  if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':
340
  try:
341
  delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})
342
  content = delta.get('content', '')
343
- if not content:
344
- continue
345
-
346
  if '<think>' in content:
347
  in_think_block = True
348
  content = content.replace('<think>', '')
349
  if '</think>' in content:
350
  in_think_block = False
351
  content = content.replace('</think>', '')
352
- if not content:
353
- continue
354
 
355
  if not in_think_block and content:
356
  yield content
357
- except Exception:
358
- pass
359
- return
360
- except GeneratorExit:
361
- raise
362
- except (requests.exceptions.ConnectionError, ConnectionResetError) as e:
363
- logging.error(f"❌ [流式连接重置] 尝试 {attempt+1}/3 异常: {e}")
364
- if attempt == 2:
365
- raise
366
- time.sleep(2 ** attempt + random.uniform(0, 1))
367
- continue
368
  except Exception as e:
369
  logging.error(f"❌ [流式中断] 尝试 {attempt+1}/3 异常: {e}")
370
- if attempt == 2:
371
- raise
372
- time.sleep(2 + random.uniform(0, 1))
373
 
374
  def extract_document_structure(self, text, paper_type="empirical"):
375
- fallbacks = {"empirical": ["Introduction", "Literature Review", "Methodology", "Results", "Discussion", "Conclusion"],
376
- "generic": ["Introduction", "Main Body", "Discussion", "Conclusion"]}
377
  default_sections = fallbacks.get(paper_type, fallbacks["generic"])
378
- if not text or len(text.strip()) < 100:
379
- return default_sections
380
 
381
- max_safe_chars = 50000
382
  if len(text) > max_safe_chars:
383
  sampled_text = text[:int(max_safe_chars * 0.7)] + "\n\n...[CONTENT OMITTED]...\n\n" + text[-int(max_safe_chars * 0.3):]
384
- else:
385
- sampled_text = text
386
 
387
  sys_prompt = "You are an expert academic editor."
388
  user_prompt = f"Analyze the following academic text and extract its core structural headings (top-level only). Rules: 1. Ignore subheadings. 2. Ignore front/back matter. 3. Output exact heading names separated by ' || '. Text snippet:\n{sampled_text}"
@@ -393,13 +342,10 @@ class SSciPipelineAgent:
393
  clean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()
394
  if '||' in clean_resp:
395
  headings = [h.strip() for h in clean_resp.split('||') if h.strip()]
396
- if len(headings) >= 3:
397
- return headings
398
  list_matches = re.findall(r'^(?:\d+\.|[A-Z]\.)\s*(.+)$', clean_resp, re.MULTILINE)
399
- if list_matches and len(list_matches) >= 3:
400
- return [m.strip() for m in list_matches]
401
- except Exception:
402
- continue
403
  return default_sections
404
 
405
  def reverse_engineer_section(self, reference_text, section_name):
@@ -414,47 +360,56 @@ class SSciPipelineAgent:
414
  return {"tone_and_style": "objective academic tone", "reporting_structure": "standard empirical reporting", "few_shot_snippet": ""}
415
 
416
  def parse_user_core_literature(self, user_lit_text):
417
- if not user_lit_text.strip():
418
- return ""
419
- sys_prompt = "You are an elite academic metadata extractor. First summarize each paper in 2-3 sentences, then extract metadata."
420
  user_prompt = f"""
421
  Analyze the following raw text extracted from user-uploaded core academic PDFs. There may be multiple papers.
422
  <RAW_TEXT>
423
- {user_lit_text[:20000]}
424
  </RAW_TEXT>
425
 
426
- For each paper, output a JSON object with the following fields: title, authors, year, venue, abstract (your summary), core_thesis, theoretical_lens, variables_and_measurements, causal_pathways, future_gaps.
427
- Return ONLY a valid JSON array.
 
 
 
 
 
 
 
 
 
 
 
 
428
  """
429
  for attempt in range(2):
430
  try:
431
- response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1, model_name="deepseek-chat")
432
  papers = self._extract_json_from_text(response)
433
-
434
- if not papers:
435
- raise ValueError("Extracted JSON is null or invalid")
436
-
437
  if isinstance(papers, dict):
438
  for v in papers.values():
439
  if isinstance(v, list):
440
  papers = v
441
  break
442
- if not isinstance(papers, list):
443
- papers = [papers]
444
-
445
  self.global_memory["core_golden_metadata"] = papers
446
-
447
  rag_context = []
448
  for paper in papers:
449
- if not isinstance(paper, dict):
450
- continue
451
  title = paper.get("title", "User Provided Document")
452
  year = paper.get("year", "n.d.")
453
  authors = paper.get("authors", ["User, Uploaded"])
454
  venue = paper.get("venue", "User Document")
455
  abstract = paper.get("abstract", "User provided core reference.")
456
  core_thesis = paper.get("core_thesis", "")
457
-
458
  if len(authors) == 1:
459
  author_str = authors[0]
460
  in_text = f"({authors[0].split(',')[0]}, {year})"
@@ -464,16 +419,16 @@ class SSciPipelineAgent:
464
  else:
465
  author_str = f"{authors[0]} et al."
466
  in_text = f"({authors[0].split(',')[0]} et al., {year})"
467
-
468
  apa_full = f"{author_str} ({year}). {title}. {venue}."
469
-
470
  with self.lock:
471
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
472
  self.citation_map[cite_tag] = {"in_text": in_text, "ref": apa_full}
473
- self.used_citations.add(cite_tag)
474
-
475
  rag_context.append(f"{cite_tag} [USER CORE PAPER] Title: {title}. Core Thesis: {core_thesis}. Abstract: {abstract}")
476
-
477
  return "\n".join(rag_context)
478
  except Exception as e:
479
  logging.error(f"❌ 解析核心论文黄金元数据尝试 {attempt+1} 失败: {e}")
@@ -515,10 +470,9 @@ class SSciPipelineAgent:
515
  queries = self._extract_json_from_text(response)
516
  if queries and isinstance(queries, list) and len(queries) > 0:
517
  final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]
518
- if final_queries:
519
- return final_queries[:3]
520
  time.sleep(1)
521
-
522
  combined_text = f"{topic} {keywords}"
523
  english_chunks = re.findall(r'[a-zA-Z0-9\s\-]{4,}', combined_text)
524
  clean_chunks = [chunk.strip() for chunk in english_chunks if len(chunk.strip()) >= 4 and self._is_english_dominant(chunk.strip())]
@@ -527,87 +481,74 @@ class SSciPipelineAgent:
527
  def _fetch_s2_page(self, search_term, offset=0, limit=50):
528
  time.sleep(random.uniform(0.5, 2.0))
529
  headers = {}
530
- if self.s2_key and str(self.s2_key).strip():
531
- headers["x-api-key"] = str(self.s2_key).strip()
532
  params = {"query": search_term, "offset": offset, "limit": limit, "fields": "title,authors,year,venue,abstract,externalIds"}
533
  logging.info(f"🔍 [S2 串行检索] 关键词: '{search_term}', Offset: {offset}")
534
  resp = self._requests_get_with_retry(f"{self.s2_api_url}/paper/search", headers=headers, params=params, timeout=15)
 
 
 
 
 
 
535
  return resp.json().get("data", [])
536
 
537
  def _fetch_openalex_page(self, search_term, page, filter_str):
538
  time.sleep(random.uniform(1.0, 3.0))
539
  dynamic_email = f"ssci_researcher_{random.randint(10000, 99999)}@gmail.com"
540
  headers = {"User-Agent": f"mailto:{dynamic_email}"}
541
- if self.openalex_key:
542
- headers["Authorization"] = f"Bearer {self.openalex_key}"
543
  params = {"search": search_term, "per-page": self.lit_per_page, "page": page, "filter": filter_str}
544
  logging.info(f"🔍 [OpenAlex 串行检索] 关键词: '{search_term}', 页码: {page}")
545
  resp = self._requests_get_with_retry(self.openalex_api_url, headers=headers, params=params, timeout=15)
546
  return resp.json().get("results", [])
547
 
548
  def fetch_references_parallel(self, topic, keywords, min_required=50, progress_callback=None):
549
- with self.lock:
550
- self.citation_map.clear()
551
- self.s2_fused = False
552
- self.oa_fused = False
553
-
554
  llm_rag_context = []
555
  seen_identifiers = set()
556
  filters_to_try = ["language:en,type:article,has_doi:true,is_paratext:false", "language:en,type:article,is_paratext:false", "type:article,is_paratext:false", "language:en,is_paratext:false"]
557
  all_used_terms = set()
558
-
559
  for expansion_phase in range(3):
560
- if len(self.citation_map) >= min_required:
561
- break
562
- self.s2_fused = False
563
- self.oa_fused = False
564
-
565
- if expansion_phase == 0:
566
- search_terms = self.generate_search_queries(topic, keywords)
567
  else:
568
  sys_prompt = "You are an expert academic librarian. The previous literature search yielded insufficient results. We must broaden the search scope."
569
  user_prompt = f"Original Topic: {topic}\nOriginal Keywords: {keywords}\nAlready Used Queries: {list(all_used_terms)}\nGenerate exactly 3 NEW, BROADER, or RELATED English search queries (max 3-4 words each) to expand the literature search. Do NOT repeat previous queries. Return ONLY a valid JSON array of strings."
570
  response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)
571
  queries = self._extract_json_from_text(response)
572
-
573
- if queries and isinstance(queries, list):
574
  search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]
575
  else:
576
  fallback_queries = re.findall(r'"([a-zA-Z\s\-]+)"', response)
577
  search_terms = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())][:3]
578
-
579
  current_batch_terms = [t for t in search_terms if t not in all_used_terms]
580
- if not current_batch_terms:
581
- continue
582
- for t in current_batch_terms:
583
- all_used_terms.add(t)
584
 
585
- if not self.s2_fused:
586
  for term in current_batch_terms:
587
- if len(self.citation_map) >= self.lit_target_papers:
588
- break
589
- if self.s2_fused:
590
- break
591
-
592
  offset = 0
593
- consecutive_400 = 0
594
  while len(self.citation_map) < self.lit_target_papers and offset < 500:
595
  try:
596
  papers = self._fetch_s2_page(term, offset=offset, limit=50)
597
- if not papers:
598
- break
599
- consecutive_400 = 0
600
  added_in_this_batch = 0
601
  for paper in papers:
602
- if len(self.citation_map) >= self.lit_target_papers:
603
- break
604
  title = paper.get("title")
605
  year = paper.get("year")
606
- if not title or not year:
607
- continue
608
  identifier = (title.lower().strip(), str(year))
609
- if identifier in seen_identifiers:
610
- continue
611
  seen_identifiers.add(identifier)
612
 
613
  authors = paper.get("authors", [])
@@ -622,31 +563,23 @@ class SSciPipelineAgent:
622
  else:
623
  last_names.append(name)
624
  formatted_authors.append(name)
625
- if not last_names:
626
- continue
627
 
628
  year_str = str(year)
629
  venue = paper.get("venue") or "Journal"
630
  doi = paper.get("externalIds", {}).get("DOI", "")
631
  abstract = paper.get("abstract", "")
632
 
633
- if len(last_names) == 1:
634
- in_text = f"({last_names[0]}, {year_str})"
635
- elif len(last_names) == 2:
636
- in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
637
- else:
638
- in_text = f"({last_names[0]} et al., {year_str})"
639
 
640
- if len(formatted_authors) > 2:
641
- author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
642
- elif len(formatted_authors) == 2:
643
- author_str = " & ".join(formatted_authors)
644
- else:
645
- author_str = formatted_authors[0]
646
 
647
  apa_full = f"{author_str} ({year_str}). {title}. {venue}."
648
- if doi:
649
- apa_full += f" https://doi.org/{doi}"
650
 
651
  with self.lock:
652
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
@@ -656,93 +589,52 @@ class SSciPipelineAgent:
656
 
657
  abs_snippet = " ".join(abstract.split()[:60]) + "..." if abstract else "Empirical data available."
658
  llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
659
-
660
- if added_in_this_batch == 0:
661
- offset += 50
662
- continue
663
  offset += 50
664
- if progress_callback:
665
- progress_callback()
666
-
667
- except requests.exceptions.HTTPError as e:
668
- if e.response.status_code == 400:
669
- error_msg = e.response.text
670
- if "offset is not available" in error_msg or "limit and/or offset" in error_msg:
671
- logging.info(f"ℹ️ [S2] 关键词 '{term}' 已无更多结果 (offset={offset}),正常结束。")
672
- break
673
- else:
674
- consecutive_400 += 1
675
- logging.warning(f"⚠️ [S2] 收到未知 400 错误: {error_msg},第 {consecutive_400} 次")
676
- if consecutive_400 >= 2:
677
- logging.error("连续 400 错误,跳过该检索词。")
678
- break
679
- time.sleep(2)
680
- continue
681
- elif e.response.status_code == 429:
682
- logging.warning(f"⚠️ [S2 限流] 等待 5 秒后重试...")
683
- time.sleep(5)
684
- continue
685
- else:
686
- logging.error(f"❌ [S2 致命错误] 状态码 {e.response.status_code},熔断 S2。")
687
- self.s2_fused = True
688
- break
689
  except Exception as e:
690
- logging.error(f"❌ [S2 网络异常] {e},熔断 S2。")
691
  self.s2_fused = True
 
692
  break
693
 
694
- if len(self.citation_map) < self.lit_target_papers and not self.oa_fused:
695
  for filter_str in filters_to_try:
696
- if len(self.citation_map) >= self.lit_target_papers:
697
- break
698
- if self.oa_fused:
699
- break
700
-
701
  for term in current_batch_terms:
702
- if len(self.citation_map) >= self.lit_target_papers:
703
- break
704
- if self.oa_fused:
705
- break
706
-
707
  page_batch = 1
708
- consecutive_failures = 0
709
  while len(self.citation_map) < self.lit_target_papers and page_batch <= self.lit_max_page_batches:
710
- batch_pages = range((page_batch - 1) * 5 + 1, page_batch * 5 + 1)
711
  raw_results = []
712
-
713
  for p in batch_pages:
714
- if len(self.citation_map) >= self.lit_target_papers:
715
- break
716
- for retry in range(3):
717
- try:
718
- res = self._fetch_openalex_page(term, p, filter_str)
719
- raw_results.extend(res)
720
- consecutive_failures = 0
721
- break
722
- except Exception as e:
723
- logging.warning(f"⚠️ OpenAlex 页 {p} 第 {retry+1} 次失败: {e}")
724
- if retry == 2:
725
- consecutive_failures += 1
726
- else:
727
- time.sleep(2 ** retry)
728
- if consecutive_failures >= 3:
729
- logging.error("OpenAlex 连续失败,熔断。")
730
  self.oa_fused = True
 
731
  break
732
- if self.oa_fused:
733
- break
734
-
735
  added_in_this_batch = 0
736
  for item in raw_results:
737
- if len(self.citation_map) >= self.lit_target_papers:
738
- break
739
  title = item.get("title")
740
- if not title or not self._is_english_dominant(title):
741
- continue
742
  year = item.get("publication_year", "n.d.")
743
  identifier = (title.lower().strip(), str(year))
744
- if identifier in seen_identifiers:
745
- continue
746
  seen_identifiers.add(identifier)
747
 
748
  venue = ((item.get("primary_location") or {}).get("source") or {}).get("display_name", "Journal")
@@ -758,27 +650,19 @@ class SSciPipelineAgent:
758
  else:
759
  last_names.append(name_raw)
760
  formatted_authors.append(name_raw)
761
- if not formatted_authors:
762
- continue
763
-
764
  year_str = str(year)
765
- if len(last_names) == 1:
766
- in_text = f"({last_names[0]}, {year_str})"
767
- elif len(last_names) == 2:
768
- in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
769
- else:
770
- in_text = f"({last_names[0]} et al., {year_str})"
771
-
772
- if len(formatted_authors) > 2:
773
- author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
774
- elif len(formatted_authors) == 2:
775
- author_str = " & ".join(formatted_authors)
776
- else:
777
- author_str = formatted_authors[0]
778
-
779
  apa_full = f"{author_str} ({year_str}). {title}. {venue}."
780
- if doi_clean:
781
- apa_full += f" https://doi.org/{doi_clean}"
782
 
783
  with self.lock:
784
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
@@ -794,12 +678,10 @@ class SSciPipelineAgent:
794
  raw_abstract = " ".join([word for pos, word in word_index])
795
  abs_snippet = " ".join(str(raw_abstract).split()[:60]) + "..." if raw_abstract else "Empirical data available."
796
  llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
797
-
798
- if added_in_this_batch == 0:
799
- break
800
  page_batch += 1
801
- if progress_callback:
802
- progress_callback()
803
 
804
  return "\n".join(llm_rag_context)
805
 
@@ -811,8 +693,7 @@ class SSciPipelineAgent:
811
 
812
  def bracket_replacer(match):
813
  inner = match.group(1)
814
- if not re.search(r'CITE-\d+', inner, re.IGNORECASE):
815
- return match.group(0)
816
  cites = re.findall(r'CITE-\d+', inner, flags=re.IGNORECASE)
817
  resolved = []
818
  for c in cites:
@@ -821,8 +702,7 @@ class SSciPipelineAgent:
821
  if full_c in self.citation_map:
822
  self.used_citations.add(full_c)
823
  resolved.append(self.citation_map[full_c]["in_text"].strip("()"))
824
- else:
825
- resolved.append(c.upper())
826
  return "(" + "; ".join(resolved) + ")"
827
 
828
  text = re.sub(r'\[(.*?)\]', bracket_replacer, text)
@@ -835,6 +715,5 @@ class SSciPipelineAgent:
835
  self.used_citations.add(full_c)
836
  return self.citation_map[full_c]["in_text"]
837
  return match.group(0)
838
-
839
  text = re.sub(r'CITE-\d+', loose_replacer, text, flags=re.IGNORECASE)
840
  return text
 
14
  import logging
15
  from tenacity import retry, stop_after_attempt, wait_random_exponential, wait_exponential, retry_if_exception_type
16
 
17
+ # 配置全局日志,直接输出到 HF 容器标准输出
18
  logging.basicConfig(
19
  level=logging.INFO,
20
  format="%(asctime)s [%(levelname)s] %(message)s",
 
27
  except ImportError:
28
  LANGDETECT_AVAILABLE = False
29
 
30
+ # 🚨 核心修复:更正为从 config 导入
31
+ from config import APP_CONFIG
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  class SSciPipelineAgent:
34
  def __init__(self, ds_key, s2_key=""):
 
41
  self.openalex_key = st.secrets.get("OA_API_KEY", "")
42
  except:
43
  self.openalex_key = os.environ.get("OA_API_KEY", "")
44
+
45
  self.ds_calls = 0
46
  self.oa_calls = 0
47
  self.s2_calls = 0
 
50
  self.citation_map = {}
51
  self.used_citations = set()
52
  self.lock = threading.RLock()
53
+
54
  self.lit_target_papers = APP_CONFIG["lit_target_papers"]
55
  self.lit_per_page = APP_CONFIG["lit_per_page"]
56
  self.lit_max_workers = APP_CONFIG["lit_max_workers"]
57
  self.lit_max_page_batches = APP_CONFIG["lit_max_page_batches"]
58
  self.chunk_words_default = APP_CONFIG["chunk_words_default"]
59
  self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]
60
+
61
  self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]
62
  self.openalex_api_url = APP_CONFIG["openalex_api_url"]
63
  self.s2_api_url = APP_CONFIG["s2_api_url"]
64
+
65
  self.global_memory = {
66
  "hypotheses": "", "variables": "", "model_summary": "",
67
  "method_summary": "", "abstract_anchor": "", "conclusion_anchor": "",
68
  "core_golden_metadata": []
69
  }
70
+
71
  try:
72
  self.tokenizer = tiktoken.get_encoding("cl100k_base")
73
  except:
 
75
 
76
  def _extract_json_from_text(self, text):
77
  """无敌 JSON 提取器:外科手术式提取,彻底无视大模型废话前缀和 Markdown 包装"""
78
+ if not text: return None
79
+
80
+ # 1. 强制清理潜在的 <think> 标签残留,防止干扰括号匹配
81
  text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
82
+
83
+ # 🚨 核心修复:强力清洗 Markdown 代码块标记,防止 JSON 解析崩溃
84
+ text = re.sub(r'```json\n?', '', text, flags=re.IGNORECASE)
85
+ text = re.sub(r'```\n?', '', text)
86
+
87
+ # 2. 寻找最外层的 {} 或 [] 边界
88
  start_dict = text.find('{')
89
  end_dict = text.rfind('}')
90
  start_list = text.find('[')
91
  end_list = text.rfind(']')
92
+
93
  dict_len = end_dict - start_dict if start_dict != -1 and end_dict != -1 else -1
94
  list_len = end_list - start_list if start_list != -1 and end_list != -1 else -1
95
+
96
  if dict_len == -1 and list_len == -1:
97
  return None
98
+
99
  try:
100
+ # 3. 强行截取最长匹配的 JSON 字符串进行解析
101
  if dict_len > list_len:
102
+ json_str = text[start_dict:end_dict+1]
103
  return json.loads(json_str)
104
  else:
105
+ json_str = text[start_list:end_list+1]
106
  return json.loads(json_str)
107
  except Exception as e:
108
  logging.error(f"❌ JSON 外科提取彻底失败: {e} | 原文片段: {text[:200]}...")
 
120
  }
121
 
122
  def load_state(self, state_dict):
123
+ if not state_dict: return
 
124
  with self.lock:
125
  self.ds_calls = state_dict.get("ds_calls", 0)
126
  self.oa_calls = state_dict.get("oa_calls", 0)
 
134
  return max(2, int(target_words / words_per_para))
135
 
136
  def _translate_text(self, text, target_lang, max_tokens=2000):
137
+ if not text.strip(): return ""
 
138
  sys_prompt = f"Translate the following text into {target_lang}. Preserve all formatting, line breaks, and [CITE-XX] tags exactly. Output ONLY the translation."
139
  return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2, model_name="deepseek-chat")
140
 
141
+ @retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=1, max=10), retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError)))
 
 
 
 
142
  def _requests_get_with_retry(self, url, headers=None, params=None, timeout=15):
143
  resp = requests.get(url, headers=headers, params=params, timeout=timeout)
144
  if resp.status_code == 429:
145
  logging.warning(f"⚠️ [API 限流] 触发 429,当前线程进入随机休眠退避。URL: {url}")
146
  resp.raise_for_status()
147
+
148
+ # 🚨 核心修复:静默拦截 S2 的 400 分页终点错误,防止上层误判为网络异常引发重试熔断
149
+ if resp.status_code == 400 and "Requested data for this limit" in resp.text:
150
+ return resp
151
+
152
  if resp.status_code != 200:
153
  logging.error(f"❌ [API 错误] 状态码: {resp.status_code}, 响应: {resp.text}")
154
  resp.raise_for_status()
155
  return resp
156
 
157
  def _is_english_dominant(self, text):
158
+ if not text: return False
 
159
  if LANGDETECT_AVAILABLE:
160
+ try: return detect(text) == 'en'
161
+ except: pass
 
 
162
  alpha_chars = sum(1 for c in str(text) if c.isalpha())
163
+ if alpha_chars == 0: return False
 
164
  return (len(re.findall(r'[a-zA-Z]', str(text))) / alpha_chars) > 0.8
165
 
166
  def _extract_memory_from_text(self, text, section_name):
167
  lower_sec = section_name.lower()
168
  if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):
169
  hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)
170
+ if hypo_matches: self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])
 
171
  if any(kw in lower_sec for kw in ["method", "measure", "variable"]):
172
  var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)
173
+ if var_matches: self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])
 
174
  if "model" in lower_sec or "figure" in lower_sec:
175
  model_match = re.search(r'(Figure\s*\d+[^\.]+\.)', text, re.IGNORECASE)
176
+ if model_match: self.global_memory["model_summary"] = model_match.group(1)
 
177
  if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):
178
  method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)
179
+ if method_match: self.global_memory["method_summary"] = method_match.group(1)
 
180
 
181
  def _count_tokens(self, text):
182
  return len(self.tokenizer.encode(text))
183
 
184
  def _truncate_context(self, text, max_tokens):
185
  tokens = self.tokenizer.encode(text)
186
+ if len(tokens) <= max_tokens: return text
 
187
  return self.tokenizer.decode(tokens[:max_tokens])
188
 
189
  def _build_memory_context(self, section_name="", max_tokens=2500):
190
  memory_parts = []
191
+ if self.global_memory["abstract_anchor"]: memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")
192
+ if self.global_memory["conclusion_anchor"]: memory_parts.append(f"【PAPER ANCHOR - EXPECTED CONCLUSION】\n{self.global_memory['conclusion_anchor']}")
193
+ if self.global_memory["hypotheses"]: memory_parts.append(f"【ESTABLISHED HYPOTHESES】\n{self.global_memory['hypotheses']}")
194
+ if self.global_memory["variables"]: memory_parts.append(f"【CORE CONSTRUCT DEFINITIONS】\n{self.global_memory['variables']}")
195
+ if self.global_memory["model_summary"]: memory_parts.append(f"【RESEARCH MODEL】\n{self.global_memory['model_summary']}")
196
+ if self.global_memory["method_summary"]: memory_parts.append(f"【METHODOLOGICAL SUMMARY】\n{self.global_memory['method_summary']}")
197
+
 
 
 
 
 
 
198
  golden_meta = self.global_memory.get("core_golden_metadata", [])
199
  if isinstance(golden_meta, list) and section_name:
200
  lower_sec = section_name.lower()
201
  injected_data = []
202
+
203
  if any(kw in lower_sec for kw in ["introduction", "background"]):
204
  for p in golden_meta:
205
+ if isinstance(p, dict) and p.get('future_gaps'): injected_data.append(f"[{p.get('title', 'Ref')}] Future Gaps: {p['future_gaps']}")
206
+ if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE GAPS (FOR RESEARCH GAP FORMULATION)】\n" + "\n".join(injected_data))
207
+
 
 
208
  elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):
209
  for p in golden_meta:
210
  if isinstance(p, dict):
211
+ if p.get('theoretical_lens'): injected_data.append(f"[{p.get('title', 'Ref')}] Theoretical Lens: {p['theoretical_lens']}")
212
+ if p.get('causal_pathways'): injected_data.append(f"[{p.get('title', 'Ref')}] Pathways: {p['causal_pathways']}")
213
+ if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE THEORIES & PATHWAYS (USE FOR HYPOTHESIS DEDUCTION)】\n" + "\n".join(injected_data))
214
+
 
 
 
215
  elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):
216
  for p in golden_meta:
217
+ if isinstance(p, dict) and p.get('variables_and_measurements'): injected_data.append(f"[{p.get('title', 'Ref')}] Measurements: {p['variables_and_measurements']}")
218
+ if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE MEASUREMENTS (USE FOR SCALE ADAPTATION DEFENSE)】\n" + "\n".join(injected_data))
219
+
 
 
220
  elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication", "result", "analysis"]):
221
  for p in golden_meta:
222
+ if isinstance(p, dict) and p.get('causal_pathways'): injected_data.append(f"[{p.get('title', 'Ref')}] Confirmed Pathways: {p['causal_pathways']}")
223
+ if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE FINDINGS (COMPARE OUR RESULTS AGAINST THESE)】\n" + "\n".join(injected_data))
 
 
224
 
225
  full = "\n\n".join(memory_parts)
226
+ if self._count_tokens(full) > max_tokens: return self._truncate_context(full, max_tokens)
 
227
  return full
228
 
229
  def call_deepseek(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3, model_name="deepseek-reasoner"):
230
  logging.info(f"🚀 [DeepSeek API] 准备调用 {model_name}, 提示词预计 Tokens: {self._count_tokens(user_prompt)}")
231
  for attempt in range(3):
232
+ with self.lock: self.ds_calls += 1
 
233
  current_model = model_name
234
  if attempt == 2 and model_name == "deepseek-reasoner":
235
  current_model = "deepseek-chat"
236
+ temp = 0.3
237
  logging.warning("⚠️ [算力降级] Reasoner 节点拥挤,强制降级为 deepseek-chat 执行本节点!")
238
+
239
  payload = {
240
+ "model": current_model,
241
+ "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
242
+ "max_tokens": max_tokens,
243
+ "stream": True
244
  }
245
  if current_model != "deepseek-reasoner":
246
  payload["temperature"] = temp
247
+
248
  full_content = ""
249
  try:
250
  with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 180)) as response:
251
  if response.status_code != 200:
252
  error_msg = f"DeepSeek API 拒绝访问 (状态码: {response.status_code})。详情: {response.text}"
253
  logging.error(f"❌ 尝试 {attempt+1}/3 失败: {error_msg}")
254
+ if attempt == 2:
255
  st.toast(f"❌ API 彻底熔断: {error_msg}", icon="🚨")
256
  raise requests.exceptions.HTTPError(error_msg)
257
+ time.sleep(3 ** attempt)
258
  continue
259
+
260
  for line in response.iter_lines():
261
  if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':
262
  try:
263
  delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})
264
  content = delta.get('content', '')
265
+ if content: full_content += content
266
+ except Exception: pass
 
 
267
  return full_content.strip()
268
  except Exception as e:
269
  logging.error(f"❌ [网络异常] 尝试 {attempt+1}/3 失败: {e}")
270
+ if attempt == 2: raise e
271
+ time.sleep(3 ** attempt)
 
272
 
273
  def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name="deepseek-reasoner"):
274
  temp = 0.3 if model_name == "deepseek-chat" else 0.2
275
  for attempt in range(3):
276
+ with self.lock: self.ds_calls += 1
 
277
  current_model = model_name
278
  if attempt >= 1 and model_name == "deepseek-reasoner":
279
  current_model = "deepseek-chat"
280
+ temp = 0.3
281
  logging.warning(f"⚠️ [流式降级] {model_name} 连接失败,强制切换至 deepseek-chat。")
282
 
283
  payload = {
284
+ "model": current_model,
285
+ "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
286
+ "max_tokens": max_tokens,
287
  "stream": True
288
  }
289
  if current_model != "deepseek-reasoner":
290
  payload["temperature"] = temp
291
+
292
  in_think_block = False
293
  try:
294
  with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 300)) as response:
295
  if response.status_code != 200:
296
  logging.error(f"❌ [流式 API 错误] 状态码: {response.status_code}, 响应: {response.text}")
297
+ if attempt == 2: response.raise_for_status()
298
+ time.sleep(2)
299
+ continue
 
300
 
301
  for line in response.iter_lines():
302
  if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':
303
  try:
304
  delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})
305
  content = delta.get('content', '')
306
+ if not content: continue
307
+
 
308
  if '<think>' in content:
309
  in_think_block = True
310
  content = content.replace('<think>', '')
311
  if '</think>' in content:
312
  in_think_block = False
313
  content = content.replace('</think>', '')
314
+ if not content: continue
 
315
 
316
  if not in_think_block and content:
317
  yield content
318
+ except Exception: pass
319
+ return
320
+ except GeneratorExit: raise
 
 
 
 
 
 
 
 
321
  except Exception as e:
322
  logging.error(f"❌ [流式中断] 尝试 {attempt+1}/3 异常: {e}")
323
+ if attempt == 2: raise
324
+ time.sleep(2)
 
325
 
326
  def extract_document_structure(self, text, paper_type="empirical"):
327
+ fallbacks = {"empirical": ["Introduction", "Literature Review", "Methodology", "Results", "Discussion", "Conclusion"], "generic": ["Introduction", "Main Body", "Discussion", "Conclusion"]}
 
328
  default_sections = fallbacks.get(paper_type, fallbacks["generic"])
329
+ if not text or len(text.strip()) < 100: return default_sections
 
330
 
331
+ max_safe_chars = 50000
332
  if len(text) > max_safe_chars:
333
  sampled_text = text[:int(max_safe_chars * 0.7)] + "\n\n...[CONTENT OMITTED]...\n\n" + text[-int(max_safe_chars * 0.3):]
334
+ else: sampled_text = text
 
335
 
336
  sys_prompt = "You are an expert academic editor."
337
  user_prompt = f"Analyze the following academic text and extract its core structural headings (top-level only). Rules: 1. Ignore subheadings. 2. Ignore front/back matter. 3. Output exact heading names separated by ' || '. Text snippet:\n{sampled_text}"
 
342
  clean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()
343
  if '||' in clean_resp:
344
  headings = [h.strip() for h in clean_resp.split('||') if h.strip()]
345
+ if len(headings) >= 3: return headings
 
346
  list_matches = re.findall(r'^(?:\d+\.|[A-Z]\.)\s*(.+)$', clean_resp, re.MULTILINE)
347
+ if list_matches and len(list_matches) >= 3: return [m.strip() for m in list_matches]
348
+ except Exception: continue
 
 
349
  return default_sections
350
 
351
  def reverse_engineer_section(self, reference_text, section_name):
 
360
  return {"tone_and_style": "objective academic tone", "reporting_structure": "standard empirical reporting", "few_shot_snippet": ""}
361
 
362
  def parse_user_core_literature(self, user_lit_text):
363
+ if not user_lit_text.strip(): return ""
364
+ sys_prompt = "You are an elite academic metadata extractor."
 
365
  user_prompt = f"""
366
  Analyze the following raw text extracted from user-uploaded core academic PDFs. There may be multiple papers.
367
  <RAW_TEXT>
368
+ {user_lit_text[:30000]}
369
  </RAW_TEXT>
370
 
371
+ Identify each distinct paper and extract its "Golden Metadata".
372
+ Return ONLY a valid JSON array of objects. Schema MUST exactly match:
373
+ [{{
374
+ "title": "Full Paper Title",
375
+ "authors": ["Lastname, Firstname", "Lastname, F."],
376
+ "year": "2023",
377
+ "venue": "Journal Name",
378
+ "abstract": "Brief summary of the paper.",
379
+ "core_thesis": "One precise sentence summarizing the core contribution.",
380
+ "theoretical_lens": "Identify the primary theoretical framework(s) applied (e.g., Resource-Based View, Social Exchange Theory).",
381
+ "variables_and_measurements": "List independent, dependent, mediator, and moderator variables. Include specific measurement items or scales if available.",
382
+ "causal_pathways": "List the significant causal relationships or hypotheses confirmed by the author (e.g., A positively impacts B, mediated by C).",
383
+ "future_gaps": "Summarize the limitations and future research directions explicitly stated by the author."
384
+ }}]
385
  """
386
  for attempt in range(2):
387
  try:
388
+ response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1, model_name="deepseek-chat")
389
  papers = self._extract_json_from_text(response)
390
+
391
+ if not papers: raise ValueError("Extracted JSON is null or invalid")
392
+
393
+ # 修复可能包裹在 dict 中的情况 (e.g., {"papers": [...]})
394
  if isinstance(papers, dict):
395
  for v in papers.values():
396
  if isinstance(v, list):
397
  papers = v
398
  break
399
+ if not isinstance(papers, list): papers = [papers]
400
+
 
401
  self.global_memory["core_golden_metadata"] = papers
402
+
403
  rag_context = []
404
  for paper in papers:
405
+ if not isinstance(paper, dict): continue
 
406
  title = paper.get("title", "User Provided Document")
407
  year = paper.get("year", "n.d.")
408
  authors = paper.get("authors", ["User, Uploaded"])
409
  venue = paper.get("venue", "User Document")
410
  abstract = paper.get("abstract", "User provided core reference.")
411
  core_thesis = paper.get("core_thesis", "")
412
+
413
  if len(authors) == 1:
414
  author_str = authors[0]
415
  in_text = f"({authors[0].split(',')[0]}, {year})"
 
419
  else:
420
  author_str = f"{authors[0]} et al."
421
  in_text = f"({authors[0].split(',')[0]} et al., {year})"
422
+
423
  apa_full = f"{author_str} ({year}). {title}. {venue}."
424
+
425
  with self.lock:
426
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
427
  self.citation_map[cite_tag] = {"in_text": in_text, "ref": apa_full}
428
+ self.used_citations.add(cite_tag)
429
+
430
  rag_context.append(f"{cite_tag} [USER CORE PAPER] Title: {title}. Core Thesis: {core_thesis}. Abstract: {abstract}")
431
+
432
  return "\n".join(rag_context)
433
  except Exception as e:
434
  logging.error(f"❌ 解析核心论文黄金元数据尝试 {attempt+1} 失败: {e}")
 
470
  queries = self._extract_json_from_text(response)
471
  if queries and isinstance(queries, list) and len(queries) > 0:
472
  final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())]
473
+ if final_queries: return final_queries[:3]
 
474
  time.sleep(1)
475
+
476
  combined_text = f"{topic} {keywords}"
477
  english_chunks = re.findall(r'[a-zA-Z0-9\s\-]{4,}', combined_text)
478
  clean_chunks = [chunk.strip() for chunk in english_chunks if len(chunk.strip()) >= 4 and self._is_english_dominant(chunk.strip())]
 
481
  def _fetch_s2_page(self, search_term, offset=0, limit=50):
482
  time.sleep(random.uniform(0.5, 2.0))
483
  headers = {}
484
+ if self.s2_key and str(self.s2_key).strip(): headers["x-api-key"] = str(self.s2_key).strip()
 
485
  params = {"query": search_term, "offset": offset, "limit": limit, "fields": "title,authors,year,venue,abstract,externalIds"}
486
  logging.info(f"🔍 [S2 串行检索] 关键词: '{search_term}', Offset: {offset}")
487
  resp = self._requests_get_with_retry(f"{self.s2_api_url}/paper/search", headers=headers, params=params, timeout=15)
488
+
489
+ # 🚨 核心修复:处理被底层的 400 状态码静默拦截返回的结果
490
+ if resp.status_code == 400:
491
+ logging.info(f"ℹ️ [S2] 关键词 '{search_term}' 已无更多结果 (offset={offset}),正常结束。")
492
+ return []
493
+
494
  return resp.json().get("data", [])
495
 
496
  def _fetch_openalex_page(self, search_term, page, filter_str):
497
  time.sleep(random.uniform(1.0, 3.0))
498
  dynamic_email = f"ssci_researcher_{random.randint(10000, 99999)}@gmail.com"
499
  headers = {"User-Agent": f"mailto:{dynamic_email}"}
500
+ if self.openalex_key: headers["Authorization"] = f"Bearer {self.openalex_key}"
 
501
  params = {"search": search_term, "per-page": self.lit_per_page, "page": page, "filter": filter_str}
502
  logging.info(f"🔍 [OpenAlex 串行检索] 关键词: '{search_term}', 页码: {page}")
503
  resp = self._requests_get_with_retry(self.openalex_api_url, headers=headers, params=params, timeout=15)
504
  return resp.json().get("results", [])
505
 
506
  def fetch_references_parallel(self, topic, keywords, min_required=50, progress_callback=None):
507
+ with self.lock: self.citation_map.clear()
 
 
 
 
508
  llm_rag_context = []
509
  seen_identifiers = set()
510
  filters_to_try = ["language:en,type:article,has_doi:true,is_paratext:false", "language:en,type:article,is_paratext:false", "type:article,is_paratext:false", "language:en,is_paratext:false"]
511
  all_used_terms = set()
512
+
513
  for expansion_phase in range(3):
514
+ if len(self.citation_map) >= min_required: break
515
+
516
+ if expansion_phase == 0: search_terms = self.generate_search_queries(topic, keywords)
 
 
 
 
517
  else:
518
  sys_prompt = "You are an expert academic librarian. The previous literature search yielded insufficient results. We must broaden the search scope."
519
  user_prompt = f"Original Topic: {topic}\nOriginal Keywords: {keywords}\nAlready Used Queries: {list(all_used_terms)}\nGenerate exactly 3 NEW, BROADER, or RELATED English search queries (max 3-4 words each) to expand the literature search. Do NOT repeat previous queries. Return ONLY a valid JSON array of strings."
520
  response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)
521
  queries = self._extract_json_from_text(response)
522
+
523
+ if queries and isinstance(queries, list):
524
  search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]
525
  else:
526
  fallback_queries = re.findall(r'"([a-zA-Z\s\-]+)"', response)
527
  search_terms = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())][:3]
528
+
529
  current_batch_terms = [t for t in search_terms if t not in all_used_terms]
530
+ if not current_batch_terms: continue
531
+ for t in current_batch_terms: all_used_terms.add(t)
 
 
532
 
533
+ if not getattr(self, 's2_fused', False):
534
  for term in current_batch_terms:
535
+ if len(self.citation_map) >= self.lit_target_papers: break
536
+ if getattr(self, 's2_fused', False): break
537
+
 
 
538
  offset = 0
 
539
  while len(self.citation_map) < self.lit_target_papers and offset < 500:
540
  try:
541
  papers = self._fetch_s2_page(term, offset=offset, limit=50)
542
+ if not papers: break
543
+
 
544
  added_in_this_batch = 0
545
  for paper in papers:
546
+ if len(self.citation_map) >= self.lit_target_papers: break
 
547
  title = paper.get("title")
548
  year = paper.get("year")
549
+ if not title or not year: continue
 
550
  identifier = (title.lower().strip(), str(year))
551
+ if identifier in seen_identifiers: continue
 
552
  seen_identifiers.add(identifier)
553
 
554
  authors = paper.get("authors", [])
 
563
  else:
564
  last_names.append(name)
565
  formatted_authors.append(name)
566
+ if not last_names: continue
 
567
 
568
  year_str = str(year)
569
  venue = paper.get("venue") or "Journal"
570
  doi = paper.get("externalIds", {}).get("DOI", "")
571
  abstract = paper.get("abstract", "")
572
 
573
+ if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"
574
+ elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
575
+ else: in_text = f"({last_names[0]} et al., {year_str})"
 
 
 
576
 
577
+ if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
578
+ elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)
579
+ else: author_str = formatted_authors[0]
 
 
 
580
 
581
  apa_full = f"{author_str} ({year_str}). {title}. {venue}."
582
+ if doi: apa_full += f" https://doi.org/{doi}"
 
583
 
584
  with self.lock:
585
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
 
589
 
590
  abs_snippet = " ".join(abstract.split()[:60]) + "..." if abstract else "Empirical data available."
591
  llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
592
+
593
+ if added_in_this_batch == 0: break
 
 
594
  offset += 50
595
+ if progress_callback: progress_callback()
596
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  except Exception as e:
598
+ logging.error(f"❌ Semantic Scholar API 拒绝响应或异常: {e}")
599
  self.s2_fused = True
600
+ logging.warning("🚨 [全局熔断] S2 引擎物理熔断!将跳过 S2,移交 OpenAlex 备用引擎。")
601
  break
602
 
603
+ if len(self.citation_map) < self.lit_target_papers and not getattr(self, 'oa_fused', False):
604
  for filter_str in filters_to_try:
605
+ if len(self.citation_map) >= self.lit_target_papers: break
606
+ if getattr(self, 'oa_fused', False): break
607
+
 
 
608
  for term in current_batch_terms:
609
+ if len(self.citation_map) >= self.lit_target_papers: break
610
+ if getattr(self, 'oa_fused', False): break
611
+
 
 
612
  page_batch = 1
 
613
  while len(self.citation_map) < self.lit_target_papers and page_batch <= self.lit_max_page_batches:
614
+ batch_pages = range((page_batch-1)*5 + 1, page_batch*5 + 1)
615
  raw_results = []
616
+
617
  for p in batch_pages:
618
+ if len(self.citation_map) >= self.lit_target_papers: break
619
+ try:
620
+ res = self._fetch_openalex_page(term, p, filter_str)
621
+ raw_results.extend(res)
622
+ except Exception as e:
623
+ logging.error(f"❌ OpenAlex API 拒绝响应: {e}")
 
 
 
 
 
 
 
 
 
 
624
  self.oa_fused = True
625
+ logging.warning("🚨 [全局熔断] OpenAlex 引擎也发生物理熔断!")
626
  break
627
+
628
+ if getattr(self, 'oa_fused', False): break
629
+
630
  added_in_this_batch = 0
631
  for item in raw_results:
632
+ if len(self.citation_map) >= self.lit_target_papers: break
 
633
  title = item.get("title")
634
+ if not title or not self._is_english_dominant(title): continue
 
635
  year = item.get("publication_year", "n.d.")
636
  identifier = (title.lower().strip(), str(year))
637
+ if identifier in seen_identifiers: continue
 
638
  seen_identifiers.add(identifier)
639
 
640
  venue = ((item.get("primary_location") or {}).get("source") or {}).get("display_name", "Journal")
 
650
  else:
651
  last_names.append(name_raw)
652
  formatted_authors.append(name_raw)
653
+ if not formatted_authors: continue
654
+
 
655
  year_str = str(year)
656
+ if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"
657
+ elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"
658
+ else: in_text = f"({last_names[0]} et al., {year_str})"
659
+
660
+ if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]
661
+ elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)
662
+ else: author_str = formatted_authors[0]
663
+
 
 
 
 
 
 
664
  apa_full = f"{author_str} ({year_str}). {title}. {venue}."
665
+ if doi_clean: apa_full += f" https://doi.org/{doi_clean}"
 
666
 
667
  with self.lock:
668
  cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"
 
678
  raw_abstract = " ".join([word for pos, word in word_index])
679
  abs_snippet = " ".join(str(raw_abstract).split()[:60]) + "..." if raw_abstract else "Empirical data available."
680
  llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")
681
+
682
+ if added_in_this_batch == 0: break
 
683
  page_batch += 1
684
+ if progress_callback: progress_callback()
 
685
 
686
  return "\n".join(llm_rag_context)
687
 
 
693
 
694
  def bracket_replacer(match):
695
  inner = match.group(1)
696
+ if not re.search(r'CITE-\d+', inner, re.IGNORECASE): return match.group(0)
 
697
  cites = re.findall(r'CITE-\d+', inner, flags=re.IGNORECASE)
698
  resolved = []
699
  for c in cites:
 
702
  if full_c in self.citation_map:
703
  self.used_citations.add(full_c)
704
  resolved.append(self.citation_map[full_c]["in_text"].strip("()"))
705
+ else: resolved.append(c.upper())
 
706
  return "(" + "; ".join(resolved) + ")"
707
 
708
  text = re.sub(r'\[(.*?)\]', bracket_replacer, text)
 
715
  self.used_citations.add(full_c)
716
  return self.citation_map[full_c]["in_text"]
717
  return match.group(0)
 
718
  text = re.sub(r'CITE-\d+', loose_replacer, text, flags=re.IGNORECASE)
719
  return text