SmartPaper / config.py
GuXiaopeng's picture
Step 4A-6-C-R3.1 Executor Bootstrap and UI State Ownership Correction (#8)
16b0aa2
Raw History Blame
26.4 kB
# -*- coding: utf-8 -*-
import os
def load_config():
base_config = {
# --- 基础运行参数 ---
"lit_target_papers": int(os.environ.get("LIT_TARGET_PAPERS", "80")),
"lit_per_page": int(os.environ.get("LIT_PER_PAGE", "100")),
"lit_max_workers": int(os.environ.get("LIT_MAX_WORKERS", "5")),
"chunk_words_default": int(os.environ.get("CHUNK_WORDS_DEFAULT", "1500")),
"target_words_min": 5000,
"target_words_default": 5000,
"target_words_max": 20000,
"search_max_retries": max(1, int(os.environ.get("SEARCH_MAX_RETRIES", "4"))),
"translation_batch_tokens": max(800, int(os.environ.get("TRANSLATION_BATCH_TOKENS", "2500"))),
"translation_glossary_term_limit": max(10, int(os.environ.get("TRANSLATION_GLOSSARY_TERM_LIMIT", "40"))),
"translation_min_coverage_ratio": float(os.environ.get("TRANSLATION_MIN_COVERAGE_RATIO", "0.25")),
"translation_min_block_ratio_zh": float(os.environ.get("TRANSLATION_MIN_BLOCK_RATIO_ZH", "0.28")),
"translation_min_block_ratio_cyrillic": float(os.environ.get("TRANSLATION_MIN_BLOCK_RATIO_CYRILLIC", "0.65")),
"translation_max_block_ratio": float(os.environ.get("TRANSLATION_MAX_BLOCK_RATIO", "2.20")),
"openalex_email": os.environ.get("OPENALEX_EMAIL", "").strip(),
# --- RAG 与解析配置 ---
"rag_chunk_size": int(os.environ.get("RAG_CHUNK_SIZE", "3000")),
"rag_top_k": int(os.environ.get("RAG_TOP_K", "3")),
"max_extract_chars": int(os.environ.get("MAX_EXTRACT_CHARS", "150000")),
# A DeepSeek request must fail before the 90-second Worker generation
# lease can expire without real execution progress. Retries renew the
# lease through the execution heartbeat hook.
"api_timeouts": {
"standard": (15, 70),
"stream": (15, 70),
"search": 15
},
"deepseek_stream_idle_seconds": max(
20,
min(65, int(os.environ.get("DEEPSEEK_STREAM_IDLE_SECONDS", "60"))),
),
# --- API 节点配置 ---
"deepseek_api_url": os.environ.get(
"DEEPSEEK_API_URL",
"https://api.deepseek.com/chat/completions",
),
# Model names are centralized here and can be upgraded in HF Variables.
# Application and engine code select a task role, never a concrete model.
"deepseek_models": {
"reasoning": os.environ.get(
"DEEPSEEK_MODEL_REASONING",
"deepseek-v4-pro",
),
"writing": os.environ.get(
"DEEPSEEK_MODEL_WRITING",
"deepseek-v4-pro",
),
"translation": os.environ.get(
"DEEPSEEK_MODEL_TRANSLATION",
"deepseek-v4-pro",
),
"fast": os.environ.get(
"DEEPSEEK_MODEL_FAST",
"deepseek-v4-flash",
),
"fallback": os.environ.get(
"DEEPSEEK_MODEL_FALLBACK",
"deepseek-v4-flash",
),
},
"deepseek_task_settings": {
"reasoning": {
"thinking": True,
"reasoning_effort": os.environ.get(
"DEEPSEEK_REASONING_EFFORT",
"high",
),
"allow_fallback": False,
},
"writing": {
"thinking": False,
"reasoning_effort": "high",
"allow_fallback": False,
},
"translation": {
"thinking": False,
"reasoning_effort": "high",
"allow_fallback": False,
},
"fast": {
"thinking": False,
"reasoning_effort": "low",
"allow_fallback": True,
},
},
"deepseek_max_retries": int(
os.environ.get("DEEPSEEK_MAX_RETRIES", "3")
),
"deepseek_show_reasoning": os.environ.get(
"DEEPSEEK_SHOW_REASONING",
"false",
).strip().lower() in {"1", "true", "yes", "on"},
# Citation-semantic audit repairs only affected sentences. Technical
# failures fall back to deterministic single-source recovery and are
# recorded in the audit log instead of terminating the whole paper.
"citation_semantic_audit": {
"enabled": os.environ.get(
"CITATION_SEMANTIC_AUDIT_ENABLED",
"true",
).strip().lower() in {"1", "true", "yes", "on"},
"batch_size": max(
1,
int(os.environ.get("CITATION_SEMANTIC_BATCH_SIZE", "5")),
),
"candidate_limit": max(
3,
int(os.environ.get("CITATION_SEMANTIC_CANDIDATE_LIMIT", "10")),
),
"fail_closed": os.environ.get(
"CITATION_SEMANTIC_FAIL_CLOSED",
"false",
).strip().lower() in {"1", "true", "yes", "on"},
"technical_retries": max(
1,
int(os.environ.get("CITATION_SEMANTIC_TECHNICAL_RETRIES", "2")),
),
"json_repair_retries": max(
0,
int(os.environ.get("CITATION_SEMANTIC_JSON_REPAIR_RETRIES", "1")),
),
},
# R3-Free task execution runs outside Streamlit. The executor renews
# the Worker lease only while real Python/model progress is recent.
"executor_heartbeat_interval_seconds": max(
10,
int(os.environ.get("SMARTPAPER_EXECUTOR_HEARTBEAT_SECONDS", "15")),
),
"executor_activity_grace_seconds": max(
30,
int(os.environ.get("SMARTPAPER_EXECUTOR_ACTIVITY_GRACE_SECONDS", "45")),
),
"executor_bootstrap_timeout_seconds": max(
5,
int(os.environ.get("SMARTPAPER_EXECUTOR_BOOTSTRAP_TIMEOUT_SECONDS", "20")),
),
"executor_bootstrap_poll_ms": max(
50,
int(os.environ.get("SMARTPAPER_EXECUTOR_BOOTSTRAP_POLL_MS", "100")),
),
"manuscript_quality": {
"abstract_max_words": int(os.environ.get("ABSTRACT_MAX_WORDS", "200")),
"abstract_max_numeric_mentions": int(os.environ.get("ABSTRACT_MAX_NUMERIC_MENTIONS", "6")),
"forbidden_phrases": [
"delve into", "intricate", "paramount", "overarching",
"pivotal", "foster", "seamlessly", "multifaceted",
"beacon", "landscape", "underscore", "robust",
"firstly", "secondly", "moreover", "furthermore",
"in conclusion", "to summarize", "as an ai",
"ai-generated", "this response",
],
},
"openalex_api_url": os.environ.get("OPENALEX_API_URL", "https://api.openalex.org/works"),
"s2_api_url": os.environ.get("S2_API_URL", "https://api.semanticscholar.org/graph/v1"),
# --- UI 多语言标签 ---
"ui_labels": {
"中文": {"title": "📊 工商管理论文智能体", "btn_generate": "🚀 生成初稿", "btn_download": "📥 下载文件", "topic_label": "📝 论文名称", "keywords_label": "🔍 关键字", "words_label": "📏 目标总单词数 (5000-20000单词)", "success": "🎉 流水线推演完毕!双语文档已就绪。"},
"English": {"title": "📊 Business Administration Article Agent", "btn_generate": "🚀 Generate Draft", "btn_download": "📥 Download", "topic_label": "📝 Article Title", "keywords_label": "🔍 Keywords", "words_label": "📏 Target Word Count", "success": "🎉 Task complete!"},
"Русский": {"title": "📊 Агент статей по бизнес-администрированию", "btn_generate": "🚀 Черновик", "btn_download": "📥 Скачать", "topic_label": "📝 Тема", "keywords_label": "🔍 Ключевые слова", "words_label": "📏 Количество слов", "success": "🎉 Задача выполнена!"},
"Қазақша": {"title": "📊 Бизнес-басқару жөніндегі ғылыми мақала агенті", "btn_generate": "🚀 Жоба дайындау", "btn_download": "📥 Жүктеу", "topic_label": "📝 Мақала атауы", "keywords_label": "🔍 Түйін сөздер", "words_label": "📏 Мақсатты сөз саны", "success": "🎉 Тапсырма аяқталды!"}
},
"target_lang_map": {
"中文": "Simplified Chinese (简体中文)",
"English": "Simplified Chinese (简体中文)",
"Русский": "Russian (Русский)",
"Қазақша": "Kazakh (Қазақша)"
},
"workspace_dir": ".workspace",
"docx_styles": {
"font_name": "Times New Roman",
"font_size_pt": 12,
"code_font": "Courier New",
"code_size_pt": 11
},
"blacklists": {
"meta_sections": [
"abstract", "keyword", "keywords", "摘要", "关键词", "关键字",
"reference", "references", "reference list", "参考文献",
"acknowledgment", "acknowledgements", "致谢",
"аннотация", "ключевые слова", "түйіндеме", "кілт сөздер"
]
},
# =====================================================================
# Canonical manuscript structures. Top-level titles are deterministic:
# the model may write content, but it may not rename, remove, or reorder
# required sections.
# =====================================================================
"amj_schema": [
{
"section_id": "introduction",
"section": "Introduction",
"weight": 0.10,
"subsections": [],
},
{
"section_id": "theory",
"section": "Theoretical Background and Hypotheses",
"weight": 0.27,
"subsections": [
{"subsection_id": "conceptual_background", "title": "Conceptual Background and Research Gap", "share": 0.23},
{"subsection_id": "theoretical_mechanisms", "title": "Theoretical Mechanisms", "share": 0.27},
{"subsection_id": "hypothesis_development", "title": "Hypothesis Development", "share": 0.35},
{"subsection_id": "integrated_model", "title": "Integrated Research Model", "share": 0.15},
],
},
{
"section_id": "methodology",
"section": "Methodology",
"weight": 0.20,
"subsections": [
{"subsection_id": "research_design", "title": "Research Design and Context", "share": 0.18},
{"subsection_id": "sample_data", "title": "Sample and Data Collection", "share": 0.20},
{"subsection_id": "measures", "title": "Measures and Construct Operationalization", "share": 0.25},
{"subsection_id": "analysis_strategy", "title": "Analytical Strategy", "share": 0.22},
{"subsection_id": "validity_bias", "title": "Validity, Bias, and Robustness Procedures", "share": 0.15},
],
},
{
"section_id": "results",
"section": "Results",
"weight": 0.23,
"subsections": [
{"subsection_id": "measurement_results", "title": "Descriptive Statistics and Measurement Assessment", "share": 0.34},
{"subsection_id": "hypothesis_results", "title": "Hypothesis and Association Tests", "share": 0.46},
{"subsection_id": "additional_results", "title": "Additional Analyses and Robustness Checks", "share": 0.20},
],
},
{
"section_id": "discussion",
"section": "Discussion",
"weight": 0.15,
"subsections": [
{"subsection_id": "interpretation", "title": "Interpretation of the Findings", "share": 0.30},
{"subsection_id": "theoretical_contributions", "title": "Theoretical Contributions", "share": 0.30},
{"subsection_id": "practical_implications", "title": "Practical Implications", "share": 0.20},
{"subsection_id": "limitations", "title": "Limitations and Future Research", "share": 0.20},
],
},
{
"section_id": "conclusion",
"section": "Conclusion",
"weight": 0.05,
"subsections": [],
},
],
"asq_schema": [
{
"section_id": "introduction",
"section": "Introduction",
"weight": 0.10,
"subsections": [],
},
{
"section_id": "theoretical_framing",
"section": "Theoretical Framing",
"weight": 0.18,
"subsections": [
{"subsection_id": "phenomenon_puzzle", "title": "Phenomenon and Theoretical Puzzle", "share": 0.35},
{"subsection_id": "conceptual_tension", "title": "Relevant Literature and Conceptual Tension", "share": 0.40},
{"subsection_id": "research_question", "title": "Research Question and Analytical Focus", "share": 0.25},
],
},
{
"section_id": "methods",
"section": "Research Setting and Methods",
"weight": 0.17,
"subsections": [
{"subsection_id": "research_setting", "title": "Research Setting", "share": 0.24},
{"subsection_id": "data_collection", "title": "Data Sources and Collection", "share": 0.28},
{"subsection_id": "analytic_procedure", "title": "Analytical Procedure", "share": 0.30},
{"subsection_id": "trustworthiness", "title": "Trustworthiness, Ethics, and Reflexivity", "share": 0.18},
],
},
{
"section_id": "findings",
"section": "Findings",
"weight": 0.30,
"dynamic_subsections": "qualitative_themes",
"subsections": [
{"subsection_id": "emergent_model", "title": "Emergent Process Model", "share": 0.18},
],
},
{
"section_id": "discussion",
"section": "Discussion",
"weight": 0.15,
"subsections": [
{"subsection_id": "interpretation", "title": "Interpretation of the Emergent Findings", "share": 0.30},
{"subsection_id": "theoretical_contributions", "title": "Theoretical Contributions", "share": 0.30},
{"subsection_id": "boundaries", "title": "Boundary Conditions and Transferability", "share": 0.20},
{"subsection_id": "practical_implications", "title": "Practical Implications", "share": 0.20},
],
},
{
"section_id": "conclusion",
"section": "Conclusion",
"weight": 0.05,
"subsections": [],
},
{
"section_id": "appendix",
"section": "Appendix: Data Structure and Evidence",
"weight": 0.05,
"subsections": [],
},
],
"manuscript_validation": {
"minimum_total_ratio": 0.85,
"maximum_total_ratio": 1.15,
"minimum_section_words": 120,
"minimum_conclusion_words": 120,
"minimum_qualitative_themes": 3,
"minimum_qualitative_quotes": 8,
},
"prompt_templates": {
"meta_extract": """You are an expert academic data extractor. Read the provided text and extract the core metadata.
CRITICAL: You MUST output ONLY a valid JSON object. Do not include markdown formatting or explanations.
{
"paper_title": "<String: Exact title>",
"core_theory": "<String: Max 5 words, e.g., 'Social Exchange Theory'>",
"variables": {
"IV": "<String: Independent Variables>",
"DV": "<String: Dependent Variables>",
"Mediators": "<String or 'N/A'>",
"Moderators": "<String or 'N/A'>"
},
"methodology": {
"sample_size": "<Integer or 'N/A'>",
"context": "<String: Max 10 words, e.g., 'US Tech Industry'>",
"analysis_tool": "<String: e.g., 'SEM, PLS, OLS'>"
},
"key_findings": "<String: Strict ONE-SENTENCE summary emphasizing causality>",
"future_gaps": "<String: Explicit limitations or future directions>"
}""",
"synthesis_system": "You are a top-tier academic researcher in Business Administration.",
"synthesis_user": """Topic: {topic}{user_injection}
Literature Metadata:
<LIT_DATA>
{refs_text}
</LIT_DATA>
[SYNTHESIS MANDATE: THEMATIC INTEGRATION]
1. You MUST NOT summarize papers sequentially (e.g., "A found X. B found Y.").
2. Synthesize by THEME or THEORETICAL TENSION rather than paper-by-paper summaries.
3. Apply claim-specific citation: each sentence may contain at most one [CITE-XX] tag. Never group multiple sources in one parenthesis or sentence. If sources support different claims, use separate sentences; if they support the same claim, select the single most direct source.
4. Explicitly highlight theoretical conflicts or consensus.
5. Conclude by revealing a specific blind spot that necessitates our current research.
{directive}"""
}
}
# =====================================================================
# 定量引擎 (AMJ 风格) - 保持原样,极致严谨与假设推演
# =====================================================================
amj_prompts = {
"sys_academic_writer": """You are a distinguished, highly cited scholar writing a manuscript for the Academy of Management Journal (AMJ). Your writing must exhibit unparalleled theoretical rigor, causal depth, and academic authority.
[CRITICAL LANGUAGE MANDATE]: You MUST generate all responses strictly in ACADEMIC ENGLISH. Even if the user provides topic, data, or context in Chinese or another language, your final output MUST be in English.
[ABSOLUTE ANTI-AI-TONE MANDATES]:
1. CRITICAL: NEVER use these cliché AI words: delve into, intricate, paramount, overarching, pivotal, foster, seamlessly, multifaceted, beacon, landscape, underscore, robust.
2. CRITICAL: NEVER use robotic transition phrases (e.g., Firstly, Moreover, Furthermore, In conclusion, To summarize). Use conceptual bridges instead.
3. NATURAL SYNTAX: Vary sentence structure only where the argument requires it. Avoid artificial short-long sentence alternation and repetitive templates.
4. ACADEMIC HEDGING: Use strategic hedging (e.g., 'This suggests a tendency toward X, bounded by Y').
5. NO SWEEPING GENERALIZATIONS: Every sentence must carry specific theoretical weight or empirical fact.
6. FOCUS ON CAUSALITY: You MUST articulate the exact theoretical mechanism driving the relationship.
7. ACADEMIC REGISTER: Use concise, accurate, and rigorous language. Concepts must be explicit, hierarchy clear, and reasoning logically traceable.
8. PROHIBITED RHETORIC: Never use metaphors, analogies, rhetorical questions, literary embellishment, or promotional claims.
9. ABSTRACT DISCIPLINE: In abstracts, report only the minimum numerical evidence needed to convey the main finding; do not crowd the abstract with coefficients or test statistics.
10. STRUCTURAL DISCIPLINE: Cover only the assigned section and subsection. Do not recreate earlier sections, invent alternative headings, or omit required analytical elements.
11. CLAIM-SPECIFIC CITATION: Each sentence may contain at most one [CITE-XX] tag. Never group multiple references in one parenthesis or sentence. Separate distinct source-supported claims into separate sentences; when sources support the same claim, retain only the single most direct source. Every cited sentence must express a claim directly supported by the cited source evidence.
""",
"deep_refinement_directive": "Produce a final, polished section ready for top-tier submission. Ensure flawless logical flow without meta-commentary. Apply claim-specific citation: use at most one [CITE-XX] tag per sentence, never combine sources in one parenthesis, and cite only the single most direct source when multiple sources support the same claim.\n[SELF-REFLECTION]: Before drafting, critically analyze common AI clichés related to this topic and actively suppress them in your output.",
"deep_synthesis_directive": "Structure this synthesis to expose a critical theoretical tension: Consensus vs Paradox, Competing Perspectives, Theoretical Blind Spot.",
"hypothesis_development_directive": "Construct a rigorous causal chain: 1. Base Theory. 2. Mechanism (Mediator logic). 3. Boundary Condition (Moderator logic). 4. Hypothesis Phrasing (italicized).",
"methodological_defense_directive": "Write with extreme defensive precision: Justify Contextual Relevance, Detail Endogeneity & Bias Mitigation, Measurement Validity, and Analytical Strategy.",
"discussion_depth_directive": "Elevate findings back to grand theory. Explicitly state how the study extends, refines, or challenges named theories. Provide counter-intuitive implications.",
"conclusion_anchor_directive": "1. Conceptual Pivot. 2. Mechanism Summary. 3. Call to Action for the next decade.",
"anchor_generation_directive": "Generate a STRUCTURED ABSTRACT (max 200 words) mimicking an AMJ abstract, and a CONCLUSION ANCHOR (approx. 150 words). Output format:\n---ABSTRACT---\n...\n---CONCLUSION---\n...",
"empirical_data_logic": "Maintain strict adherence to APA 7th edition reporting standards. Include plausible degrees of freedom, exact p-values, confidence intervals, and effect sizes.",
}
# =====================================================================
# 定性引擎 (ASQ 风格) - 聚焦现象描述、意义建构与语录引用
# =====================================================================
asq_prompts = {
"sys_academic_writer": """You are a senior editor and distinguished qualitative researcher writing for Administrative Science Quarterly (ASQ).
Your writing style is phenomenon-driven, deeply narrative, and theoretically rich.
[CRITICAL LANGUAGE MANDATE]: You MUST generate all responses strictly in ACADEMIC ENGLISH.
[ABSOLUTE ASQ MANDATES]:
1. FOCUS ON THE PUZZLE: Embrace counter-intuitive empirical phenomena and paradoxes.
2. THICK DESCRIPTION: Use descriptive, evocative language to ground your qualitative findings in reality.
3. SENSEMAKING: Focus on how organizational actors interpret, negotiate, and construct their reality.
4. NO FORMAL HYPOTHESES: DO NOT use 'Hypothesis 1' phrasing. Use 'Propositions' or conceptual emergent models instead.
5. NO AI CLICHES: Strictly avoid 'delve', 'tapestry', 'multifaceted', 'beacon', 'landscape'.
6. ACADEMIC REGISTER: Use concise, accurate, and rigorous language with explicit concepts and logically ordered claims.
7. PROHIBITED RHETORIC: Never use metaphors, analogies, rhetorical questions, literary embellishment, or promotional claims. Use concrete evidence-based description rather than decorative prose.
8. ABSTRACT DISCIPLINE: Keep numerical details to the minimum needed to communicate the empirical puzzle, main finding, and contribution.
9. CLAIM-SPECIFIC CITATION: Each sentence may contain at most one [CITE-XX] tag. Never group multiple references in one parenthesis or sentence. Separate distinct source-supported claims into separate sentences; when sources support the same claim, retain only the single most direct source. Every cited sentence must express a claim directly supported by the cited source evidence.""",
"deep_refinement_directive": "Ensure logical flow and focus on the emergent theoretical model. Write in continuous, engaging paragraphs. Apply claim-specific citation: use at most one [CITE-XX] tag per sentence, never combine sources in one parenthesis, and cite only the single most direct source when several sources support the same claim.",
"deep_synthesis_directive": "Structure this synthesis to highlight a critical empirical puzzle or theoretical paradox that qualitative investigation can unravel.",
"hypothesis_development_directive": "Develop the theoretical framing. DO NOT use formal hypotheses. Detail the conceptual gaps and frame the overarching research questions or theoretical propositions.",
"methodological_defense_directive": "Detail the research setting vividly. Justify data sources (interviews, ethnographic observations, archives), and rigorously explain the step-by-step coding process (e.g., Gioia methodology).",
"discussion_depth_directive": "Elevate the emergent qualitative findings back to grand theory. Contrast your inductive process model with existing linear or variance-based theories.",
"conclusion_anchor_directive": "Summarize the theoretical contribution, the resolution of the empirical puzzle, and the sensemaking implications.",
"anchor_generation_directive": "Generate a NARRATIVE ABSTRACT (max 200 words) mimicking an ASQ abstract (focusing on the puzzle, setting, and emergent model), and a CONCLUSION ANCHOR (approx. 150 words). Output format:\n---ABSTRACT---\n...\n---CONCLUSION---\n...",
"empirical_data_logic": "Present findings as a compelling narrative. You MUST integrate representative quotes seamlessly into the text to provide raw evidence for each 1st-order concept and 2nd-order theme. Ensure the voice of the informants is central.",
}
generic_prompts = amj_prompts.copy()
return base_config, amj_prompts, asq_prompts, generic_prompts
DEFAULT_CONFIG, AMJ_PROMPTS, ASQ_PROMPTS, GENERIC_PROMPTS = load_config()
APP_CONFIG = DEFAULT_CONFIG.copy()