Spaces:
Sleeping
Sleeping
Update core/pipeline_agent.py
Browse files13 unmodified lines141516171819206 unmodified lines272829303132333435363738394041424344456 unmodified lines525354555657582 unmodified lines6162636465666768697071727374757677787980818283841 unmodified line868788899091929394959697989910010110210310410510610710810911011111211311 unmodified lines1251261271281291301311327 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873884 unmodified lines3933943953963973983994004014024034044058 unmodified lines4144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594603 unmodified lines46446546646746846947047147247347447547647747847935 unmodified lines5155165175185195205215225235242 unmodified lines5275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126138 unmodified lines6226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516523 unmodified lines6566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477489 unmodified lines7587597607617627637647657667677687697707717727737747757767777787797807817827837849 unmodified lines7947957967977987998008018028038048055 unmodified lines8118128138148158168178182 unmodified lines8218228238248258268278286 unmodified lines83583683783883984013 unmodified linesimport loggingfrom tenacity import retry, stop_after_attempt, wait_random_exponential, wait_exponential, retry_if_exception_type# 配置全局日志logging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(message)s",6 unmodified linesexcept ImportError:LANGDETECT_AVAILABLE = Falsefrom app_config import APP_CONFIGdef count_words_adaptive(text, lang_hint="en"):"""语言感知的字数/字符数统计"""if not text:return 0if lang_hint in ["zh", "ru", "kk"]:chars = re.findall(r'[\u4e00-\u9fff\u0400-\u052F]', text)return len(chars)else:return len(text.split())class SSciPipelineAgent:def __init__(self, ds_key, s2_key=""):6 unmodified linesself.openalex_key = st.secrets.get("OA_API_KEY", "")except:self.openalex_key = os.environ.get("OA_API_KEY", "")self.ds_calls = 0self.oa_calls = 0self.s2_calls = 02 unmodified linesself.citation_map = {}self.used_citations = set()self.lock = threading.RLock()self.lit_target_papers = APP_CONFIG["lit_target_papers"]self.lit_per_page = APP_CONFIG["lit_per_page"]self.lit_max_workers = APP_CONFIG["lit_max_workers"]self.lit_max_page_batches = APP_CONFIG["lit_max_page_batches"]self.chunk_words_default = APP_CONFIG["chunk_words_default"]self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]self.openalex_api_url = APP_CONFIG["openalex_api_url"]self.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:1 unmodified linedef _extract_json_from_text(self, text):"""无敌 JSON 提取器:外科手术式提取,彻底无视大模型废话前缀和 Markdown 包装"""if not text:return Nonetext = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)start_dict = text.find('{')end_dict = text.rfind('}')start_list = text.find('[')end_list = text.rfind(']')dict_len = end_dict - start_dict if start_dict != -1 and end_dict != -1 else -1list_len = end_list - start_list if start_list != -1 and end_list != -1 else -1if dict_len == -1 and list_len == -1:return Nonetry:if dict_len > list_len:json_str = text[start_dict:end_dict + 1]return json.loads(json_str)else:json_str = text[start_list:end_list + 1]return json.loads(json_str)except Exception as e:logging.error(f"❌ JSON 外科提取彻底失败: {e} | 原文片段: {text[:200]}...")11 unmodified lines}def load_state(self, state_dict):if not state_dict:returnwith self.lock:self.ds_calls = state_dict.get("ds_calls", 0)self.oa_calls = state_dict.get("oa_calls", 0)7 unmodified linesreturn max(2, int(target_words / words_per_para))def _translate_text(self, text, target_lang, max_tokens=2000):if not text.strip():return ""sys_prompt = f"Translate the following text into {target_lang}. Preserve all formatting, line breaks, and [CITE-XX] tags exactly. Output ONLY the translation."return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2, model_name="deepseek-chat")@retry(stop=stop_after_attempt(3),wait=wait_exponential(multiplier=1, min=2, max=10),retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError)))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):if not text:return Falseif LANGDETECT_AVAILABLE:try:return detect(text) == 'en'except:passalpha_chars = sum(1 for c in str(text) if c.isalpha())if alpha_chars == 0:return Falsereturn (len(re.findall(r'[a-zA-Z]', str(text))) / alpha_chars) > 0.8def _extract_memory_from_text(self, text, section_name):lower_sec = section_name.lower()if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)if hypo_matches:self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])if any(kw in lower_sec for kw in ["method", "measure", "variable"]):var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)if var_matches:self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])if "model" in lower_sec or "figure" in lower_sec:model_match = re.search(r'(Figure\s*\d+[^\.]+\.)', text, re.IGNORECASE)if model_match:self.global_memory["model_summary"] = model_match.group(1)if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)if method_match:self.global_memory["method_summary"] = method_match.group(1)def _count_tokens(self, text):return len(self.tokenizer.encode(text))def _truncate_context(self, text, max_tokens):tokens = self.tokenizer.encode(text)if 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']}")if self.global_memory["hypotheses"]:memory_parts.append(f"【ESTABLISHED HYPOTHESES】\n{self.global_memory['hypotheses']}")if 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 isinstance(golden_meta, list) 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 isinstance(p, dict) and p.get('future_gaps'):injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict):if p.get('theoretical_lens'):injected_data.append(f"[{p.get('title', 'Ref')}] Theoretical Lens: {p['theoretical_lens']}")if p.get('causal_pathways'):injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict) and p.get('variables_and_measurements'):injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict) and p.get('causal_pathways'):injected_data.append(f"[{p.get('title', 'Ref')}] 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"temp = 0.3logging.warning("⚠️ [算力降级] Reasoner 节点拥挤,强制降级为 deepseek-chat 执行本节点!")payload = {"model": current_model,"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],"max_tokens": max_tokens,"stream": True}if current_model != "deepseek-reasoner":payload["temperature"] = tempfull_content = ""try:with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 180)) as response:if response.status_code != 200:error_msg = f"DeepSeek API 拒绝访问 (状态码: {response.status_code})。详情: {response.text}"logging.error(f"❌ 尝试 {attempt+1}/3 失败: {error_msg}")if attempt == 2:st.toast(f"❌ API 彻底熔断: {error_msg}", icon="🚨")raise requests.exceptions.HTTPError(error_msg)time.sleep(3 ** attempt + random.uniform(0, 1))continuefor line in response.iter_lines():if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':try:delta = 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 + random.uniform(0, 1))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"temp = 0.3logging.warning(f"⚠️ [流式降级] {model_name} 连接失败,强制切换至 deepseek-chat。")payload = {"model": current_model,"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],"max_tokens": max_tokens,"stream": True}if current_model != "deepseek-reasoner":payload["temperature"] = tempin_think_block = Falsetry:with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 300)) as response:if response.status_code != 200:logging.error(f"❌ [流式 API 错误] 状态码: {response.status_code}, 响应: {response.text}")if attempt == 2:response.raise_for_status()time.sleep(2 + random.uniform(0, 1))continuefor line in response.iter_lines():if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':try:delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})content = delta.get('content', '')if not content:continueif '<think>' in content:in_think_block = Truecontent = content.replace('<think>', '')if '</think>' in content:in_think_block = Falsecontent = content.replace('</think>', '')if not content:continueif not in_think_block and content:yield contentexcept Exception:passreturnexcept GeneratorExit:raiseexcept (requests.exceptions.ConnectionError, ConnectionResetError) as e:logging.error(f"❌ [流式连接重置] 尝试 {attempt+1}/3 异常: {e}")if attempt == 2:raisetime.sleep(2 ** attempt + random.uniform(0, 1))continueexcept Exception as e:logging.error(f"❌ [流式中断] 尝试 {attempt+1}/3 异常: {e}")if attempt == 2:raisetime.sleep(2 + random.uniform(0, 1))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}"4 unmodified linesclean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).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):8 unmodified linesreturn {"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. First summarize each paper in 2-3 sentences, then extract metadata."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[:20000]}</RAW_TEXT>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.Return ONLY a valid JSON array."""for attempt in range(2):try:response = self.call_deepseek(sys_prompt, user_prompt, temp=0.1, model_name="deepseek-chat")papers = self._extract_json_from_text(response)if not papers:raise ValueError("Extracted JSON is null or invalid")if isinstance(papers, dict):for v in papers.values():if isinstance(v, list):papers = vbreakif not isinstance(papers, list):papers = [papers]self.global_memory["core_golden_metadata"] = papersrag_context = []for paper in papers:if not isinstance(paper, dict):continuetitle = 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})"3 unmodified lineselse: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}")35 unmodified linesqueries = self._extract_json_from_text(response)if queries and isinstance(queries, list) and len(queries) > 0:final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(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())]2 unmodified linesdef _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()params = {"query": search_term, "offset": offset, "limit": limit, "fields": "title,authors,year,venue,abstract,externalIds"}logging.info(f"🔍 [S2 串行检索] 关键词: '{search_term}', Offset: {offset}")resp = self._requests_get_with_retry(f"{self.s2_api_url}/paper/search", headers=headers, params=params, timeout=15)return resp.json().get("data", [])def _fetch_openalex_page(self, search_term, page, filter_str):time.sleep(random.uniform(1.0, 3.0))dynamic_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", [])def fetch_references_parallel(self, topic, keywords, min_required=50, progress_callback=None):with self.lock:self.citation_map.clear()self.s2_fused = Falseself.oa_fused = Falsellm_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:breakself.s2_fused = Falseself.oa_fused = Falseif 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."response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)queries = self._extract_json_from_text(response)if queries and isinstance(queries, list):search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]else: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]current_batch_terms = [t for t in search_terms if t not in all_used_terms]if not current_batch_terms:continuefor t in current_batch_terms:all_used_terms.add(t)if not self.s2_fused:for term in current_batch_terms:if len(self.citation_map) >= self.lit_target_papers:breakif self.s2_fused:breakoffset = 0consecutive_400 = 0while len(self.citation_map) < self.lit_target_papers and offset < 500:try:papers = self._fetch_s2_page(term, offset=offset, limit=50)if not papers:breakconsecutive_400 = 0added_in_this_batch = 0for paper in papers:if len(self.citation_map) >= self.lit_target_papers:breaktitle = paper.get("title")year = paper.get("year")if not title or not year:continueidentifier = (title.lower().strip(), str(year))if identifier in seen_identifiers:continueseen_identifiers.add(identifier)authors = paper.get("authors", [])8 unmodified lineselse:last_names.append(name)formatted_authors.append(name)if not last_names:continueyear_str = str(year)venue = paper.get("venue") or "Journal"doi = paper.get("externalIds", {}).get("DOI", "")abstract = paper.get("abstract", "")if len(last_names) == 1:in_text = f"({last_names[0]}, {year_str})"elif len(last_names) == 2:in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"else:in_text = f"({last_names[0]} et al., {year_str})"if len(formatted_authors) > 2:author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]elif len(formatted_authors) == 2:author_str = " & ".join(formatted_authors)else:author_str = formatted_authors[0]apa_full = f"{author_str} ({year_str}). {title}. {venue}."if doi:apa_full += f" https://doi.org/{doi}"with self.lock:cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"3 unmodified linesabs_snippet = " ".join(abstract.split()[:60]) + "..." if abstract else "Empirical data available."llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")if added_in_this_batch == 0:offset += 50continueoffset += 50if progress_callback:progress_callback()except requests.exceptions.HTTPError as e:if e.response.status_code == 400:error_msg = e.response.textif "offset is not available" in error_msg or "limit and/or offset" in error_msg:logging.info(f"ℹ️ [S2] 关键词 '{term}' 已无更多结果 (offset={offset}),正常结束。")breakelse:consecutive_400 += 1logging.warning(f"⚠️ [S2] 收到未知 400 错误: {error_msg},第 {consecutive_400} 次")if consecutive_400 >= 2:logging.error("连续 400 错误,跳过该检索词。")breaktime.sleep(2)continueelif e.response.status_code == 429:logging.warning(f"⚠️ [S2 限流] 等待 5 秒后重试...")time.sleep(5)continueelse:logging.error(f"❌ [S2 致命错误] 状态码 {e.response.status_code},熔断 S2。")self.s2_fused = Truebreakexcept Exception as e:logging.error(f"❌ [S2 网络异常] {e},熔断 S2。")self.s2_fused = Truebreakif len(self.citation_map) < self.lit_target_papers and not self.oa_fused:for filter_str in filters_to_try:if len(self.citation_map) >= self.lit_target_papers:breakif self.oa_fused:breakfor term in current_batch_terms:if len(self.citation_map) >= self.lit_target_papers:breakif self.oa_fused:breakpage_batch = 1consecutive_failures = 0while len(self.citation_map) < self.lit_target_papers and page_batch <= self.lit_max_page_batches:batch_pages = range((page_batch - 1) * 5 + 1, page_batch * 5 + 1)raw_results = []for p in batch_pages:if len(self.citation_map) >= self.lit_target_papers:breakfor retry in range(3):try:res = self._fetch_openalex_page(term, p, filter_str)raw_results.extend(res)consecutive_failures = 0breakexcept Exception as e:logging.warning(f"⚠️ OpenAlex 页 {p} 第 {retry+1} 次失败: {e}")if retry == 2:consecutive_failures += 1else:time.sleep(2 ** retry)if consecutive_failures >= 3:logging.error("OpenAlex 连续失败,熔断。")self.oa_fused = Truebreakif self.oa_fused:breakadded_in_this_batch = 0for item in raw_results:if len(self.citation_map) >= self.lit_target_papers:breaktitle = item.get("title")if not title or not self._is_english_dominant(title):continueyear = item.get("publication_year", "n.d.")identifier = (title.lower().strip(), str(year))if identifier in seen_identifiers:continueseen_identifiers.add(identifier)venue = ((item.get("primary_location") or {}).get("source") or {}).get("display_name", "Journal")9 unmodified lineselse:last_names.append(name_raw)formatted_authors.append(name_raw)if not formatted_authors:continueyear_str = str(year)if len(last_names) == 1:in_text = f"({last_names[0]}, {year_str})"elif len(last_names) == 2:in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"else:in_text = f"({last_names[0]} et al., {year_str})"if len(formatted_authors) > 2:author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]elif len(formatted_authors) == 2:author_str = " & ".join(formatted_authors)else:author_str = formatted_authors[0]apa_full = f"{author_str} ({year_str}). {title}. {venue}."if doi_clean:apa_full += f" https://doi.org/{doi_clean}"with self.lock:cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"9 unmodified linesraw_abstract = " ".join([word for pos, word in word_index])abs_snippet = " ".join(str(raw_abstract).split()[:60]) + "..." if raw_abstract else "Empirical data available."llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")if added_in_this_batch == 0:breakpage_batch += 1if progress_callback:progress_callback()return "\n".join(llm_rag_context)5 unmodified linesdef bracket_replacer(match):inner = match.group(1)if not re.search(r'CITE-\d+', inner, re.IGNORECASE):return match.group(0)cites = re.findall(r'CITE-\d+', inner, flags=re.IGNORECASE)resolved = []for c in cites:2 unmodified linesif full_c in self.citation_map:self.used_citations.add(full_c)resolved.append(self.citation_map[full_c]["in_text"].strip("()"))else:resolved.append(c.upper())return "(" + "; ".join(resolved) + ")"text = re.sub(r'\[(.*?)\]', bracket_replacer, text)6 unmodified linesself.used_citations.add(full_c)return self.citation_map[full_c]["in_text"]return match.group(0)text = re.sub(r'CITE-\d+', loose_replacer, text, flags=re.IGNORECASE)return text13 unmodified lines141516171819206 unmodified lines27282930313233346 unmodified lines414243444546472 unmodified lines5051525354555657585960616263646566676869707172731 unmodified line7576777879808182838485868788899091929394959697989910010110210310410510610710811 unmodified lines1201211221231241251267 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363374 unmodified lines3423433443453463473483493503518 unmodified lines3603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144153 unmodified lines41942042142242342442542642742842943043143243343435 unmodified lines4704714724734744754764774782 unmodified lines4814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535548 unmodified lines5635645655665675685695705715725735745755765775785795805815825835845853 unmodified lines5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396409 unmodified lines6506516526536546556566576586596606616626636646656666676689 unmodified lines6786796806816826836846856866875 unmodified lines6936946956966976986992 unmodified lines7027037047057067077086 unmodified lines71571671771871913 unmodified linesimport loggingfrom tenacity import retry, stop_after_attempt, wait_random_exponential, wait_exponential, retry_if_exception_type# 配置全局日志,直接输出到 HF 容器标准输出logging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(message)s",6 unmodified linesexcept ImportError:LANGDETECT_AVAILABLE = False# 🚨 核心修复:更正为从 config 导入from config import APP_CONFIGclass SSciPipelineAgent:def __init__(self, ds_key, s2_key=""):6 unmodified linesself.openalex_key = st.secrets.get("OA_API_KEY", "")except:self.openalex_key = os.environ.get("OA_API_KEY", "")self.ds_calls = 0self.oa_calls = 0self.s2_calls = 02 unmodified linesself.citation_map = {}self.used_citations = set()self.lock = threading.RLock()self.lit_target_papers = APP_CONFIG["lit_target_papers"]self.lit_per_page = APP_CONFIG["lit_per_page"]self.lit_max_workers = APP_CONFIG["lit_max_workers"]self.lit_max_page_batches = APP_CONFIG["lit_max_page_batches"]self.chunk_words_default = APP_CONFIG["chunk_words_default"]self.chunk_words_cyrillic = APP_CONFIG["chunk_words_cyrillic"]self.deepseek_api_url = APP_CONFIG["deepseek_api_url"]self.openalex_api_url = APP_CONFIG["openalex_api_url"]self.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:1 unmodified linedef _extract_json_from_text(self, text):"""无敌 JSON 提取器:外科手术式提取,彻底无视大模型废话前缀和 Markdown 包装"""if not text: return None# 1. 强制清理潜在的 <think> 标签残留,防止干扰括号匹配text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)# 🚨 核心修复:强力清洗 Markdown 代码块标记,防止 JSON 解析崩溃text = re.sub(r'```json\n?', '', text, flags=re.IGNORECASE)text = re.sub(r'```\n?', '', text)# 2. 寻找最外层的 {} 或 [] 边界start_dict = text.find('{')end_dict = text.rfind('}')start_list = text.find('[')end_list = text.rfind(']')dict_len = end_dict - start_dict if start_dict != -1 and end_dict != -1 else -1list_len = end_list - start_list if start_list != -1 and end_list != -1 else -1if dict_len == -1 and list_len == -1:return Nonetry:# 3. 强行截取最长匹配的 JSON 字符串进行解析if dict_len > list_len:json_str = text[start_dict:end_dict+1]return json.loads(json_str)else:json_str = text[start_list:end_list+1]return json.loads(json_str)except Exception as e:logging.error(f"❌ JSON 外科提取彻底失败: {e} | 原文片段: {text[:200]}...")11 unmodified lines}def load_state(self, state_dict):if not state_dict: returnwith self.lock:self.ds_calls = state_dict.get("ds_calls", 0)self.oa_calls = state_dict.get("oa_calls", 0)7 unmodified linesreturn max(2, int(target_words / words_per_para))def _translate_text(self, text, target_lang, max_tokens=2000):if not text.strip(): return ""sys_prompt = f"Translate the following text into {target_lang}. Preserve all formatting, line breaks, and [CITE-XX] tags exactly. Output ONLY the translation."return self.call_deepseek(sys_prompt, text, max_tokens=max_tokens, temp=0.2, model_name="deepseek-chat")@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()# 🚨 核心修复:静默拦截 S2 的 400 分页终点错误,防止上层误判为网络异常引发重试熔断if resp.status_code == 400 and "Requested data for this limit" in resp.text:return respif resp.status_code != 200:logging.error(f"❌ [API 错误] 状态码: {resp.status_code}, 响应: {resp.text}")resp.raise_for_status()return respdef _is_english_dominant(self, text):if not text: return Falseif LANGDETECT_AVAILABLE:try: return detect(text) == 'en'except: passalpha_chars = sum(1 for c in str(text) if c.isalpha())if alpha_chars == 0: return Falsereturn (len(re.findall(r'[a-zA-Z]', str(text))) / alpha_chars) > 0.8def _extract_memory_from_text(self, text, section_name):lower_sec = section_name.lower()if any(kw in lower_sec for kw in ["introduction", "literature", "hypothesis"]):hypo_matches = re.findall(r'(H\d+[:\s].*?)(?=\n|$)', text, re.IGNORECASE)if hypo_matches: self.global_memory["hypotheses"] = "\n".join(hypo_matches[:10])if any(kw in lower_sec for kw in ["method", "measure", "variable"]):var_matches = re.findall(r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:was|is|refers to)\s+([^\.]+\.)', text)if var_matches: self.global_memory["variables"] = "\n".join([f"- {v[0]}: {v[1][:100]}" for v in var_matches[:8]])if "model" in lower_sec or "figure" in lower_sec:model_match = re.search(r'(Figure\s*\d+[^\.]+\.)', text, re.IGNORECASE)if model_match: self.global_memory["model_summary"] = model_match.group(1)if any(kw in lower_sec for kw in ["method", "sample", "procedure"]):method_match = re.search(r'(sample\s+consisted\s+of[^\.]+\.)', text, re.IGNORECASE)if method_match: self.global_memory["method_summary"] = method_match.group(1)def _count_tokens(self, text):return len(self.tokenizer.encode(text))def _truncate_context(self, text, max_tokens):tokens = self.tokenizer.encode(text)if 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']}")if self.global_memory["hypotheses"]: memory_parts.append(f"【ESTABLISHED HYPOTHESES】\n{self.global_memory['hypotheses']}")if 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 isinstance(golden_meta, list) 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 isinstance(p, dict) and p.get('future_gaps'): injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict):if p.get('theoretical_lens'): injected_data.append(f"[{p.get('title', 'Ref')}] Theoretical Lens: {p['theoretical_lens']}")if p.get('causal_pathways'): injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict) and p.get('variables_and_measurements'): injected_data.append(f"[{p.get('title', 'Ref')}] 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 isinstance(p, dict) and p.get('causal_pathways'): injected_data.append(f"[{p.get('title', 'Ref')}] 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"temp = 0.3logging.warning("⚠️ [算力降级] Reasoner 节点拥挤,强制降级为 deepseek-chat 执行本节点!")payload = {"model": current_model,"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],"max_tokens": max_tokens,"stream": True}if current_model != "deepseek-reasoner":payload["temperature"] = tempfull_content = ""try:with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 180)) as response:if response.status_code != 200:error_msg = f"DeepSeek API 拒绝访问 (状态码: {response.status_code})。详情: {response.text}"logging.error(f"❌ 尝试 {attempt+1}/3 失败: {error_msg}")if attempt == 2:st.toast(f"❌ API 彻底熔断: {error_msg}", icon="🚨")raise requests.exceptions.HTTPError(error_msg)time.sleep(3 ** attempt)continuefor line in response.iter_lines():if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':try:delta = 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"temp = 0.3logging.warning(f"⚠️ [流式降级] {model_name} 连接失败,强制切换至 deepseek-chat。")payload = {"model": current_model,"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],"max_tokens": max_tokens,"stream": True}if current_model != "deepseek-reasoner":payload["temperature"] = tempin_think_block = Falsetry:with requests.post(self.deepseek_api_url, headers={"Authorization": f"Bearer {self.ds_key}"}, json=payload, stream=True, timeout=(15, 300)) as response:if response.status_code != 200:logging.error(f"❌ [流式 API 错误] 状态码: {response.status_code}, 响应: {response.text}")if attempt == 2: response.raise_for_status()time.sleep(2)continuefor line in response.iter_lines():if line and line.decode('utf-8').startswith('data: ') and line.decode('utf-8') != 'data: [DONE]':try:delta = json.loads(line.decode('utf-8')[6:])['choices'][0].get('delta', {})content = delta.get('content', '')if not content: continueif '<think>' in content:in_think_block = Truecontent = content.replace('<think>', '')if '</think>' in content:in_think_block = Falsecontent = content.replace('</think>', '')if not content: continueif 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}"4 unmodified linesclean_resp = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL).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):8 unmodified linesreturn {"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")papers = self._extract_json_from_text(response)if not papers: raise ValueError("Extracted JSON is null or invalid")# 修复可能包裹在 dict 中的情况 (e.g., {"papers": [...]})if isinstance(papers, dict):for v in papers.values():if isinstance(v, list):papers = vbreakif not isinstance(papers, list): papers = [papers]self.global_memory["core_golden_metadata"] = papersrag_context = []for paper in papers:if not isinstance(paper, dict): continuetitle = 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})"3 unmodified lineselse: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}")35 unmodified linesqueries = self._extract_json_from_text(response)if queries and isinstance(queries, list) and len(queries) > 0:final_queries = [str(q).strip() for q in queries if self._is_english_dominant(str(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())]2 unmodified linesdef _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()params = {"query": search_term, "offset": offset, "limit": limit, "fields": "title,authors,year,venue,abstract,externalIds"}logging.info(f"🔍 [S2 串行检索] 关键词: '{search_term}', Offset: {offset}")resp = self._requests_get_with_retry(f"{self.s2_api_url}/paper/search", headers=headers, params=params, timeout=15)# 🚨 核心修复:处理被底层的 400 状态码静默拦截返回的结果if resp.status_code == 400:logging.info(f"ℹ️ [S2] 关键词 '{search_term}' 已无更多结果 (offset={offset}),正常结束。")return []return resp.json().get("data", [])def _fetch_openalex_page(self, search_term, page, filter_str):time.sleep(random.uniform(1.0, 3.0))dynamic_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", [])def fetch_references_parallel(self, topic, keywords, min_required=50, progress_callback=None):with 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."response = self.call_deepseek(sys_prompt, user_prompt, temp=0.5)queries = self._extract_json_from_text(response)if queries and isinstance(queries, list):search_terms = [str(q).strip() for q in queries if self._is_english_dominant(str(q).strip())][:3]else: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]current_batch_terms = [t for t in search_terms if t not in all_used_terms]if 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: breakif getattr(self, 's2_fused', False): breakoffset = 0while len(self.citation_map) < self.lit_target_papers and offset < 500:try:papers = self._fetch_s2_page(term, offset=offset, limit=50)if not papers: breakadded_in_this_batch = 0for paper in papers:if len(self.citation_map) >= self.lit_target_papers: breaktitle = paper.get("title")year = paper.get("year")if not title or not year: continueidentifier = (title.lower().strip(), str(year))if identifier in seen_identifiers: continueseen_identifiers.add(identifier)authors = paper.get("authors", [])8 unmodified lineselse:last_names.append(name)formatted_authors.append(name)if not last_names: continueyear_str = str(year)venue = paper.get("venue") or "Journal"doi = paper.get("externalIds", {}).get("DOI", "")abstract = paper.get("abstract", "")if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"else: in_text = f"({last_names[0]} et al., {year_str})"if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)else: author_str = formatted_authors[0]apa_full = f"{author_str} ({year_str}). {title}. {venue}."if doi: apa_full += f" https://doi.org/{doi}"with self.lock:cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"3 unmodified linesabs_snippet = " ".join(abstract.split()[:60]) + "..." if abstract else "Empirical data available."llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")if added_in_this_batch == 0: breakoffset += 50if progress_callback: progress_callback()except Exception as e:logging.error(f"❌ Semantic Scholar API 拒绝响应或异常: {e}")self.s2_fused = Truelogging.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: breakif getattr(self, 'oa_fused', False): breakfor term in current_batch_terms:if len(self.citation_map) >= self.lit_target_papers: breakif getattr(self, 'oa_fused', False): breakpage_batch = 1while len(self.citation_map) < self.lit_target_papers and page_batch <= self.lit_max_page_batches:batch_pages = range((page_batch-1)*5 + 1, page_batch*5 + 1)raw_results = []for p in batch_pages:if len(self.citation_map) >= self.lit_target_papers: breaktry:res = self._fetch_openalex_page(term, p, filter_str)raw_results.extend(res)except Exception as e:logging.error(f"❌ OpenAlex API 拒绝响应: {e}")self.oa_fused = Truelogging.warning("🚨 [全局熔断] OpenAlex 引擎也发生物理熔断!")breakif getattr(self, 'oa_fused', False): breakadded_in_this_batch = 0for item in raw_results:if len(self.citation_map) >= self.lit_target_papers: breaktitle = item.get("title")if not title or not self._is_english_dominant(title): continueyear = item.get("publication_year", "n.d.")identifier = (title.lower().strip(), str(year))if identifier in seen_identifiers: continueseen_identifiers.add(identifier)venue = ((item.get("primary_location") or {}).get("source") or {}).get("display_name", "Journal")9 unmodified lineselse:last_names.append(name_raw)formatted_authors.append(name_raw)if not formatted_authors: continueyear_str = str(year)if len(last_names) == 1: in_text = f"({last_names[0]}, {year_str})"elif len(last_names) == 2: in_text = f"({last_names[0]} & {last_names[1]}, {year_str})"else: in_text = f"({last_names[0]} et al., {year_str})"if len(formatted_authors) > 2: author_str = ", ".join(formatted_authors[:-1]) + ", & " + formatted_authors[-1]elif len(formatted_authors) == 2: author_str = " & ".join(formatted_authors)else: author_str = formatted_authors[0]apa_full = f"{author_str} ({year_str}). {title}. {venue}."if doi_clean: apa_full += f" https://doi.org/{doi_clean}"with self.lock:cite_tag = f"[CITE-{len(self.citation_map)+1:02d}]"9 unmodified linesraw_abstract = " ".join([word for pos, word in word_index])abs_snippet = " ".join(str(raw_abstract).split()[:60]) + "..." if raw_abstract else "Empirical data available."llm_rag_context.append(f"{cite_tag} Title: {title}. Focus: {abs_snippet}")if added_in_this_batch == 0: breakpage_batch += 1if progress_callback: progress_callback()return "\n".join(llm_rag_context)5 unmodified linesdef bracket_replacer(match):inner = match.group(1)if not re.search(r'CITE-\d+', inner, re.IGNORECASE): return match.group(0)cites = re.findall(r'CITE-\d+', inner, flags=re.IGNORECASE)resolved = []for c in cites:2 unmodified linesif full_c in self.citation_map:self.used_citations.add(full_c)resolved.append(self.citation_map[full_c]["in_text"].strip("()"))else: resolved.append(c.upper())return "(" + "; ".join(resolved) + ")"text = re.sub(r'\[(.*?)\]', bracket_replacer, text)6 unmodified linesself.used_citations.add(full_c)return self.citation_map[full_c]["in_text"]return match.group(0)text = re.sub(r'CITE-\d+', loose_replacer, text, flags=re.IGNORECASE)return text
core/pipeline_agent.py+213-334