Spaces:
Sleeping
Sleeping
Update core/pipeline_agent.py
Browse files26 unmodified lines2728293031323311 unmodified lines45464748495051528 unmodified lines616263646566676869707172737414 unmodified lines8990919293949533 unmodified lines12913013113213313413513613713813914014114214314414514628 unmodified lines1751761771781791801811 unmodified line18318418518618718818919019119219319419519619719819926 unmodified lines22622722822923023123223323423523623723823924024124224324424524624724833 unmodified lines28228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538616 unmodified lines4034044054064074084094104114124134144158 unmodified lines4244254264274284294304314324334344354364377 unmodified lines4454464474484494504514524534544554564574582 unmodified lines4614624634644654664674684694704714724734744754764774784794804814821 unmodified line4844854864874884894904914924932 unmodified lines49649749849950050150250350464 unmodified lines56957057157257357457557657726 unmodified linesexcept ImportError:LANGDETECT_AVAILABLE = False# 引入全局配置from app_config import APP_CONFIGclass SSciPipelineAgent:11 unmodified linesself.ds_calls = 0self.oa_calls = 0self.s2_calls = 0self.s2_fused = False # 🚨 新增:Semantic Scholar (主擎) 物理熔断开关self.oa_fused = False # 🚨 新增:OpenAlex (备擎) 物理熔断开关self.citation_map = {}self.used_citations = set()self.lock = threading.RLock()8 unmodified linesself.s2_api_url = APP_CONFIG["s2_api_url"]self.global_memory = {"hypotheses": "", "variables": "", "model_summary": "","method_summary": "", "abstract_anchor": "", "conclusion_anchor": ""}try:self.tokenizer = tiktoken.get_encoding("cl100k_base")except:self.tokenizer = tiktoken.get_encoding("gpt2")# ================= 状态管理器 (用于断点续传) =================def export_state(self):with self.lock:return {14 unmodified linesself.citation_map = state_dict.get("citation_map", {})self.used_citations = set(state_dict.get("used_citations", []))self.global_memory = state_dict.get("global_memory", self.global_memory)# =====================================================================def _calc_paragraph_count(self, target_words, lang_hint="en"):words_per_para = 100 if lang_hint in ["ru", "kk"] else 13033 unmodified linesexcept Exception:return False# 🚨 “快速失败”网络请求底层,最多重试3次,最大等待10秒,不行就立刻抛异常触发外层熔断@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)))def _requests_get_with_retry(self, url, headers=None, params=None, timeout=15):resp = requests.get(url, headers=headers, params=params, timeout=timeout)if resp.status_code == 429:logging.warning(f"⚠️ [API 限流] 触发 429,当前线程进入随机休眠退避。URL: {url}")resp.raise_for_status()if resp.status_code != 200:logging.error(f"❌ [API 错误] 状态码: {resp.status_code}, 响应: {resp.text}")resp.raise_for_status()return respdef _is_english_dominant(self, text):28 unmodified linesif len(tokens) <= max_tokens: return textreturn self.tokenizer.decode(tokens[:max_tokens])def _build_memory_context(self, max_tokens=2000):memory_parts = []if self.global_memory["abstract_anchor"]: memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")if self.global_memory["conclusion_anchor"]: memory_parts.append(f"【PAPER ANCHOR - EXPECTED CONCLUSION】\n{self.global_memory['conclusion_anchor']}")1 unmodified lineif self.global_memory["variables"]: memory_parts.append(f"【CORE CONSTRUCT DEFINITIONS】\n{self.global_memory['variables']}")if self.global_memory["model_summary"]: memory_parts.append(f"【RESEARCH MODEL】\n{self.global_memory['model_summary']}")if self.global_memory["method_summary"]: memory_parts.append(f"【METHODOLOGICAL SUMMARY】\n{self.global_memory['method_summary']}")full = "\n\n".join(memory_parts)if self._count_tokens(full) > max_tokens: return self._truncate_context(full, max_tokens)return fulldef call_deepseek(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3, model_name="deepseek-reasoner"):"""带自动降级与显式报错的阻塞调用"""logging.info(f"🚀 [DeepSeek API] 准备调用 {model_name}, 提示词预计 Tokens: {self._count_tokens(user_prompt)}")for attempt in range(3):with self.lock: self.ds_calls += 1current_model = model_nameif attempt == 2 and model_name == "deepseek-reasoner":current_model = "deepseek-chat"26 unmodified linesdelta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})content = delta.get('content', '')if content: full_content += contentexcept Exception:passreturn full_content.strip()except Exception as e:logging.error(f"❌ [网络异常] 尝试 {attempt+1}/3 失败: {e}")if attempt == 2: raise etime.sleep(3 ** attempt)def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name="deepseek-reasoner"):"""带连接重试与安全解析的流式输出生成器"""temp = 0.3 if model_name == "deepseek-chat" else 0.2for attempt in range(3):with self.lock: self.ds_calls += 1current_model = model_nameif attempt >= 1 and model_name == "deepseek-reasoner":current_model = "deepseek-chat"33 unmodified linesif not in_think_block and content:yield contentexcept Exception:passreturnexcept GeneratorExit:raiseexcept Exception as e:logging.error(f"❌ [流式中断] 尝试 {attempt+1}/3 异常: {e}")if attempt == 2: raisetime.sleep(2)def extract_document_structure(self, text, paper_type="empirical"):fallbacks = {"empirical": ["Introduction", "Literature Review", "Methodology", "Results", "Discussion", "Conclusion"],"review": ["Introduction", "Theoretical Background", "Framework Development", "Future Directions", "Conclusion"],"generic": ["Introduction", "Main Body", "Discussion", "Conclusion"]}default_sections = fallbacks.get(paper_type, fallbacks["generic"])if not text or len(text.strip()) < 100:return default_sectionsmax_safe_chars = 50000if len(text) > max_safe_chars:head_size = int(max_safe_chars * 0.7)tail_size = int(max_safe_chars * 0.3)sampled_text = text[:head_size] + "\n\n...[CONTENT OMITTED]...\n\n" + text[-tail_size:]else:sampled_text = textsys_prompt = "You are an expert academic editor."user_prompt = f"""Analyze the following academic text and extract its core structural headings (top-level only).Rules:1. Ignore subheadings (e.g., 3.1, 3.2).2. Ignore front/back matter like 'Abstract', 'Keywords', or 'References'.3. Output the exact heading names separated by ' || '.4. Do NOT output any other text, JSON formatting, or markdown blocks.Example Output:Introduction || Theoretical Background || Method || Results || Discussion || ConclusionText snippet:{sampled_text}"""for attempt in range(2):try:response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=300)clean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()clean_resp = re.sub(r'^```.*|```$', '', clean_resp, flags=re.MULTILINE).strip()if '||' in clean_resp:headings = [h.strip() for h in clean_resp.split('||') if h.strip()]if len(headings) >= 3:return headingslist_matches = re.findall(r'^(?:\d+\.|[A-Z]\.)\s*(.+)$', clean_resp, re.MULTILINE)if list_matches and len(list_matches) >= 3:return [m.strip() for m in list_matches]except Exception as e:logging.warning(f"Structure extraction attempt {attempt + 1} failed: {e}")continuereturn default_sectionsdef reverse_engineer_section(self, reference_text, section_name):sys_prompt = "You are an expert academic reverse-engineer. Analyze the provided text from a top-tier journal paper section."user_prompt = f"""Target Section Type: {section_name}Analyze the following reference text and extract the structural and stylistic DNA:<REFERENCE_TEXT>{reference_text[:10000]}</REFERENCE_TEXT>Output ONLY a valid JSON object with the following schema:{{"tone_and_style": "Describe the writing style in 3-5 precise adjectives/phrases (e.g., highly objective, uses complex subordinate clauses, passive voice dominant).","reporting_structure": "Describe the sequence of information presented (e.g., 'Reports reliability first, then CFA fit indices, then structural paths').","few_shot_snippet": "Extract a highly representative, continuous 150-200 word snippet from the text that embodies its style perfectly."}}"""for attempt in range(3):response = self.call_deepseek(sys_prompt, user_prompt, temp=0.2)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)try:result = json.loads(clean)if "few_shot_snippet" in result: return resultexcept:time.sleep(1)return {"tone_and_style": "objective academic tone", "reporting_structure": "standard empirical reporting", "few_shot_snippet": ""}def synthesize_literature(self, topic, refs_text, user_core_literature=""):sys_prompt = "You are a top-tier academic researcher in Business Administration and Information Systems."user_injection = f"\n\nCRITICAL MANDATE: Prioritize and integrate the following User-Provided Core Literature:\n<USER_CORE_LITERATURE>\n{user_core_literature}\n</USER_CORE_LITERATURE>\n" if user_core_literature else ""user_prompt = f"""Topic: {topic}{user_injection}\nLiterature Metadata:\n<LIT_DATA>\n{refs_text}\n</LIT_DATA>\n\n{APP_CONFIG['deep_synthesis_directive']}"""return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)16 unmodified linestry:plan = json.loads(clean)if "structure" in plan: return planexcept Exception as e:time.sleep(2)raise ValueError("Outline Generation Failed. Invalid JSON structure.")def generate_search_queries(self, topic, keywords):sys_prompt = "You are an expert academic librarian. Generate English search queries."user_prompt = f"""Topic: {topic}\nKeywords: {keywords}\nGenerate exactly 3 concise English search queries (max 3-4 words each). Return ONLY a valid JSON array of strings."""for attempt in range(3):response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1 + attempt * 0.1)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)8 unmodified linesfinal_queries = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())]if final_queries: return final_queries[:3]time.sleep(1)logging.warning("LLM 检索词生成失败,启用动态正则特征提取...")combined_text = f"{topic} {keywords}"english_chunks = re.findall(r'[a-zA-Z0-9\s\-]{4,}', combined_text)clean_chunks = [chunk.strip() for chunk in english_chunks if len(chunk.strip()) >= 4 and self._is_english_dominant(chunk.strip())]return clean_chunks[:3] if clean_chunks else []def _fetch_s2_page(self, search_term, offset=0, limit=50):# 🚨 平权接入:S2 也采用随机抖动与 requests_get_with_retry 机制time.sleep(random.uniform(0.5, 2.0))headers = {}if self.s2_key and str(self.s2_key).strip(): headers["x-api-key"] = str(self.s2_key).strip()7 unmodified linesdynamic_email = f"ssci_researcher_{random.randint(10000, 99999)}@gmail.com"headers = {"User-Agent": f"mailto:{dynamic_email}"}if self.openalex_key: headers["Authorization"] = f"Bearer {self.openalex_key}"params = {"search": search_term,"per-page": self.lit_per_page,"page": page,"filter": filter_str}logging.info(f"🔍 [OpenAlex 串行检索] 关键词: '{search_term}', 页码: {page}")resp = self._requests_get_with_retry(self.openalex_api_url, headers=headers, params=params, timeout=15)return resp.json().get("results", [])2 unmodified lineswith self.lock: self.citation_map.clear()llm_rag_context = []seen_identifiers = set()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"]all_used_terms = set()for expansion_phase in range(3):if len(self.citation_map) >= min_required:breakif expansion_phase == 0:search_terms = self.generate_search_queries(topic, keywords)else:sys_prompt = "You are an expert academic librarian. The previous literature search yielded insufficient results. We must broaden the search scope."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."1 unmodified lineresponse = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)queries = json.loads(clean)if isinstance(queries, list):search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]else:search_terms = []except:fallback_queries = re.findall(r'"([a-zA-Z\s\-]+)"', response)search_terms = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())][:3]2 unmodified linesif not current_batch_terms: continuefor t in current_batch_terms: all_used_terms.add(t)# ==========================================# 🚨 第一阶段:主引擎 S2 检索 (提级)# ==========================================if not getattr(self, 's2_fused', False):for term in current_batch_terms:if len(self.citation_map) >= self.lit_target_papers: break64 unmodified lineslogging.warning("🚨 [全局熔断] S2 引擎物理熔断!将跳过 S2,移交 OpenAlex 备用引擎。")break# ==========================================# 🚨 移交网关与第二阶段:备用引擎 OpenAlex 检索 (降级兜底)# ==========================================if len(self.citation_map) < self.lit_target_papers and not getattr(self, 'oa_fused', False):for filter_str in filters_to_try:if len(self.citation_map) >= self.lit_target_papers: break26 unmodified lines27282930313211 unmodified lines44454647484950518 unmodified lines606162636465666768697071727314 unmodified lines88899091929333 unmodified lines12712812913013113213313413513613713813914014128 unmodified lines1701711721731741751761 unmodified line17817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721826 unmodified lines24524624724824925025125225325425525625725825926026133 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441516 unmodified lines4324334344354364374384394404414424438 unmodified lines4524534544554564574584594604614624637 unmodified lines4714724734744754764772 unmodified lines4804814824834844854864874884894904914921 unmodified line4944954964974984995005012 unmodified lines50450550650750850964 unmodified lines57457557657757857926 unmodified linesexcept ImportError:LANGDETECT_AVAILABLE = Falsefrom app_config import APP_CONFIGclass SSciPipelineAgent:11 unmodified linesself.ds_calls = 0self.oa_calls = 0self.s2_calls = 0self.s2_fused = Falseself.oa_fused = Falseself.citation_map = {}self.used_citations = set()self.lock = threading.RLock()8 unmodified linesself.s2_api_url = APP_CONFIG["s2_api_url"]self.global_memory = {"hypotheses": "", "variables": "", "model_summary": "","method_summary": "", "abstract_anchor": "", "conclusion_anchor": "","core_golden_metadata": []}try:self.tokenizer = tiktoken.get_encoding("cl100k_base")except:self.tokenizer = tiktoken.get_encoding("gpt2")def export_state(self):with self.lock:return {14 unmodified linesself.citation_map = state_dict.get("citation_map", {})self.used_citations = set(state_dict.get("used_citations", []))self.global_memory = state_dict.get("global_memory", self.global_memory)def _calc_paragraph_count(self, target_words, lang_hint="en"):words_per_para = 100 if lang_hint in ["ru", "kk"] else 13033 unmodified linesexcept Exception:return False@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)))def _requests_get_with_retry(self, url, headers=None, params=None, timeout=15):resp = requests.get(url, headers=headers, params=params, timeout=timeout)if resp.status_code == 429:logging.warning(f"⚠️ [API 限流] 触发 429,当前线程进入随机休眠退避。URL: {url}")resp.raise_for_status()if resp.status_code != 200:logging.error(f"❌ [API 错误] 状态码: {resp.status_code}, 响应: {resp.text}")resp.raise_for_status()return respdef _is_english_dominant(self, text):28 unmodified linesif len(tokens) <= max_tokens: return textreturn self.tokenizer.decode(tokens[:max_tokens])def _build_memory_context(self, section_name="", max_tokens=2500):memory_parts = []if self.global_memory["abstract_anchor"]: memory_parts.append(f"【PAPER ANCHOR - ABSTRACT】\n{self.global_memory['abstract_anchor']}")if self.global_memory["conclusion_anchor"]: memory_parts.append(f"【PAPER ANCHOR - EXPECTED CONCLUSION】\n{self.global_memory['conclusion_anchor']}")1 unmodified lineif self.global_memory["variables"]: memory_parts.append(f"【CORE CONSTRUCT DEFINITIONS】\n{self.global_memory['variables']}")if self.global_memory["model_summary"]: memory_parts.append(f"【RESEARCH MODEL】\n{self.global_memory['model_summary']}")if self.global_memory["method_summary"]: memory_parts.append(f"【METHODOLOGICAL SUMMARY】\n{self.global_memory['method_summary']}")golden_meta = self.global_memory.get("core_golden_metadata", [])if golden_meta and section_name:lower_sec = section_name.lower()injected_data = []if any(kw in lower_sec for kw in ["introduction", "background"]):for p in golden_meta:if p.get('future_gaps'): injected_data.append(f"[{p['title']}] Future Gaps: {p['future_gaps']}")if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE GAPS (FOR RESEARCH GAP FORMULATION)】\n" + "\n".join(injected_data))elif any(kw in lower_sec for kw in ["literature", "theor", "hypothesis", "review"]):for p in golden_meta:if p.get('theoretical_lens'): injected_data.append(f"[{p['title']}] Theoretical Lens: {p['theoretical_lens']}")if p.get('causal_pathways'): injected_data.append(f"[{p['title']}] Pathways: {p['causal_pathways']}")if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE THEORIES & PATHWAYS (USE FOR HYPOTHESIS DEDUCTION)】\n" + "\n".join(injected_data))elif any(kw in lower_sec for kw in ["method", "measure", "data", "sample"]):for p in golden_meta:if p.get('variables_and_measurements'): injected_data.append(f"[{p['title']}] Measurements: {p['variables_and_measurements']}")if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE MEASUREMENTS (USE FOR SCALE ADAPTATION DEFENSE)】\n" + "\n".join(injected_data))elif any(kw in lower_sec for kw in ["discussion", "conclusion", "implication", "result", "analysis"]):for p in golden_meta:if p.get('causal_pathways'): injected_data.append(f"[{p['title']}] Confirmed Pathways: {p['causal_pathways']}")if injected_data: memory_parts.append("【TARGETED INJECTION: CORE LITERATURE FINDINGS (COMPARE OUR RESULTS AGAINST THESE)】\n" + "\n".join(injected_data))full = "\n\n".join(memory_parts)if self._count_tokens(full) > max_tokens: return self._truncate_context(full, max_tokens)return fulldef call_deepseek(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3, model_name="deepseek-reasoner"):logging.info(f"🚀 [DeepSeek API] 准备调用 {model_name}, 提示词预计 Tokens: {self._count_tokens(user_prompt)}")for attempt in range(3):with self.lock: self.ds_calls += 1current_model = model_nameif attempt == 2 and model_name == "deepseek-reasoner":current_model = "deepseek-chat"26 unmodified linesdelta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})content = delta.get('content', '')if content: full_content += contentexcept Exception: passreturn full_content.strip()except Exception as e:logging.error(f"❌ [网络异常] 尝试 {attempt+1}/3 失败: {e}")if attempt == 2: raise etime.sleep(3 ** attempt)def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name="deepseek-reasoner"):temp = 0.3 if model_name == "deepseek-chat" else 0.2for attempt in range(3):with self.lock: self.ds_calls += 1current_model = model_nameif attempt >= 1 and model_name == "deepseek-reasoner":current_model = "deepseek-chat"33 unmodified linesif not in_think_block and content:yield contentexcept Exception: passreturnexcept GeneratorExit: raiseexcept Exception as e:logging.error(f"❌ [流式中断] 尝试 {attempt+1}/3 异常: {e}")if attempt == 2: raisetime.sleep(2)def extract_document_structure(self, text, paper_type="empirical"):fallbacks = {"empirical": ["Introduction", "Literature Review", "Methodology", "Results", "Discussion", "Conclusion"], "generic": ["Introduction", "Main Body", "Discussion", "Conclusion"]}default_sections = fallbacks.get(paper_type, fallbacks["generic"])if not text or len(text.strip()) < 100: return default_sectionsmax_safe_chars = 50000if len(text) > max_safe_chars:sampled_text = text[:int(max_safe_chars * 0.7)] + "\n\n...[CONTENT OMITTED]...\n\n" + text[-int(max_safe_chars * 0.3):]else: sampled_text = textsys_prompt = "You are an expert academic editor."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}"for attempt in range(2):try:response = self.call_deepseek(sys_prompt, user_prompt, max_tokens=300)clean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).strip()clean_resp = re.sub(r'^```.*|```$', '', clean_resp, flags=re.MULTILINE).strip()if '||' in clean_resp:headings = [h.strip() for h in clean_resp.split('||') if h.strip()]if len(headings) >= 3: return headingslist_matches = re.findall(r'^(?:\d+\.|[A-Z]\.)\s*(.+)$', clean_resp, re.MULTILINE)if list_matches and len(list_matches) >= 3: return [m.strip() for m in list_matches]except Exception: continuereturn default_sectionsdef reverse_engineer_section(self, reference_text, section_name):sys_prompt = "You are an expert academic reverse-engineer."user_prompt = f"Target Section: {section_name}\nAnalyze the reference text:\n<REFERENCE_TEXT>\n{reference_text[:10000]}\n</REFERENCE_TEXT>\nOutput ONLY a valid JSON object: {{\"tone_and_style\": \"...\", \"reporting_structure\": \"...\", \"few_shot_snippet\": \"...\"}}"for attempt in range(3):response = self.call_deepseek(sys_prompt, user_prompt, temp=0.2)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)try:result = json.loads(clean)if "few_shot_snippet" in result: return resultexcept: time.sleep(1)return {"tone_and_style": "objective academic tone", "reporting_structure": "standard empirical reporting", "few_shot_snippet": ""}def parse_user_core_literature(self, user_lit_text):if not user_lit_text.strip(): return ""sys_prompt = "You are an elite academic metadata extractor."user_prompt = f"""Analyze the following raw text extracted from user-uploaded core academic PDFs. There may be multiple papers.<RAW_TEXT>{user_lit_text[:30000]}</RAW_TEXT>Identify each distinct paper and extract its "Golden Metadata".Return ONLY a valid JSON array of objects. Schema MUST exactly match:[{{"title": "Full Paper Title","authors": ["Lastname, Firstname", "Lastname, F."],"year": "2023","venue": "Journal Name","abstract": "Brief summary of the paper.","core_thesis": "One precise sentence summarizing the core contribution.","theoretical_lens": "Identify the primary theoretical framework(s) applied (e.g., Resource-Based View, Social Exchange Theory).","variables_and_measurements": "List independent, dependent, mediator, and moderator variables. Include specific measurement items or scales if available.","causal_pathways": "List the significant causal relationships or hypotheses confirmed by the author (e.g., A positively impacts B, mediated by C).","future_gaps": "Summarize the limitations and future research directions explicitly stated by the author."}}]"""for attempt in range(2):try:response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1, model_name="deepseek-chat")clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)papers = json.loads(clean)self.global_memory["core_golden_metadata"] = papersrag_context = []for paper in papers:title = paper.get("title", "User Provided Document")year = paper.get("year", "n.d.")authors = paper.get("authors", ["User, Uploaded"])venue = paper.get("venue", "User Document")abstract = paper.get("abstract", "User provided core reference.")core_thesis = paper.get("core_thesis", "")if len(authors) == 1:author_str = authors[0]in_text = f"({authors[0].split(',')[0]}, {year})"elif len(authors) == 2:author_str = f"{authors[0]} & {authors[1]}"in_text = f"({authors[0].split(',')[0]} & {authors[1].split(',')[0]}, {year})"else:author_str = f"{authors[0]} et al."in_text = f"({authors[0].split(',')[0]} et al., {year})"apa_full = f"{author_str} ({year}). {title}. {venue}."with self.lock:cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"self.citation_map[cite_tag] = {"in_text": in_text, "ref": apa_full}self.used_citations.add(cite_tag)rag_context.append(f"{cite_tag} [USER CORE PAPER] Title: {title}. Core Thesis: {core_thesis}. Abstract: {abstract}")return "\n".join(rag_context)except Exception as e:logging.error(f"❌ 解析核心论文黄金元数据尝试 {attempt+1} 失败: {e}")time.sleep(2)return ""def synthesize_literature(self, topic, refs_text, user_core_literature=""):sys_prompt = "You are a top-tier academic researcher in Business Administration and Information Systems."user_injection = f"\n\nCRITICAL MANDATE: Prioritize and integrate the following User-Provided Core Literature raw text to deepen the theoretical analysis:\n<USER_CORE_LITERATURE>\n{user_core_literature[:20000]}\n</USER_CORE_LITERATURE>\n" if user_core_literature else ""user_prompt = f"""Topic: {topic}{user_injection}\nLiterature Metadata:\n<LIT_DATA>\n{refs_text}\n</LIT_DATA>\n\n{APP_CONFIG['deep_synthesis_directive']}"""return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)16 unmodified linestry:plan = json.loads(clean)if "structure" in plan: return planexcept Exception: time.sleep(2)raise ValueError("Outline Generation Failed. Invalid JSON structure.")def generate_search_queries(self, topic, keywords):sys_prompt = "You are an expert academic librarian. Generate English search queries."user_prompt = f"""Topic: {topic}\nKeywords: {keywords}\nGenerate exactly 3 concise English search queries. Return ONLY a valid JSON array of strings."""for attempt in range(3):response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1 + attempt * 0.1)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)8 unmodified linesfinal_queries = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())]if final_queries: return final_queries[:3]time.sleep(1)combined_text = f"{topic} {keywords}"english_chunks = re.findall(r'[a-zA-Z0-9\s\-]{4,}', combined_text)clean_chunks = [chunk.strip() for chunk in english_chunks if len(chunk.strip()) >= 4 and self._is_english_dominant(chunk.strip())]return clean_chunks[:3] if clean_chunks else []def _fetch_s2_page(self, search_term, offset=0, limit=50):time.sleep(random.uniform(0.5, 2.0))headers = {}if self.s2_key and str(self.s2_key).strip(): headers["x-api-key"] = str(self.s2_key).strip()7 unmodified linesdynamic_email = f"ssci_researcher_{random.randint(10000, 99999)}@gmail.com"headers = {"User-Agent": f"mailto:{dynamic_email}"}if self.openalex_key: headers["Authorization"] = f"Bearer {self.openalex_key}"params = {"search": search_term, "per-page": self.lit_per_page, "page": page, "filter": filter_str}logging.info(f"🔍 [OpenAlex 串行检索] 关键词: '{search_term}', 页码: {page}")resp = self._requests_get_with_retry(self.openalex_api_url, headers=headers, params=params, timeout=15)return resp.json().get("results", [])2 unmodified lineswith self.lock: self.citation_map.clear()llm_rag_context = []seen_identifiers = set()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"]all_used_terms = set()for expansion_phase in range(3):if len(self.citation_map) >= min_required: breakif expansion_phase == 0: search_terms = self.generate_search_queries(topic, keywords)else:sys_prompt = "You are an expert academic librarian. The previous literature search yielded insufficient results. We must broaden the search scope."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."1 unmodified lineresponse = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)clean = re.sub(r'^```json\s*|\s*```$', '', response.strip(), flags=re.IGNORECASE | re.MULTILINE)queries = json.loads(clean)if isinstance(queries, list): search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]else: search_terms = []except:fallback_queries = re.findall(r'"([a-zA-Z\s\-]+)"', response)search_terms = [q.strip() for q in fallback_queries if self._is_english_dominant(q.strip())][:3]2 unmodified linesif not current_batch_terms: continuefor t in current_batch_terms: all_used_terms.add(t)if not getattr(self, 's2_fused', False):for term in current_batch_terms:if len(self.citation_map) >= self.lit_target_papers: break64 unmodified lineslogging.warning("🚨 [全局熔断] S2 引擎物理熔断!将跳过 S2,移交 OpenAlex 备用引擎。")breakif len(self.citation_map) < self.lit_target_papers and not getattr(self, 'oa_fused', False):for filter_str in filters_to_try:if len(self.citation_map) >= self.lit_target_papers: break
core/pipeline_agent.py+121-119