Spaces:
Sleeping
Sleeping
Update core/pipeline_agent.py
Browse files- core/pipeline_agent.py +31 -42
core/pipeline_agent.py
CHANGED
|
@@ -166,13 +166,13 @@ class SSciPipelineAgent:
|
|
| 166 |
|
| 167 |
def _extract_memory_from_text(self, text, section_name):
|
| 168 |
lower_sec = section_name.lower()
|
| 169 |
-
if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):
|
| 170 |
hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)
|
| 171 |
if hypo_matches:
|
| 172 |
self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])
|
| 173 |
logging.info(f"🧠 [记忆更新] 从 {section_name} 中提取了假设 H1-Hn")
|
| 174 |
|
| 175 |
-
if any(kw in lower_sec for kw in ["method", "measure", "variable"]):
|
| 176 |
var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)
|
| 177 |
if var_matches:
|
| 178 |
self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])
|
|
@@ -183,7 +183,7 @@ class SSciPipelineAgent:
|
|
| 183 |
if model_match:
|
| 184 |
self.global_memory["model_summary"] = model_match.group(1)
|
| 185 |
|
| 186 |
-
if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):
|
| 187 |
method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)
|
| 188 |
if method_match:
|
| 189 |
self.global_memory["method_summary"] = method_match.group(1)
|
|
@@ -205,9 +205,9 @@ class SSciPipelineAgent:
|
|
| 205 |
if self.global_memory["abstract_anchor"]:
|
| 206 |
memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")
|
| 207 |
|
| 208 |
-
is_intro_lit = any(kw in lower_sec for kw in ["introduction", "background", "literature", "theor", "review"])
|
| 209 |
-
is_method = any(kw in lower_sec for kw in ["method", "measure", "data", "sample"])
|
| 210 |
-
is_result = any(kw in lower_sec for kw in ["result", "analysis"])
|
| 211 |
is_discussion = any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"])
|
| 212 |
|
| 213 |
if is_intro_lit or is_discussion:
|
|
@@ -388,28 +388,6 @@ class SSciPipelineAgent:
|
|
| 388 |
raise
|
| 389 |
time.sleep(2)
|
| 390 |
|
| 391 |
-
def extract_document_structure(self, text, paper_type="empirical"):
|
| 392 |
-
fallbacks = {"empirical": ["Introduction", "Literature Review", "Methodology", "Results", "Discussion", "Conclusion"], "generic": ["Introduction", "Main Body", "Discussion", "Conclusion"]}
|
| 393 |
-
default_sections = fallbacks.get(paper_type, fallbacks["generic"])
|
| 394 |
-
if not text or len(text.strip()) < 100:
|
| 395 |
-
return default_sections
|
| 396 |
-
|
| 397 |
-
sampled_text = text[:35000] + "\n...[OMITTED]...\n" + text[-15000:] if len(text) > 50000 else text
|
| 398 |
-
sys_prompt = "You are an expert academic editor."
|
| 399 |
-
user_prompt = f"Extract core structural headings (top-level only). Ignore subheadings/front matter. Output exact names separated by ' || '.\nText:\n{sampled_text}"
|
| 400 |
-
|
| 401 |
-
for attempt in range(2):
|
| 402 |
-
try:
|
| 403 |
-
response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=300)
|
| 404 |
-
clean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()
|
| 405 |
-
if '||' in clean_resp:
|
| 406 |
-
headings = [h.strip() for h in clean_resp.split('||') if h.strip()]
|
| 407 |
-
if len(headings) >= 3:
|
| 408 |
-
return headings
|
| 409 |
-
except Exception:
|
| 410 |
-
continue
|
| 411 |
-
return default_sections
|
| 412 |
-
|
| 413 |
def parse_user_core_literature(self, user_lit_text):
|
| 414 |
if not user_lit_text.strip():
|
| 415 |
return ""
|
|
@@ -499,15 +477,30 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 499 |
|
| 500 |
return final_abstract, final_conclusion
|
| 501 |
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
|
| 512 |
def prefetch_jit_literature(self, topic, keywords, structure):
|
| 513 |
jit_rag_texts = []
|
|
@@ -515,8 +508,7 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 515 |
|
| 516 |
for sec in structure:
|
| 517 |
sec_title = sec.get("section", "")
|
| 518 |
-
if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result"]):
|
| 519 |
-
# [修改 3] 在 JIT 查询时也限制布尔嵌套
|
| 520 |
jit_prompt = f"Topic: '{topic}'. Keywords: '{keywords}'. Section: '{sec_title}'. Generate exactly 1 highly specific English search query (e.g., a specific statistical method, measurement scale, or analytical framework needed). Keep it UNDER 5 terms. NO complex boolean logic. Return ONLY the query string, no quotes."
|
| 521 |
query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2, model_name="deepseek-chat").strip(' "\'')
|
| 522 |
if query:
|
|
@@ -545,7 +537,6 @@ You MUST output your response EXACTLY using the following two delimiters. Do not
|
|
| 545 |
logging.info(f"✅ [Pre-fetch JIT] 成功抓取并注入了 {len(jit_rag_texts)} 篇底层支撑文献。")
|
| 546 |
return "\n".join(jit_rag_texts)
|
| 547 |
|
| 548 |
-
# [修复核心 2] 彻底精简大模型的布尔检索词生成逻辑
|
| 549 |
def generate_search_queries(self, topic, keywords):
|
| 550 |
sys_prompt = """You are an expert academic librarian. Generate exactly 3 concise English search queries.
|
| 551 |
[CRITICAL SEARCH QUERY RULES]
|
|
@@ -632,7 +623,6 @@ Return ONLY a valid JSON array of strings."""
|
|
| 632 |
results = []
|
| 633 |
logging.info(f"🌐 [OA Worker] 正在 OpenAlex 检索: '{term}' (page={page})")
|
| 634 |
try:
|
| 635 |
-
# [修复核心 1] 在 params 中直接注入 mailto 参数,确保进入礼貌池
|
| 636 |
params = {
|
| 637 |
"search": term,
|
| 638 |
"per-page": self.lit_per_page,
|
|
@@ -708,7 +698,6 @@ Return ONLY a valid JSON array of strings."""
|
|
| 708 |
search_terms = self.generate_search_queries(topic, keywords)
|
| 709 |
else:
|
| 710 |
logging.info(f"🔄 [文献检索] 阶段 {expansion_phase}: 数量不足 ({len(self.citation_map)}/{min_required}),正在扩大检索范围...")
|
| 711 |
-
# [配合修复] 在拓展搜索阶段同样增加布尔嵌套约束
|
| 712 |
sys_prompt = """You are an expert academic librarian. We must broaden the search scope.
|
| 713 |
[CRITICAL SEARCH QUERY RULES]
|
| 714 |
1. DO NOT use complex, deeply nested boolean logic (e.g., Avoid `(A OR B) AND (C OR D)`).
|
|
|
|
| 166 |
|
| 167 |
def _extract_memory_from_text(self, text, section_name):
|
| 168 |
lower_sec = section_name.lower()
|
| 169 |
+
if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis", "framing"]):
|
| 170 |
hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)
|
| 171 |
if hypo_matches:
|
| 172 |
self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])
|
| 173 |
logging.info(f"🧠 [记忆更新] 从 {section_name} 中提取了假设 H1-Hn")
|
| 174 |
|
| 175 |
+
if any(kw in lower_sec for kw in ["method", "measure", "variable", "setting"]):
|
| 176 |
var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)
|
| 177 |
if var_matches:
|
| 178 |
self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])
|
|
|
|
| 183 |
if model_match:
|
| 184 |
self.global_memory["model_summary"] = model_match.group(1)
|
| 185 |
|
| 186 |
+
if any(kw in lower_sec for kw in ["method", "sample", "procedure", "setting"]):
|
| 187 |
method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)
|
| 188 |
if method_match:
|
| 189 |
self.global_memory["method_summary"] = method_match.group(1)
|
|
|
|
| 205 |
if self.global_memory["abstract_anchor"]:
|
| 206 |
memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")
|
| 207 |
|
| 208 |
+
is_intro_lit = any(kw in lower_sec for kw in ["introduction", "background", "literature", "theor", "review", "framing"])
|
| 209 |
+
is_method = any(kw in lower_sec for kw in ["method", "measure", "data", "sample", "setting"])
|
| 210 |
+
is_result = any(kw in lower_sec for kw in ["result", "analysis", "finding"])
|
| 211 |
is_discussion = any(kw in lower_sec for kw in ["discussion", "conclusion", "implication"])
|
| 212 |
|
| 213 |
if is_intro_lit or is_discussion:
|
|
|
|
| 388 |
raise
|
| 389 |
time.sleep(2)
|
| 390 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
def parse_user_core_literature(self, user_lit_text):
|
| 392 |
if not user_lit_text.strip():
|
| 393 |
return ""
|
|
|
|
| 477 |
|
| 478 |
return final_abstract, final_conclusion
|
| 479 |
|
| 480 |
+
# =====================================================================
|
| 481 |
+
# [核心架构升级] 双轨制大纲路由,取代自由生成的结构断层风险
|
| 482 |
+
# =====================================================================
|
| 483 |
+
def generate_outline(self, topic, keywords, mode="amj"):
|
| 484 |
+
schema_key = "asq_schema" if mode == "asq" else "amj_schema"
|
| 485 |
+
sections = APP_CONFIG.get(schema_key, APP_CONFIG["amj_schema"])
|
| 486 |
+
|
| 487 |
+
sys_prompt = "You are a senior academic editor. Polish the provided section titles to be more professional but DO NOT change the structure."
|
| 488 |
+
structure_str = " || ".join([s["section"] for s in sections])
|
| 489 |
+
response = self.call_deepseek(sys_prompt, f"Topic: {topic}. Structure: {structure_str}. Output refined titles only, separated by ' || '.", model_name="deepseek-chat")
|
| 490 |
+
|
| 491 |
+
refined_titles = [t.strip() for t in response.split("||")]
|
| 492 |
+
|
| 493 |
+
final_structure = []
|
| 494 |
+
for i, s in enumerate(sections):
|
| 495 |
+
title = refined_titles[i] if i < len(refined_titles) and refined_titles[i] else s["section"]
|
| 496 |
+
title = title.replace("*", "").strip()
|
| 497 |
+
final_structure.append({
|
| 498 |
+
"section": title,
|
| 499 |
+
"weight": s["weight"],
|
| 500 |
+
"is_method_or_result": any(kw in title.lower() for kw in ["method", "result", "analysis", "finding", "setting"])
|
| 501 |
+
})
|
| 502 |
+
|
| 503 |
+
return {"en_topic": topic, "structure": final_structure}
|
| 504 |
|
| 505 |
def prefetch_jit_literature(self, topic, keywords, structure):
|
| 506 |
jit_rag_texts = []
|
|
|
|
| 508 |
|
| 509 |
for sec in structure:
|
| 510 |
sec_title = sec.get("section", "")
|
| 511 |
+
if any(kw in sec_title.lower() for kw in ["method", "methodology", "analysis", "result", "finding", "setting"]):
|
|
|
|
| 512 |
jit_prompt = f"Topic: '{topic}'. Keywords: '{keywords}'. Section: '{sec_title}'. Generate exactly 1 highly specific English search query (e.g., a specific statistical method, measurement scale, or analytical framework needed). Keep it UNDER 5 terms. NO complex boolean logic. Return ONLY the query string, no quotes."
|
| 513 |
query = self.call_deepseek("You are an expert academic librarian.", jit_prompt, max_tokens=50, temp=0.2, model_name="deepseek-chat").strip(' "\'')
|
| 514 |
if query:
|
|
|
|
| 537 |
logging.info(f"✅ [Pre-fetch JIT] 成功抓取并注入了 {len(jit_rag_texts)} 篇底层支撑文献。")
|
| 538 |
return "\n".join(jit_rag_texts)
|
| 539 |
|
|
|
|
| 540 |
def generate_search_queries(self, topic, keywords):
|
| 541 |
sys_prompt = """You are an expert academic librarian. Generate exactly 3 concise English search queries.
|
| 542 |
[CRITICAL SEARCH QUERY RULES]
|
|
|
|
| 623 |
results = []
|
| 624 |
logging.info(f"🌐 [OA Worker] 正在 OpenAlex 检索: '{term}' (page={page})")
|
| 625 |
try:
|
|
|
|
| 626 |
params = {
|
| 627 |
"search": term,
|
| 628 |
"per-page": self.lit_per_page,
|
|
|
|
| 698 |
search_terms = self.generate_search_queries(topic, keywords)
|
| 699 |
else:
|
| 700 |
logging.info(f"🔄 [文献检索] 阶段 {expansion_phase}: 数量不足 ({len(self.citation_map)}/{min_required}),正在扩大检索范围...")
|
|
|
|
| 701 |
sys_prompt = """You are an expert academic librarian. We must broaden the search scope.
|
| 702 |
[CRITICAL SEARCH QUERY RULES]
|
| 703 |
1. DO NOT use complex, deeply nested boolean logic (e.g., Avoid `(A OR B) AND (C OR D)`).
|