Spaces:
Sleeping
Sleeping
A5-R3-R4C dormant ModelPolicy v2 execution seam
Browse filesFiles changed (6)
2887 unmodified lines2888288928902891289228932894289528962897289822 unmodified lines292129222923292429252926734 unmodified lines366136623663366436653666235 unmodified lines390239033904390539063907316 unmodified lines4224422542264227422842292887 unmodified linesroutes = model.get("routes") if isinstance(model.get("routes"), dict) else {}if not routes:raise RuntimeError("trusted_task_policy_model_routes_missing")# A5-R3-R3A closes snapshot identity only. It deliberately does not# reinterpret fine-grained logical-node routes as the legacy coarse# capability roles. Product execution remains fail-closed until the# separate logical-node execution contract is implemented.raise RuntimeError("trusted_task_policy_model_route_contract_not_ready")def _run_impl(self) -> dict[str, Any]:req = self.request22 unmodified linesagent = SSciPipelineAgent(ds_key, s2_key)self.agent = agentagent.set_model_policy_snapshot(plan_policy_snapshot)agent.set_cancel_checker(self.cancel_checker)# DeepSeek/search activity marks the executor as genuinely alive; the# heartbeat thread decides separately when to renew D1's lease.734 unmodified lines# glossary order deterministic and avoids sharing mutable writer state.translation_agent = SSciPipelineAgent(ds_key, s2_key)translation_agent.set_model_policy_snapshot(plan_policy_snapshot)self.translation_agent = translation_agenttranslation_agent.set_execution_progress_hook(lambda: self._progress_activity())translation_agent.set_cancel_checker(lambda: self.cancel_checker())235 unmodified linesfor word in ["abstract", "keyword", "conclusion", "references", "appendix"])section_id = str(sec.get("section_id") or "")planned_items = [item for item in list(citation_plan.get(display_name, []))if agent.citation_source_role_eligible(316 unmodified linesagent.stream_deepseek(sys_prompt, candidate_user_prompt, max_tokens=7000,model_role="writing", thinking=False, allow_fallback=False,),preview_prefix=full_draft_en + prefix,preview_stage=(display_name if section_attempt == 1 else f"{display_name}:retry"),2887 unmodified lines2888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294022 unmodified lines29632964296529662967296829692970734 unmodified lines37053706370737083709371037113712235 unmodified lines394839493950395139523953395439553956316 unmodified lines42734274427542764277427842792887 unmodified linesroutes = model.get("routes") if isinstance(model.get("routes"), dict) else {}if not routes:raise RuntimeError("trusted_task_policy_model_routes_missing")if str(snapshot.get("model_policy_version") or "") not in {"model-standard-v2", "model-flagship-v2"}:# Preserve the dormant R3A v1 fail-closed contract; only v2 may# cross the new trusted logical-node execution seam.raise RuntimeError("trusted_task_policy_model_route_contract_not_ready")if str(model.get("provider_catalog_version") or "") != "deepseek-v4-concrete-v1":raise RuntimeError("trusted_task_policy_provider_catalog_invalid")return snapshot@staticmethoddef _section_logical_node(mode: str, section_id: str, subsection_id: str | None = None) -> str | None:"""Map academic topology to a tier-neutral writer logical node."""mode = str(mode or "").strip().lower()section_id = str(section_id or "").strip().lower()subsection_id = str(subsection_id or "").strip().lower()if mode == "amj":if section_id in {"introduction", "theory"}:return "core_section_writing"if section_id == "methodology":return "methods_writing"if section_id == "results":return "quantitative_results_writing"if section_id == "discussion":if subsection_id in {"practical_implications", "limitations"}:return "ordinary_section_writing"return "core_section_writing"if section_id == "conclusion":return "ordinary_section_writing"elif mode == "asq":if section_id in {"introduction", "theoretical_framing"}:return "core_section_writing"if section_id == "methods":return "methods_writing"if section_id == "findings":if subsection_id == "emergent_model":return "core_section_writing"return "evidence_rich_findings_narration"if section_id == "discussion":if subsection_id in {"boundaries", "practical_implications"}:return "ordinary_section_writing"return "core_section_writing"if section_id == "conclusion":return "ordinary_section_writing"if section_id == "appendix":return Noneraise RuntimeError(f"logical_node_mapping_missing:{mode}:{section_id}:{subsection_id}")def _run_impl(self) -> dict[str, Any]:req = self.request22 unmodified linesagent = SSciPipelineAgent(ds_key, s2_key)self.agent = agentagent.set_model_policy_snapshot(plan_policy_snapshot)if trusted_task_policy_snapshot is not None:agent.set_trusted_product_policy_snapshot(trusted_task_policy_snapshot)agent.set_cancel_checker(self.cancel_checker)# DeepSeek/search activity marks the executor as genuinely alive; the# heartbeat thread decides separately when to renew D1's lease.734 unmodified lines# glossary order deterministic and avoids sharing mutable writer state.translation_agent = SSciPipelineAgent(ds_key, s2_key)translation_agent.set_model_policy_snapshot(plan_policy_snapshot)if trusted_task_policy_snapshot is not None:translation_agent.set_trusted_product_policy_snapshot(trusted_task_policy_snapshot)self.translation_agent = translation_agenttranslation_agent.set_execution_progress_hook(lambda: self._progress_activity())translation_agent.set_cancel_checker(lambda: self.cancel_checker())235 unmodified linesfor word in ["abstract", "keyword", "conclusion", "references", "appendix"])section_id = str(sec.get("section_id") or "")section_logical_node = self._section_logical_node(mode, section_id, sec.get("subsection_id"))planned_items = [item for item in list(citation_plan.get(display_name, []))if agent.citation_source_role_eligible(316 unmodified linesagent.stream_deepseek(sys_prompt, candidate_user_prompt, max_tokens=7000,model_role="writing", thinking=False, allow_fallback=False,logical_node=section_logical_node,),preview_prefix=full_draft_en + prefix,preview_stage=(display_name if section_attempt == 1 else f"{display_name}:retry"),
20 unmodified lines2122232425262721 unmodified lines4950515220 unmodified linesprompt,snippet,max_tokens=1000,model_name="deepseek-chat")# 强制提取 JSON 部分,过滤模型可能的解释性前缀或后缀21 unmodified linesdef extract_golden_metadata(agent, paper_texts: List[str]):extractor = MetaExtractor(agent)return extractor.run_batch_extraction(paper_texts)20 unmodified lines212223242526272821 unmodified lines5051525320 unmodified linesprompt,snippet,max_tokens=1000,model_name="deepseek-chat",logical_node='literature_parsing',)# 强制提取 JSON 部分,过滤模型可能的解释性前缀或后缀21 unmodified linesdef extract_golden_metadata(agent, paper_texts: List[str]):extractor = MetaExtractor(agent)return extractor.run_batch_extraction(paper_texts)
1234567891029 unmodified lines40414243444546474849505152537 unmodified lines6162636465666 unmodified lines7374757677787980818283848 unmodified lines9394959697981 unmodified line1001011021031041058 unmodified lines1141151161171181191205 unmodified lines1261271281291301311328 unmodified lines14114214314414514614710 unmodified lines158159160161162163164165166167168169170171172173174175176177# -*- coding: utf-8 -*-"""Provider-neutral model routing primitives for SmartPaper.A2 keeps the currently verified DeepSeek transport intact while moving providerselection out of academic business logic. Providers are registered adapters;academic code asks for a capability (reasoning/writing/translation/fast/repair)and never needs to know the concrete vendor or model name."""from __future__ import annotations29 unmodified linesfallback_providers: tuple[str, ...] = ()class ProviderNeutralModelGateway:"""Route capability calls to registered provider adapters.Adapter callables intentionally share the existing PipelineAgent requestsignature. This makes A2 a low-risk architectural seam: DeepSeek remainsthe verified adapter today, while Gemini/Qwen/OpenAI adapters can beregistered later without changing manuscript generation code."""def __init__(self, config: dict[str, Any] | None = None):cfg = dict(config or {})7 unmodified linesif isinstance(row, str):provider = str(row or self.default_provider).strip().lower()provider_role = capelse:item = dict(row or {})provider = str(item.get("provider") or self.default_provider).strip().lower()6 unmodified linesfor name in raw_fallbacksif str(name or "").strip())if not isinstance(row, dict):fallbacks = ()self._routes[cap] = ModelRoute(provider=provider, provider_role=provider_role, fallback_providers=fallbacks)self._call_adapters: dict[str, Callable[..., str]] = {}self._stream_adapters: dict[str, Callable[..., Iterable[str]]] = {}self._policy_snapshot: dict[str, Any] = {}def register_provider(self,8 unmodified linesself._call_adapters[name] = call_adapterself._stream_adapters[name] = stream_adapterdef set_policy_snapshot(self, snapshot: dict[str, Any] | None) -> None:self._policy_snapshot = deepcopy(dict(snapshot or {}))1 unmodified linedef policy_snapshot(self) -> dict[str, Any]:return deepcopy(self._policy_snapshot)def _route(self, capability: str) -> ModelRoute:cap = str(capability or "reasoning").strip().lower() or "reasoning"policy_routes = dict(self._policy_snapshot.get("model_routes") or {})8 unmodified linesprovider=str(row.get("provider") or self.default_provider).strip().lower(),provider_role=str(row.get("provider_role") or cap).strip().lower(),fallback_providers=tuple(str(name or "").strip().lower() for name in raw_fallbacksif str(name or "").strip()),)5 unmodified linesname for name in (route.provider, *route.fallback_providers) if name))def call(self, *, capability: str, **kwargs) -> str:route = self._route(capability)missing = []for provider in self._provider_sequence(route):8 unmodified linesf"model_provider_unavailable:{','.join(missing) or route.provider}:{capability}")def stream(self, *, capability: str, **kwargs):route = self._route(capability)missing = []for provider in self._provider_sequence(route):10 unmodified lines)def resolve_plan_policy_snapshot(app_config: dict[str, Any], request: dict[str, Any] | None = None) -> dict[str, Any]:"""Freeze a config-driven plan policy without touching payment authority.A2 only creates the interface. Worker/D1 remain the authority for payment,quota and entitlement; if the request does not yet carry a trusted plan_id,the legacy-current policy preserves existing production behavior."""req = dict(request or {})policies = dict(app_config.get("plan_policies") or {})# Never trust a browser/request plan label as an entitlement authority.# A future Worker/D1 integration may inject a trusted entitlement snapshot;# until then every task stays on the legacy-current production policy.entitlement = req.get("entitlement_snapshot") if isinstance(req.get("entitlement_snapshot"), dict) else {}requested = str(req.get("trusted_plan_id") or entitlement.get("plan_id") or ""123456789101129 unmodified lines4142434445464748495051525354555657587 unmodified lines666768697071726 unmodified lines7980818283848586878889909192938 unmodified lines1021031041051061071081 unmodified line1101111121131141151161171181191201211221231241251261271288 unmodified lines1371381391401411421431445 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662678 unmodified lines27627727827928028128228328428528628728828929029129229329410 unmodified lines305306307308309310311312313314315316317318319320321# -*- coding: utf-8 -*-"""Provider-neutral model routing primitives for SmartPaper.Legacy tasks continue to route by coarse capability. A5-R3-R4B adds aseparate, trusted product-policy seam: academic callers provide an explicitlogical_node, while the frozen TaskPolicySnapshot supplies provider/model andexecution settings. Product routing never falls back to legacy capabilityroutes."""from __future__ import annotations29 unmodified linesfallback_providers: tuple[str, ...] = ()@dataclass(frozen=True)class TrustedProductRoute:provider: strmodel_id: strthinking_enabled: boolreasoning_effort: str | Nonemax_output_tokens: intretry_budget: intclass ProviderNeutralModelGateway:"""Route legacy capabilities or trusted product logical nodes to adapters."""def __init__(self, config: dict[str, Any] | None = None):cfg = dict(config or {})7 unmodified linesif isinstance(row, str):provider = str(row or self.default_provider).strip().lower()provider_role = capfallbacks = ()else:item = dict(row or {})provider = str(item.get("provider") or self.default_provider).strip().lower()6 unmodified linesfor name in raw_fallbacksif str(name or "").strip())self._routes[cap] = ModelRoute(provider=provider,provider_role=provider_role,fallback_providers=fallbacks,)self._call_adapters: dict[str, Callable[..., str]] = {}self._stream_adapters: dict[str, Callable[..., Iterable[str]]] = {}self._policy_snapshot: dict[str, Any] = {}self._trusted_product_policy_snapshot: dict[str, Any] = {}def register_provider(self,8 unmodified linesself._call_adapters[name] = call_adapterself._stream_adapters[name] = stream_adapter# Legacy config/request policy. It remains a separate trust domain.def set_policy_snapshot(self, snapshot: dict[str, Any] | None) -> None:self._policy_snapshot = deepcopy(dict(snapshot or {}))1 unmodified linedef policy_snapshot(self) -> dict[str, Any]:return deepcopy(self._policy_snapshot)def set_trusted_product_policy_snapshot(self, snapshot: dict[str, Any] | None) -> None:"""Attach a Worker/D1-verified TaskPolicySnapshot for product execution.The runner validates task identity and snapshot SHA before calling thissetter. The gateway still validates route shape and fails closed beforeinvoking any provider adapter."""self._trusted_product_policy_snapshot = deepcopy(dict(snapshot or {}))@propertydef trusted_product_policy_snapshot(self) -> dict[str, Any]:return deepcopy(self._trusted_product_policy_snapshot)def _route(self, capability: str) -> ModelRoute:cap = str(capability or "reasoning").strip().lower() or "reasoning"policy_routes = dict(self._policy_snapshot.get("model_routes") or {})8 unmodified linesprovider=str(row.get("provider") or self.default_provider).strip().lower(),provider_role=str(row.get("provider_role") or cap).strip().lower(),fallback_providers=tuple(str(name or "").strip().lower()for name in raw_fallbacksif str(name or "").strip()),)5 unmodified linesname for name in (route.provider, *route.fallback_providers) if name))def _trusted_product_context(self) -> tuple[dict[str, Any], dict[str, Any]] | None:snapshot = self._trusted_product_policy_snapshotif not snapshot:return Noneresolved = snapshot.get("resolved_policy")if not isinstance(resolved, dict):raise ModelRequestError("trusted_product_policy_invalid")model = resolved.get("model")if not isinstance(model, dict):raise ModelRequestError("trusted_product_model_policy_missing")routes = model.get("routes")if not isinstance(routes, dict) or not routes:raise ModelRequestError("trusted_product_model_routes_missing")return resolved, routesdef _trusted_product_route(self, logical_node: str | None) -> tuple[TrustedProductRoute, str]:context = self._trusted_product_context()if context is None:raise ModelRequestError("trusted_product_policy_missing")resolved, routes = contextnode = str(logical_node or "").strip()if not node:raise ModelRequestError("trusted_product_logical_node_required")row = routes.get(node)if not isinstance(row, dict):raise ModelRequestError(f"trusted_product_route_missing:{node}")provider = str(row.get("provider") or "").strip().lower()model_id = str(row.get("model_id_or_alias") or "").strip()if not provider or not model_id:raise ModelRequestError(f"trusted_product_route_invalid:{node}")thinking = row.get("thinking_enabled")if not isinstance(thinking, bool):raise ModelRequestError(f"trusted_product_route_thinking_invalid:{node}")effort = row.get("reasoning_effort")if thinking:if str(effort or "").strip().lower() != "high":raise ModelRequestError(f"trusted_product_route_effort_invalid:{node}")effort = "high"else:if effort not in (None, ""):raise ModelRequestError(f"trusted_product_route_effort_invalid:{node}")effort = Nonetry:max_output_tokens = int(row.get("max_output_tokens"))retry_budget = int(row.get("retry_budget"))except (TypeError, ValueError):raise ModelRequestError(f"trusted_product_route_budget_invalid:{node}")if max_output_tokens <= 0 or retry_budget < 0:raise ModelRequestError(f"trusted_product_route_budget_invalid:{node}")if row.get("escalation_model_id_or_alias") not in (None, ""):raise ModelRequestError(f"trusted_product_route_escalation_forbidden:{node}")if row.get("escalation_condition_code") not in (None, ""):raise ModelRequestError(f"trusted_product_route_escalation_forbidden:{node}")model_policy_version = str(resolved.get("model_policy_version")or snapshot_model_policy_version(self._trusted_product_policy_snapshot)or "").strip()return TrustedProductRoute(provider=provider,model_id=model_id,thinking_enabled=thinking,reasoning_effort=effort,max_output_tokens=max_output_tokens,retry_budget=retry_budget,), model_policy_version@staticmethoddef _effective_max_tokens(requested: Any, ceiling: int) -> int:if requested is None:return int(ceiling)try:value = int(requested)except (TypeError, ValueError):raise ModelRequestError("trusted_product_max_tokens_invalid")if value <= 0:raise ModelRequestError("trusted_product_max_tokens_invalid")return min(value, int(ceiling))def _product_payload(self, *, capability: str, logical_node: str | None, kwargs: dict[str, Any]):route, model_policy_version = self._trusted_product_route(logical_node)payload = dict(kwargs)payload["model_role"] = str(capability or "reasoning").strip().lower() or "reasoning"payload["model_name"] = route.model_idpayload["thinking"] = route.thinking_enabledpayload["reasoning_effort"] = route.reasoning_effortpayload["allow_fallback"] = Falsepayload["max_tokens"] = self._effective_max_tokens(payload.get("max_tokens"), route.max_output_tokens)payload["retry_budget"] = route.retry_budgetpayload["logical_node"] = str(logical_node or "").strip()payload["model_policy_version"] = model_policy_versionpayload["route_enforced"] = Truereturn route.provider, payloaddef call(self, *, capability: str, logical_node: str | None = None, **kwargs) -> str:if self._trusted_product_context() is not None:provider, payload = self._product_payload(capability=capability, logical_node=logical_node, kwargs=kwargs)adapter = self._call_adapters.get(provider)if not callable(adapter):raise ModelProviderUnavailableError(f"model_provider_unavailable:{provider}:{logical_node or capability}")return adapter(**payload)route = self._route(capability)missing = []for provider in self._provider_sequence(route):8 unmodified linesf"model_provider_unavailable:{','.join(missing) or route.provider}:{capability}")def stream(self, *, capability: str, logical_node: str | None = None, **kwargs):if self._trusted_product_context() is not None:provider, payload = self._product_payload(capability=capability, logical_node=logical_node, kwargs=kwargs)adapter = self._stream_adapters.get(provider)if not callable(adapter):raise ModelProviderUnavailableError(f"model_provider_unavailable:{provider}:{logical_node or capability}")yield from adapter(**payload)returnroute = self._route(capability)missing = []for provider in self._provider_sequence(route):10 unmodified lines)def snapshot_model_policy_version(snapshot: dict[str, Any] | None) -> str:data = dict(snapshot or {})return str(data.get("model_policy_version") or "").strip()def resolve_plan_policy_snapshot(app_config: dict[str, Any], request: dict[str, Any] | None = None) -> dict[str, Any]:"""Freeze a config-driven legacy plan policy without touching payment authority."""req = dict(request or {})policies = dict(app_config.get("plan_policies") or {})entitlement = req.get("entitlement_snapshot") if isinstance(req.get("entitlement_snapshot"), dict) else {}requested = str(req.get("trusted_plan_id") or entitlement.get("plan_id") or ""
271 unmodified lines27227327427527627727829 unmodified lines308309310311312313537 unmodified lines85185285385485585685785818 unmodified lines87787887988088188288312 unmodified lines89689789889990090111 unmodified lines91391491591691791823 unmodified lines94294394494594694794851 unmodified lines10001001100210031004100510 unmodified lines101610171018101910201021102210231024102510263 unmodified lines10301031103210331034103510367 unmodified lines104410451046104710481049105012 unmodified lines10631064106510661067106811 unmodified lines10801081108210831084108535 unmodified lines1121112211231124112511261127132 unmodified lines12601261126212631264126519 unmodified lines12851286128712881289129012914 unmodified lines1296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813196 unmodified lines13261327132813291330133113322 unmodified lines13351336133713381339134013415 unmodified lines13471348134913501351135213535 unmodified lines13591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138215 unmodified lines13981399140014011402140357 unmodified lines146114621463146414651466146736 unmodified lines15041505150615071508150952 unmodified lines156215631564156515661567100 unmodified lines166816691670167116721673956 unmodified lines263026312632263326342635446 unmodified lines308230833084308530863087199 unmodified lines3287328832893290329132921950 unmodified lines524352445245524652475248137 unmodified lines53865387538853895390539147 unmodified lines543954405441544254435444466 unmodified lines59115912591359145915591646 unmodified lines59635964596559665967596868 unmodified lines6037603860396040604160422016 unmodified lines805980608061806280638064256 unmodified lines832183228323832483258326126 unmodified lines845384548455845684578458141 unmodified lines86008601860286038604860585 unmodified lines869186928693869486958696265 unmodified lines896289638964896589668967183 unmodified lines915191529153915491559156179 unmodified lines93369337933893399340934190 unmodified lines94329433943494359436943720 unmodified lines94589459946094619462946319 unmodified lines948394849485948694879488367 unmodified lines985698579858985998609861758 unmodified lines106201062110622106231062410625271 unmodified linesself, *, usage, model, role, attempt_index, streaming, thinking,reasoning_effort, system_prompt, user_prompt, started_at,completed_at, first_token_at=None, finish_reason="",response_payload=None,):if not self._model_usage_enabled():return29 unmodified linesmetadata=sanitize_metadata({"system_fingerprint": response_payload.get("system_fingerprint"),"reasoning_effort": reasoning_effort,}),)emit_usage_event(getattr(self, "_model_usage_sink", None), event)537 unmodified linesrequested_model,requested_thinking,allow_fallback,):total = self.deepseek_max_retriesfallback_model = self.deepseek_models.get("fallback", "")for attempt in range(total):model = requested_model18 unmodified linesthinking=None,reasoning_effort=None,allow_fallback=None,response_format=None,):if not str(getattr(self, "ds_key", "") or "").strip():raise DeepSeekAuthenticationError(12 unmodified linesreasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)tokens_est = self._count_tokens(str(user_prompt))logging.info(11 unmodified linesrequested_model,requested_thinking,resolved_fallback,):with self.lock:self.ds_calls += 123 unmodified lineslogging.info("DeepSeek static attempt start | attempt=%s/%s | model=%s",attempt + 1,self.deepseek_max_retries,current_model,)response = requests.post(51 unmodified linescompleted_at=completed_at,finish_reason=choices[0].get("finish_reason"),response_payload=result,)return content10 unmodified linesDeepSeekAPIError,) as exc:last_error = excis_last = attempt == self.deepseek_max_retries - 1logging.error("DeepSeek attempt %s/%s failed: %s",attempt + 1,self.deepseek_max_retries,exc,)self._touch_execution_progress("deepseek_static_retry")3 unmodified linesraise DeepSeekAPIError("DeepSeek API failed after "f"{self.deepseek_max_retries} attempts: {last_error}")def _stream_deepseek_transport(7 unmodified linesreasoning_effort=None,temp=0.3,allow_fallback=None,reasoning_only_recovery=False,):if not str(getattr(self, "ds_key", "") or "").strip():raise DeepSeekAuthenticationError(12 unmodified linesreasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)tokens_est = self._count_tokens(str(user_prompt))logging.info(11 unmodified linesrequested_model,requested_thinking,resolved_fallback,):with self.lock:self.ds_calls += 135 unmodified lineslogging.info("DeepSeek stream attempt start | attempt=%s/%s | model=%s | idle_limit=%ss",attempt + 1,self.deepseek_max_retries,current_model,self.deepseek_stream_idle_seconds,)132 unmodified linesfirst_token_at=first_content_at,finish_reason=stream_finish_reason,response_payload=stream_response_payload,)return19 unmodified lineslogging.error("DeepSeek stream attempt %s/%s failed: %s",attempt + 1,self.deepseek_max_retries,exc,)4 unmodified lines) from excself._touch_execution_progress("deepseek_stream_retry")is_last = attempt == self.deepseek_max_retries - 1if is_last:breaktime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError("DeepSeek streaming failed after "f"{self.deepseek_max_retries} attempts: {last_error}")def set_model_policy_snapshot(self, snapshot):self.model_policy_snapshot = dict(snapshot or {})self.model_gateway.set_policy_snapshot(self.model_policy_snapshot)def call_model(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3,model_name=None, model_role="reasoning", thinking=None,reasoning_effort=None, allow_fallback=None, response_format=None,):gateway = getattr(self, "model_gateway", None)if gateway is None:6 unmodified linesresponse_format=response_format,)return gateway.call(capability=model_role, system_prompt=system_prompt, user_prompt=user_prompt,max_tokens=max_tokens, temp=temp, model_name=model_name,thinking=thinking, reasoning_effort=reasoning_effort,allow_fallback=allow_fallback, response_format=response_format,2 unmodified linesdef stream_model(self, system_prompt, user_prompt, max_tokens=8000, model_name=None,model_role="reasoning", thinking=None, reasoning_effort=None, temp=0.3,allow_fallback=None, reasoning_only_recovery=False,):gateway = getattr(self, "model_gateway", None)if gateway is None:5 unmodified lines)returnyield from gateway.stream(capability=model_role, system_prompt=system_prompt, user_prompt=user_prompt,max_tokens=max_tokens, model_name=model_name, thinking=thinking,reasoning_effort=reasoning_effort, temp=temp, allow_fallback=allow_fallback,reasoning_only_recovery=reasoning_only_recovery,5 unmodified linesself, system_prompt, user_prompt, max_tokens=8000, temp=0.3,model_name=None, model_role="reasoning", thinking=None,reasoning_effort=None, allow_fallback=None, response_format=None,):return self.call_model(system_prompt, user_prompt, max_tokens=max_tokens, temp=temp,model_name=model_name, model_role=model_role, thinking=thinking,reasoning_effort=reasoning_effort, allow_fallback=allow_fallback,response_format=response_format,)def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name=None,model_role="reasoning", thinking=None, reasoning_effort=None, temp=0.3,allow_fallback=None, reasoning_only_recovery=False,):yield from self.stream_model(system_prompt, user_prompt, max_tokens=max_tokens, model_name=model_name,model_role=model_role, thinking=thinking, reasoning_effort=reasoning_effort,temp=temp, allow_fallback=allow_fallback,reasoning_only_recovery=reasoning_only_recovery,)def parse_user_core_literature(self, user_lit_text):15 unmodified linesmodel_role="reasoning",thinking=True,allow_fallback=False,)papers = self._extract_json_from_text(response)if not papers:57 unmodified linesuser_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace("{topic}", topic).replace("{user_injection}", user_injection).replace("{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.call_deepseek(sys_prompt, user_prompt, temp=0.2)def generate_anchors(self,36 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,)return _stream_direct_synthesis()52 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,)return _stream_direct_research_logic()100 unmodified linesthinking=False,allow_fallback=False,response_format={"type": "json_object"},)try:parsed = self._extract_json_from_text(response)956 unmodified linesuser_prompt,temp=0.1 + attempt * 0.1,model_role="fast",))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())]446 unmodified linesf"Topic: {topic}\nKeywords: {keywords}\nUsed: {sorted(all_used_terms)}",temp=0.4,model_role='fast',)parsed = self._extract_json_from_text(response)terms = parsed if isinstance(parsed, list) else []199 unmodified linesmodel_role='reasoning',thinking=False,allow_fallback=False,)parsed = self._extract_json_from_text(raw)parsed_rows = parsed.get('assignments') if isinstance(parsed, dict) else None1950 unmodified linesmodel_role='reasoning',thinking=False,allow_fallback=False,)parsed = self._extract_json_from_text(response)if isinstance(parsed, dict):137 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,)parsed = self._extract_json_from_text(response)last_error = None47 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,)parsed = self._extract_json_from_text(response)by_id = index_items(parsed)466 unmodified linesmodel_role='writing',thinking=False,allow_fallback=False,)revised = self._remove_ai_meta_traces(revised)original_numbers = self._numeric_tokens(value)46 unmodified linesraw = self.call_deepseek('You are an independent senior management-journal reviewer. Be exact and conservative.',prompt, max_tokens=800, temp=0.0, model_role='fast', thinking=False, allow_fallback=True,)except PipelineCancelledError:raise68 unmodified linesrepaired = self.call_model('You are SmartPaper Adaptive Academic Repair. Preserve evidence truth and repair prose with Conciseness, Accuracy, and Rigor.',prompt, max_tokens=7000, temp=0.15, model_role='repair', thinking=True, allow_fallback=True,)except PipelineCancelledError:raise2016 unmodified linesjson.dumps({'ir_version': self.CANONICAL_GLOSSARY_IR_VERSION, 'terms': payload}, ensure_ascii=False),max_tokens=max(1200, min(5000, 120 + len(payload) * 90)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []256 unmodified linesjson.dumps({'ir_version': self.CANONICAL_GLOSSARY_IR_VERSION, 'terms': payload}, ensure_ascii=False),max_tokens=max(1200, min(4200, 180 + len(payload) * 120)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []126 unmodified linesjson.dumps({'terms': missing}, ensure_ascii=False),max_tokens=max(1200, min(5000, len(missing) * 80)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []141 unmodified linesresponse = self.call_deepseek('You are a bilingual academic translation equivalence auditor. Be conservative and evidence-preserving.',prompt, max_tokens=1200, temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)ok = parsed.get('ok') if isinstance(parsed, dict) else None85 unmodified linessystem_prompt, json.dumps(payload, ensure_ascii=False),max_tokens=max(1200, min(3600, 650 + 260 * len(rows))),temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)returned = parsed.get('items', []) if isinstance(parsed, dict) else []265 unmodified linesmodel_role='translation',thinking=False,allow_fallback=False,)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []183 unmodified lineseffective_prompt, marked_source,max_tokens=max(1800, min(9000, self._count_tokens(marked_source) * 2 + 1200)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)try:parsed = self._parse_marked_translation(result, expected_ids)179 unmodified linesresponse = self.call_deepseek(prompt, json.dumps(payload, ensure_ascii=False), max_tokens=900, temp=0.0,model_role='reasoning', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)raw = parsed.get('delta_codes', []) if isinstance(parsed, dict) else []90 unmodified lineseffective_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)parsed = self._parse_marked_translation(result, [block_id])try:20 unmodified linesstrict_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)strict_parsed = self._parse_marked_translation(strict_result, [block_id])restored = self._restore_translation_tokens(19 unmodified linesnumeric_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,)retry_parsed = self._parse_marked_translation(retry_result, [block_id])restored = self._restore_translation_tokens(367 unmodified linessystem_prompt, json.dumps(payload, ensure_ascii=False),max_tokens=max(1200, min(3200, 600 + 180 * len(model_rows))),temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,)parsed = self._extract_json_from_text(response)returned = parsed.get('items', []) if isinstance(parsed, dict) else []758 unmodified linestranslated = self.call_model('You are SmartPaper Adaptive Translation. Produce faithful academic translation with no added or omitted claims.',prompt, max_tokens=8000, temp=0.1, model_role='translation', thinking=False, allow_fallback=True,)translated = re.sub(r'<think>.*?</think>', '', str(translated or ''), flags=re.S).strip()if not translated:271 unmodified lines27227327427527627727829 unmodified lines308309310311312313314315316537 unmodified lines85485585685785885986086186286386486586618 unmodified lines88588688788888989089189212 unmodified lines90590690790890991091191291391491591691791891911 unmodified lines93193293393493593693723 unmodified lines96196296396496596696751 unmodified lines1019102010211022102310241025102610 unmodified lines103710381039104010411042104310441045104610473 unmodified lines10511052105310541055105610577 unmodified lines1065106610671068106910701071107212 unmodified lines10851086108710881089109010911092109310941095109610971098109911 unmodified lines111111121113111411151116111735 unmodified lines1153115411551156115711581159132 unmodified lines1292129312941295129612971298129919 unmodified lines13191320132113221323132413254 unmodified lines13301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613576 unmodified lines136413651366136713681369137013712 unmodified lines13741375137613771378137913805 unmodified lines138613871388138913901391139213935 unmodified lines139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142315 unmodified lines143914401441144214431444144557 unmodified lines150315041505150615071508150936 unmodified lines154615471548154915501551155252 unmodified lines1605160616071608160916101611100 unmodified lines1712171317141715171617171718956 unmodified lines2675267626772678267926802681446 unmodified lines3128312931303131313231333134199 unmodified lines33343335333633373338333933401950 unmodified lines5291529252935294529552965297137 unmodified lines543554365437543854395440544147 unmodified lines5489549054915492549354945495466 unmodified lines596259635964596559665967596846 unmodified lines601560166017601860196020602168 unmodified lines60906091609260936094609560962016 unmodified lines8113811481158116811781188119256 unmodified lines8376837783788379838083818382126 unmodified lines8509851085118512851385148515141 unmodified lines865786588659866086618662866385 unmodified lines8749875087518752875387548755265 unmodified lines9021902290239024902590269027183 unmodified lines9211921292139214921592169217179 unmodified lines939793989399940094019402940390 unmodified lines949494959496949794989499950020 unmodified lines952195229523952495259526952719 unmodified lines9547954895499550955195529553367 unmodified lines9921992299239924992599269927758 unmodified lines10686106871068810689106901069110692271 unmodified linesself, *, usage, model, role, attempt_index, streaming, thinking,reasoning_effort, system_prompt, user_prompt, started_at,completed_at, first_token_at=None, finish_reason="",response_payload=None, logical_node="", model_policy_version="",):if not self._model_usage_enabled():return29 unmodified linesmetadata=sanitize_metadata({"system_fingerprint": response_payload.get("system_fingerprint"),"reasoning_effort": reasoning_effort,"logical_node": str(logical_node or ""),"model_policy_version": str(model_policy_version or ""),"resolved_model_id": str(response_payload.get("model") or model or ""),}),)emit_usage_event(getattr(self, "_model_usage_sink", None), event)537 unmodified linesrequested_model,requested_thinking,allow_fallback,retry_budget=None,):total = (self.deepseek_max_retriesif retry_budget is Noneelse max(1, 1 + int(retry_budget)))fallback_model = self.deepseek_models.get("fallback", "")for attempt in range(total):model = requested_model18 unmodified linesthinking=None,reasoning_effort=None,allow_fallback=None,response_format=None, retry_budget=None, logical_node=None,model_policy_version=None, route_enforced=False,):if not str(getattr(self, "ds_key", "") or "").strip():raise DeepSeekAuthenticationError(12 unmodified linesreasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)if route_enforced:resolved_fallback = Falseif not requested_thinking:resolved_effort = Noneattempt_total = (self.deepseek_max_retriesif retry_budget is Noneelse max(1, 1 + int(retry_budget)))tokens_est = self._count_tokens(str(user_prompt))logging.info(11 unmodified linesrequested_model,requested_thinking,resolved_fallback,retry_budget=retry_budget,):with self.lock:self.ds_calls += 123 unmodified lineslogging.info("DeepSeek static attempt start | attempt=%s/%s | model=%s",attempt + 1,attempt_total,current_model,)response = requests.post(51 unmodified linescompleted_at=completed_at,finish_reason=choices[0].get("finish_reason"),response_payload=result,logical_node=logical_node,model_policy_version=model_policy_version,)return content10 unmodified linesDeepSeekAPIError,) as exc:last_error = excis_last = attempt == attempt_total - 1logging.error("DeepSeek attempt %s/%s failed: %s",attempt + 1,attempt_total,exc,)self._touch_execution_progress("deepseek_static_retry")3 unmodified linesraise DeepSeekAPIError("DeepSeek API failed after "f"{attempt_total} attempts: {last_error}")def _stream_deepseek_transport(7 unmodified linesreasoning_effort=None,temp=0.3,allow_fallback=None,reasoning_only_recovery=False, retry_budget=None, logical_node=None,model_policy_version=None, route_enforced=False,):if not str(getattr(self, "ds_key", "") or "").strip():raise DeepSeekAuthenticationError(12 unmodified linesreasoning_effort=reasoning_effort,allow_fallback=allow_fallback,)if route_enforced:resolved_fallback = Falseif not requested_thinking:resolved_effort = Noneattempt_total = (self.deepseek_max_retriesif retry_budget is Noneelse max(1, 1 + int(retry_budget)))tokens_est = self._count_tokens(str(user_prompt))logging.info(11 unmodified linesrequested_model,requested_thinking,resolved_fallback,retry_budget=retry_budget,):with self.lock:self.ds_calls += 135 unmodified lineslogging.info("DeepSeek stream attempt start | attempt=%s/%s | model=%s | idle_limit=%ss",attempt + 1,attempt_total,current_model,self.deepseek_stream_idle_seconds,)132 unmodified linesfirst_token_at=first_content_at,finish_reason=stream_finish_reason,response_payload=stream_response_payload,logical_node=logical_node,model_policy_version=model_policy_version,)return19 unmodified lineslogging.error("DeepSeek stream attempt %s/%s failed: %s",attempt + 1,attempt_total,exc,)4 unmodified lines) from excself._touch_execution_progress("deepseek_stream_retry")is_last = attempt == attempt_total - 1if is_last:breaktime.sleep(self._retry_delay(attempt))raise DeepSeekAPIError("DeepSeek streaming failed after "f"{attempt_total} attempts: {last_error}")def set_model_policy_snapshot(self, snapshot):self.model_policy_snapshot = dict(snapshot or {})self.model_gateway.set_policy_snapshot(self.model_policy_snapshot)def set_trusted_product_policy_snapshot(self, snapshot):self.model_gateway.set_trusted_product_policy_snapshot(snapshot)def call_model(self, system_prompt, user_prompt, max_tokens=8000, temp=0.3,model_name=None, model_role="reasoning", thinking=None,reasoning_effort=None, allow_fallback=None, response_format=None,logical_node=None,):gateway = getattr(self, "model_gateway", None)if gateway is None:6 unmodified linesresponse_format=response_format,)return gateway.call(capability=model_role, logical_node=logical_node,system_prompt=system_prompt, user_prompt=user_prompt,max_tokens=max_tokens, temp=temp, model_name=model_name,thinking=thinking, reasoning_effort=reasoning_effort,allow_fallback=allow_fallback, response_format=response_format,2 unmodified linesdef stream_model(self, system_prompt, user_prompt, max_tokens=8000, model_name=None,model_role="reasoning", thinking=None, reasoning_effort=None, temp=0.3,allow_fallback=None, reasoning_only_recovery=False, logical_node=None,):gateway = getattr(self, "model_gateway", None)if gateway is None:5 unmodified lines)returnyield from gateway.stream(capability=model_role, logical_node=logical_node,system_prompt=system_prompt, user_prompt=user_prompt,max_tokens=max_tokens, model_name=model_name, thinking=thinking,reasoning_effort=reasoning_effort, temp=temp, allow_fallback=allow_fallback,reasoning_only_recovery=reasoning_only_recovery,5 unmodified linesself, system_prompt, user_prompt, max_tokens=8000, temp=0.3,model_name=None, model_role="reasoning", thinking=None,reasoning_effort=None, allow_fallback=None, response_format=None,logical_node=None,):return self.call_model(system_prompt, user_prompt, max_tokens=max_tokens, temp=temp,model_name=model_name, model_role=model_role, thinking=thinking,reasoning_effort=reasoning_effort, allow_fallback=allow_fallback,response_format=response_format, logical_node=logical_node,)def stream_deepseek(self, system_prompt, user_prompt, max_tokens=8000, model_name=None,model_role="reasoning", thinking=None, reasoning_effort=None, temp=0.3,allow_fallback=None, reasoning_only_recovery=False, logical_node=None,):yield from self.stream_model(system_prompt, user_prompt, max_tokens=max_tokens, model_name=model_name,model_role=model_role, thinking=thinking, reasoning_effort=reasoning_effort,temp=temp, allow_fallback=allow_fallback,reasoning_only_recovery=reasoning_only_recovery, logical_node=logical_node,)def parse_user_core_literature(self, user_lit_text):15 unmodified linesmodel_role="reasoning",thinking=True,allow_fallback=False,logical_node='literature_parsing',)papers = self._extract_json_from_text(response)if not papers:57 unmodified linesuser_prompt = APP_CONFIG["prompt_templates"]["synthesis_user"].replace("{topic}", topic).replace("{user_injection}", user_injection).replace("{refs_text}", refs_text).replace("{directive}", APP_CONFIG['deep_synthesis_directive'])return self.call_deepseek(sys_prompt, user_prompt, temp=0.2, logical_node="literature_synthesis")def generate_anchors(self,36 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,logical_node='literature_synthesis',)return _stream_direct_synthesis()52 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,logical_node='research_logic',)return _stream_direct_research_logic()100 unmodified linesthinking=False,allow_fallback=False,response_format={"type": "json_object"},logical_node='front_matter_writing',)try:parsed = self._extract_json_from_text(response)956 unmodified linesuser_prompt,temp=0.1 + attempt * 0.1,model_role="fast",logical_node='search_jit',))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())]446 unmodified linesf"Topic: {topic}\nKeywords: {keywords}\nUsed: {sorted(all_used_terms)}",temp=0.4,model_role='fast',logical_node='search_jit',)parsed = self._extract_json_from_text(response)terms = parsed if isinstance(parsed, list) else []199 unmodified linesmodel_role='reasoning',thinking=False,allow_fallback=False,logical_node='citation_planning',)parsed = self._extract_json_from_text(raw)parsed_rows = parsed.get('assignments') if isinstance(parsed, dict) else None1950 unmodified linesmodel_role='reasoning',thinking=False,allow_fallback=False,logical_node='critical_citation_adjudication',)parsed = self._extract_json_from_text(response)if isinstance(parsed, dict):137 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,logical_node='ordinary_citation_qa',)parsed = self._extract_json_from_text(response)last_error = None47 unmodified linesmodel_role="reasoning",thinking=False,allow_fallback=False,logical_node='ordinary_citation_qa',)parsed = self._extract_json_from_text(response)by_id = index_items(parsed)466 unmodified linesmodel_role='writing',thinking=False,allow_fallback=False,logical_node='ordinary_repair',)revised = self._remove_ai_meta_traces(revised)original_numbers = self._numeric_tokens(value)46 unmodified linesraw = self.call_deepseek('You are an independent senior management-journal reviewer. Be exact and conservative.',prompt, max_tokens=800, temp=0.0, model_role='fast', thinking=False, allow_fallback=True,logical_node='section_critique',)except PipelineCancelledError:raise68 unmodified linesrepaired = self.call_model('You are SmartPaper Adaptive Academic Repair. Preserve evidence truth and repair prose with Conciseness, Accuracy, and Rigor.',prompt, max_tokens=7000, temp=0.15, model_role='repair', thinking=True, allow_fallback=True,logical_node='ordinary_repair',)except PipelineCancelledError:raise2016 unmodified linesjson.dumps({'ir_version': self.CANONICAL_GLOSSARY_IR_VERSION, 'terms': payload}, ensure_ascii=False),max_tokens=max(1200, min(5000, 120 + len(payload) * 90)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []256 unmodified linesjson.dumps({'ir_version': self.CANONICAL_GLOSSARY_IR_VERSION, 'terms': payload}, ensure_ascii=False),max_tokens=max(1200, min(4200, 180 + len(payload) * 120)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='ordinary_translation_qa',)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []126 unmodified linesjson.dumps({'terms': missing}, ensure_ascii=False),max_tokens=max(1200, min(5000, len(missing) * 80)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []141 unmodified linesresponse = self.call_deepseek('You are a bilingual academic translation equivalence auditor. Be conservative and evidence-preserving.',prompt, max_tokens=1200, temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,logical_node='ordinary_translation_qa',)parsed = self._extract_json_from_text(response)ok = parsed.get('ok') if isinstance(parsed, dict) else None85 unmodified linessystem_prompt, json.dumps(payload, ensure_ascii=False),max_tokens=max(1200, min(3600, 650 + 260 * len(rows))),temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,logical_node='ordinary_translation_qa',)parsed = self._extract_json_from_text(response)returned = parsed.get('items', []) if isinstance(parsed, dict) else []265 unmodified linesmodel_role='translation',thinking=False,allow_fallback=False,logical_node='translation',)parsed = self._extract_json_from_text(response)items = parsed.get('terms', []) if isinstance(parsed, dict) else []183 unmodified lineseffective_prompt, marked_source,max_tokens=max(1800, min(9000, self._count_tokens(marked_source) * 2 + 1200)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)try:parsed = self._parse_marked_translation(result, expected_ids)179 unmodified linesresponse = self.call_deepseek(prompt, json.dumps(payload, ensure_ascii=False), max_tokens=900, temp=0.0,model_role='reasoning', thinking=False, allow_fallback=False,logical_node='ordinary_translation_qa',)parsed = self._extract_json_from_text(response)raw = parsed.get('delta_codes', []) if isinstance(parsed, dict) else []90 unmodified lineseffective_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)parsed = self._parse_marked_translation(result, [block_id])try:20 unmodified linesstrict_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)strict_parsed = self._parse_marked_translation(strict_result, [block_id])restored = self._restore_translation_tokens(19 unmodified linesnumeric_prompt, marked_source,max_tokens=max(1200, min(2600, self._count_tokens(marked_source) * 2 + 900)),temp=0.0, model_role='translation', thinking=False, allow_fallback=False,logical_node='translation',)retry_parsed = self._parse_marked_translation(retry_result, [block_id])restored = self._restore_translation_tokens(367 unmodified linessystem_prompt, json.dumps(payload, ensure_ascii=False),max_tokens=max(1200, min(3200, 600 + 180 * len(model_rows))),temp=0.0, model_role='reasoning', thinking=False, allow_fallback=False,logical_node='critical_translation_adjudication',)parsed = self._extract_json_from_text(response)returned = parsed.get('items', []) if isinstance(parsed, dict) else []758 unmodified linestranslated = self.call_model('You are SmartPaper Adaptive Translation. Produce faithful academic translation with no added or omitted claims.',prompt, max_tokens=8000, temp=0.1, model_role='translation', thinking=False, allow_fallback=True,logical_node='translation',)translated = re.sub(r'<think>.*?</think>', '', str(translated or ''), flags=re.S).strip()if not translated:
732 unmodified lines73373473573673773814 unmodified lines753754755756757758732 unmodified linesbase_prompt,max_tokens=8000, temp=0.0, model_role="reasoning",thinking=False, allow_fallback=False, response_format={"type": "json_object"},)else:retry_prompt = base_prompt + (14 unmodified linesthinking=False,allow_fallback=False,response_format={"type": "json_object"},)response = re.sub(732 unmodified lines73373473573673773873914 unmodified lines754755756757758759760732 unmodified linesbase_prompt,max_tokens=8000, temp=0.0, model_role="reasoning",thinking=False, allow_fallback=False, response_format={"type": "json_object"},logical_node='structured_json',)else:retry_prompt = base_prompt + (14 unmodified linesthinking=False,allow_fallback=False,response_format={"type": "json_object"},logical_node='structured_json',)response = re.sub(
479 unmodified lines480481482483484485479 unmodified linesmodel_role="fast",thinking=False,allow_fallback=True,)parsed = agent._extract_json_from_text(raw)if not isinstance(parsed, dict):479 unmodified lines480481482483484485486479 unmodified linesmodel_role="fast",thinking=False,allow_fallback=True,logical_node='structured_json',)parsed = agent._extract_json_from_text(raw)if not isinstance(parsed, dict):
core/generation_runner.py+55-5
core/meta_extractor.py+3-2
core/model_gateway.py+170-26
core/pipeline_agent.py+86-19
core/qualitative_engine.py+2
core/quantitative_engine.py+1