Skip to content

Instantly share code, notes, and snippets.

@jmanhype
Created January 24, 2026 23:12
Show Gist options
  • Select an option

  • Save jmanhype/99142b35817e5772ebe7cad6260aece3 to your computer and use it in GitHub Desktop.

Select an option

Save jmanhype/99142b35817e5772ebe7cad6260aece3 to your computer and use it in GitHub Desktop.
Denario + Zhipu GLM Setup: Generate NeurIPS papers with Chinese LLMs (cheaper than OpenAI/Gemini)

Denario + Zhipu GLM Setup Guide

Generate NeurIPS-format research papers using Denario with Zhipu GLM models (cheaper alternative to OpenAI/Gemini).

Quick Start

# 1. Create virtual environment
python3.12 -m venv ~/denario_env
source ~/denario_env/bin/activate

# 2. Install Denario
pip install denario

# 3. Install TinyTeX for PDF compilation
curl -sL "https://yihui.org/tinytex/install-bin-unix.sh" | sh
~/Library/TinyTeX/bin/*/tlmgr install multirow environ

# 4. Patch Denario for GLM support (see patches below)

# 5. Run paper generation
python generate_paper.py

Required API Keys

Service Purpose Get Key
Zhipu AI LLM (GLM-4.7) https://open.bigmodel.cn
Perplexity Citations https://perplexity.ai

Files in This Gist

  • README.md - This guide
  • generate_paper.py - Complete paper generation script
  • patch_reader.py - Script to patch Denario for GLM support
  • data_description_template.md - Template for your research description

Patches Required

Denario needs two files patched to recognize GLM models:

  1. denario/langgraph_agents/reader.py
  2. denario/paper_agents/reader.py

In both files, find:

elif any(key in state['llm']['model'] for key in ['gpt', 'o3']):

Change to:

elif any(key in state['llm']['model'] for key in ['gpt', 'o3', 'glm']):

Run patch_reader.py to apply automatically.

Rate Limiting

Zhipu has per-minute rate limits. The generation script includes a 2-second delay between LLM calls to avoid 429 errors.

Output

Papers are generated in ./paper/ directory:

  • paper_v1_preliminary.pdf - Basic paper
  • paper_v2_no_citations.pdf - Formatted without citations
  • paper_v3_citations.pdf - Final paper with arXiv citations

Troubleshooting

Error Solution
xelatex not found Install TinyTeX (see above)
429 Too Many Requests Increase sleep delay in script
GLM model not recognized Apply reader.py patches
Data description not found Create input_files/data_description.md

[Your Project Name]: [Brief Description]

System Overview

[2-3 sentences describing what your system/tool/framework does]

Core Innovation

[Describe the key novel contribution - what makes this different from existing approaches?]

Key benefits:

  • [Benefit 1]
  • [Benefit 2]
  • [Benefit 3]

Architecture / Methodology

[Describe the main components or phases of your approach]

  1. [Component 1]: [Description]
  2. [Component 2]: [Description]
  3. [Component 3]: [Description]

Key Features

[List the main features or capabilities]

  • [Feature 1]: [Brief explanation]
  • [Feature 2]: [Brief explanation]
  • [Feature 3]: [Brief explanation]

Technical Implementation

[Describe key technical details]

  • [Technical aspect 1]
  • [Technical aspect 2]
  • [Technical aspect 3]

Experimental Results (Hypothetical)

[If you have results, include them. If not, describe expected outcomes]

  • [Metric 1]: [Value or expected range]
  • [Metric 2]: [Value or expected range]
  • [Metric 3]: [Value or expected range]

Technical Stack

[List the main technologies used]

  • [Technology 1]
  • [Technology 2]
  • [Technology 3]
#!/usr/bin/env python3
"""
Denario Paper Generator with Zhipu GLM Support
Generates NeurIPS-format research papers using GLM-4.7 and Perplexity for citations.
Usage:
1. Create input_files/data_description.md with your research description
2. Set environment variables (or edit this script)
3. Run: python generate_paper.py
Requirements:
- Python 3.12+
- denario (pip install denario)
- TinyTeX for PDF compilation
- Patched reader.py files (run patch_reader.py first)
"""
import os
import sys
import time
# ============================================================================
# CONFIGURATION - Edit these values or set as environment variables
# ============================================================================
# Zhipu API (https://open.bigmodel.cn)
ZHIPU_API_KEY = os.environ.get("ZHIPU_API_KEY", "YOUR_ZHIPU_API_KEY_HERE")
ZHIPU_BASE_URL = "https://open.bigmodel.cn/api/coding/paas/v4"
# Perplexity API for citations (https://perplexity.ai)
PERPLEXITY_API_KEY = os.environ.get("PERPLEXITY_API_KEY", "YOUR_PERPLEXITY_API_KEY_HERE")
# Model settings
MODEL_NAME = "glm-4.7" # Options: glm-4.5-air, glm-4.5, glm-4.6, glm-4.7
MAX_OUTPUT_TOKENS = 16384
TEMPERATURE = 0.7
# Rate limiting (Zhipu has per-minute limits)
RATE_LIMIT_DELAY = 2 # seconds between API calls
# Journal format
JOURNAL = "NeurIPS" # Options: NeurIPS, ICML, Nature, etc.
# ============================================================================
# SETUP
# ============================================================================
# Add TinyTeX to PATH (adjust for your system)
tinytex_paths = [
f"{os.environ['HOME']}/Library/TinyTeX/bin/universal-darwin", # macOS
f"{os.environ['HOME']}/.TinyTeX/bin/x86_64-linux", # Linux
f"{os.environ['HOME']}/bin", # Generic
]
for path in tinytex_paths:
if os.path.exists(path):
os.environ["PATH"] = f"{path}:" + os.environ["PATH"]
break
# Set API credentials
os.environ["OPENAI_API_KEY"] = ZHIPU_API_KEY
os.environ["OPENAI_BASE_URL"] = ZHIPU_BASE_URL
os.environ["PERPLEXITY_API_KEY"] = PERPLEXITY_API_KEY
# ============================================================================
# RATE LIMITING MONKEY-PATCH
# ============================================================================
from langchain_openai import ChatOpenAI
_original_invoke = ChatOpenAI.invoke
_original_stream = ChatOpenAI.stream
def _patched_invoke(self, *args, **kwargs):
time.sleep(RATE_LIMIT_DELAY)
return _original_invoke(self, *args, **kwargs)
def _patched_stream(self, *args, **kwargs):
time.sleep(RATE_LIMIT_DELAY)
return _original_stream(self, *args, **kwargs)
ChatOpenAI.invoke = _patched_invoke
ChatOpenAI.stream = _patched_stream
print(f"Applied {RATE_LIMIT_DELAY}s rate limit delay")
# ============================================================================
# MAIN GENERATION
# ============================================================================
from denario import Denario
from denario.llm import LLM
def main():
print(f"=== Denario Paper Generator ===")
print(f"Model: {MODEL_NAME}")
print(f"Journal: {JOURNAL}")
print()
# Check for data description
if not os.path.exists("input_files/data_description.md"):
print("ERROR: input_files/data_description.md not found!")
print("Create this file with your research description first.")
sys.exit(1)
# Initialize Denario
d = Denario(
project_dir=".",
clear_project_dir=False
)
# Create LLM instance
llm = LLM(
name=MODEL_NAME,
max_output_tokens=MAX_OUTPUT_TOKENS,
temperature=TEMPERATURE
)
# Step 1: Generate Research Idea
print("=== Step 1: Generating Research Idea ===")
d.get_idea(llm=llm)
print("Idea generation complete!")
# Step 2: Generate Methodology
print("\n=== Step 2: Generating Methodology ===")
d.get_method(llm=llm)
print("Methodology generation complete!")
# Step 3: Generate Paper with Citations
print(f"\n=== Step 3: Generating {JOURNAL} Paper with Citations ===")
print("(This will take 15-30 minutes...)")
d.get_paper(llm=llm, journal=JOURNAL, add_citations=True)
print("\n=== Paper generation complete! ===")
print("Output files:")
print(" - ./paper/paper_v1_preliminary.pdf")
print(" - ./paper/paper_v2_no_citations.pdf")
print(" - ./paper/paper_v3_citations.pdf <-- Final paper")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Patch Denario to support Zhipu GLM models.
Run this after installing Denario to enable GLM-4.x model support.
Usage:
python patch_reader.py
"""
import os
import sys
def find_denario_path():
"""Find the Denario installation path."""
try:
import denario
return os.path.dirname(denario.__file__)
except ImportError:
print("ERROR: Denario not installed. Run: pip install denario")
sys.exit(1)
def patch_file(filepath):
"""Patch a reader.py file to support GLM models."""
if not os.path.exists(filepath):
print(f" SKIP: {filepath} not found")
return False
with open(filepath, 'r') as f:
content = f.read()
# Check if already patched
if "'glm'" in content:
print(f" SKIP: {filepath} already patched")
return False
# Find and replace the model check
old_pattern = "['gpt', 'o3']"
new_pattern = "['gpt', 'o3', 'glm']"
if old_pattern not in content:
print(f" WARN: Pattern not found in {filepath}")
return False
new_content = content.replace(old_pattern, new_pattern)
with open(filepath, 'w') as f:
f.write(new_content)
print(f" OK: Patched {filepath}")
return True
def main():
print("=== Denario GLM Patcher ===\n")
denario_path = find_denario_path()
print(f"Denario installation: {denario_path}\n")
# Files to patch
files_to_patch = [
os.path.join(denario_path, "langgraph_agents", "reader.py"),
os.path.join(denario_path, "paper_agents", "reader.py"),
]
patched = 0
for filepath in files_to_patch:
if patch_file(filepath):
patched += 1
print(f"\nPatched {patched} file(s)")
if patched > 0:
print("\nGLM models now supported!")
print("Available models: glm-4.5-air, glm-4.5, glm-4.6, glm-4.7")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment