DSPy: The framework for programming—not prompting—language models
Python
[Doc PR Part 3] Add scripts to automatically generate API reference md files (#1980)
Chen Qianb666f49a44e1
diff --git a/docs/README.md b/docs/README.mdindex faf7d6072..69f7aa134 100644--- a/docs/README.md+++ b/docs/README.md@@ -16,7 +16,13 @@ To build and test the documentation locally:pip install -r requirements.txt```-3. Run the build command:+3. Generate the API docs and index them:+ ```bash+ python scripts/generate_api_docs.py+ python scripts/generate_api_summary.py+ ```++4. Run the build command:```bashmkdocs build```diff --git a/docs/docs/stylesheets/extra.css b/docs/docs/stylesheets/extra.cssindex 778ac93a7..346bf3d16 100644--- a/docs/docs/stylesheets/extra.css+++ b/docs/docs/stylesheets/extra.css@@ -1,14 +1,12 @@/* Custom styles for logo */-.md-logo {+.md-logo, .md-logo img {width: auto !important;- height: 1.5rem !important; /* Reduced from 1.8rem */+ height: 1.5rem !important;padding: 0 !important;margin: 0 !important;}.md-logo img {- width: auto !important;- height: 1.5rem !important; /* Reduced from 1.8rem */object-fit: contain !important;}@@ -47,13 +45,6 @@}}-/* Fully responsive on smaller screens */-/* @media (max-width: 6px) {- .md-content {- max-width: 98%;- }-} */-/* Justified text for main content */.md-content__inner p {@@ -105,3 +96,136 @@ body[data-md-color-scheme="slate"] .jp-Cell-outputWrapper .jp-OutputArea-output.md-sidebar {width: 235px;}++/* Adjust search bar position */+.md-search {+ margin-left: auto;+ padding-right: 0;+}++/* If you need to adjust the width of the search bar */+.md-search__inner {+ width: 13rem;+}++/* Adjust repository button position and alignment */+.md-header__source {+ margin-left: 1rem;+ margin-right: 0;+ text-align: right; /* Keep right alignment for container */+ width: auto; /* Allow container to shrink to content */+}++.md-header__source .md-source {+ justify-content: flex-start; /* Change to flex-start to align text to left */+ width: auto; /* Allow element to shrink to content */+ min-width: 0; /* Remove minimum width constraint */+}++.md-header__source .md-source__icon {+ order: 2; /* Keep icon on the right */+ margin-left: 0.5rem;+ margin-right: 0;+}++.md-header__source .md-source__repository {+ order: 1; /* Keep text on the left */+ text-align: left; /* Ensure text is left-aligned */+ width: auto; /* Allow text container to shrink */+}++h2.doc-heading {+ font-size: 1rem;+ font-weight: 700;+}++/* Add more spacing between API sections */+.doc-heading {+ margin-top: 1em;+ border-top: 1px solid var(--md-default-fg-color--lightest);+ font-size: 0.85rem;+}++/* Make method names more prominent */+.doc-method, .doc-function {+ background-color: var(--md-code-bg-color);+ padding: 0.1em;+ margin: 0.5em 0;+ border-radius: 4px;+}++/* Make class documentation stand out */+.doc-class {+ padding: 1em;+ margin: 1em 0;+ border-left: 4px solid var(--md-primary-fg-color);+ background-color: var(--md-code-bg-color);+}++/* Style for type labels */+.doc-label {+ font-size: 0.8em;+ padding: 0.2em 0.6em;+ border-radius: 4px;+ background-color: var(--md-code-bg-color);+ display: inline-block;+ margin: 0.2em 0;+ font-weight: 400;+ text-transform: none; /* Prevent uppercase transformation */+ color: var(--md-code-fg-color);+}++/* Add indentation and visual cues for nested navigation items */+.md-nav__item .md-nav__item {+ padding-left: 0.3rem;+ border-left: 1px solid var(--md-primary-fg-color--light);+ margin-left: 0.2rem;+}++/* Add some spacing between items */+.md-nav__item {+ margin: 0.3em 0; /* Reduced from 0.4em */+}++/* Optional: add hover effect */+.md-nav__item .md-nav__item:hover {+ border-left-color: var(--md-primary-fg-color);+}+++/* Enhance code examples in documentation */+.highlight {+ background-color: #f8f9fa;+ border: 1px solid #e9ecef;+ border-radius: 6px;+ margin: 1.5em 0;+ padding: 1em;+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);+}++/* Dark mode adjustments */+[data-md-color-scheme="slate"] .highlight {+ background-color: #2b2b2b;+ border-color: #404040;+}++/* Add subtle left border for visual interest */+.highlight pre {+ margin: 0;+}++/* Ensure code is readable */+.highlight code {+ font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;+ font-size: 0.9em;+}++/* Copy button styling */+.highlight .md-clipboard {+ color: var(--md-default-fg-color--lighter);+}++.highlight .md-clipboard:hover {+ color: var(--md-accent-fg-color);+}+diff --git a/docs/mkdocs.yml b/docs/mkdocs.ymlindex 9577774e4..e5846b039 100644--- a/docs/mkdocs.yml+++ b/docs/mkdocs.yml@@ -64,7 +64,6 @@ nav:- FAQ: faqs.md- Cheatsheet: cheatsheet.md-theme:name: materialcustom_dir: overrides@@ -108,7 +107,33 @@ extra_css:plugins:- social- search- - mkdocstrings+ - mkdocstrings:+ handlers:+ python:+ options:+ docstring_style: google+ show_source: true+ show_root_heading: true+ heading_level: 3+ members_order: source+ separate_signature: false+ show_category_heading: true+ show_symbol_type_heading: true+ show_docstring_parameters: true+ show_if_no_docstring: true+ show_signature_annotations: true+ unwrap_annotated: true+ annotations_path: brief+ docstring_section_style: table+ merge_init_into_class: true+ rendering:+ show_if_no_docstring: true+ show_warnings: false+ html_meta: false+ docstring_options:+ returns_style: table+ separate_signature: false+ merge_return_lines: true- mkdocs-jupyter:ignore_h1_titles: True- redirects:diff --git a/docs/scripts/generate_api_docs.py b/docs/scripts/generate_api_docs.pynew file mode 100644index 000000000..0a78bde26--- /dev/null+++ b/docs/scripts/generate_api_docs.py@@ -0,0 +1,159 @@+from pathlib import Path+import importlib+import inspect+import pkgutil+import shutil+from typing import Any+++def get_module_contents(module):+ """Get all public classes and functions from a module."""+ contents_in_all = getattr(module, "__all__", None)++ contents = {}+ for name, obj in inspect.getmembers(module):+ if contents_in_all and name not in contents_in_all:+ continue+ if inspect.ismodule(obj) and obj.__name__.startswith(module.__name__) and not name.startswith("_"):+ contents[name] = obj+ elif (+ (inspect.isclass(obj) or inspect.isfunction(obj))+ and obj.__module__.startswith(module.__name__)+ and not name.startswith("_")+ ):+ contents[name] = obj+ return contents+++def get_public_methods(cls):+ """Returns a list of all public methods in a class."""+ return [+ name+ for name, member in inspect.getmembers(cls, predicate=inspect.isfunction)+ if name == "__call__" or not name.startswith("_") # Exclude private and dunder methods, but include `__call__`+ ]+++def generate_doc_page(name: str, module_path: str, obj: Any, is_root: bool = False) -> str:+ """Generate documentation page content for an object."""+ members_config = ""+ if inspect.isclass(obj):+ methods = get_public_methods(obj)+ if methods:+ methods_list = "\n".join(f" - {method}" for method in methods)+ members_config = f"""+ members:+{methods_list}"""++ return f"""# {module_path}.{name}++::: {module_path}.{name}+ handler: python+ options:{members_config}+ show_source: true+ show_undocumented_members: true+ show_root_heading: true+ show_inherited_members: true+ heading_level: 2+ docstring_style: google+ show_root_full_path: true+ show_object_full_path: false+ separate_signature: false+"""+++def generate_md_docs(output_dir: Path, excluded_modules=None):+ """Generate documentation for all public classes and functions in the dspy package.++ Args:+ output_dir: The directory to write the documentation to, e.g. "docs/api"+ excluded_modules: A list of modules to exclude from documentation, e.g. ["dspy.dsp"]+ """+ module = importlib.import_module("dspy")+ output_dir.mkdir(parents=True, exist_ok=True)++ init_contents = get_module_contents(module)+ objects_processed = {}++ # Generate docs for root-level objects, e.g. dspy.Predict, dspy.Example, etc.+ for name, obj in init_contents.items():+ if inspect.ismodule(obj):+ continue++ page_content = generate_doc_page(name, "dspy", obj, is_root=True)+ with open(output_dir / f"{name}.md", "w") as f:+ f.write(page_content)++ objects_processed[f"{obj.__module__}.{name}"] = obj++ for submodule in pkgutil.iter_modules(module.__path__, prefix=f"{module.__name__}."):+ submodule_name = submodule.name.split(".")[-1]++ # Skip if this is a private module or not in __init__.py+ if submodule_name.startswith("_") or submodule_name not in init_contents:+ continue++ generate_md_docs_submodule(submodule.name, output_dir / submodule_name, objects_processed, excluded_modules)+++def generate_md_docs_submodule(module_path: str, output_dir: Path, objects_processed=None, excluded_modules=None):+ """Recursively generate documentation for a submodule.++ We generate docs for all public classes and functions in the submodule, then recursively generate docs for all+ submodules within the submodule.++ Args:+ module_path: The path to the submodule, e.g. "dspy.predict"+ output_dir: The directory to write the documentation to, e.g. "docs/api/predict"+ objects_processed: A dictionary of objects that have already been processed, used to avoid redundant processing.+ excluded_modules: A list of modules to exclude from documentation, e.g. ["dspy.dsp"]+ """+ if excluded_modules and module_path in excluded_modules:+ return++ try:+ module = importlib.import_module(module_path)+ except ImportError:+ print(f"Skipping {module_path} due to import error")+ return+ output_dir.mkdir(parents=True, exist_ok=True)++ init_contents = get_module_contents(module)++ for name, obj in init_contents.items():+ if inspect.ismodule(obj):+ continue++ full_name = f"{obj.__module__}.{name}"+ if full_name not in objects_processed:+ # Only generate docs for objects that are not root-level objects.+ page_content = generate_doc_page(name, module_path, obj, is_root=False)+ with open(output_dir / f"{name}.md", "w") as f:+ f.write(page_content)++ objects_processed[full_name] = obj++ for name, obj in init_contents.items():+ if inspect.ismodule(obj):+ generate_md_docs_submodule(f"{module_path}.{name}", output_dir / name, objects_processed)+++def remove_empty_dirs(path: Path):+ """Recursively remove empty directories."""+ for child in path.glob("*"):+ if child.is_dir():+ remove_empty_dirs(child)++ if path.is_dir() and not any(path.iterdir()):+ path.rmdir()+++if __name__ == "__main__":+ api_dir = Path("docs/api")+ if api_dir.exists():+ shutil.rmtree(api_dir)++ excluded_modules = ["dspy.dsp"]+ generate_md_docs(api_dir, excluded_modules=excluded_modules)+ # Clean up empty directories+ remove_empty_dirs(api_dir)diff --git a/docs/scripts/generate_api_summary.py b/docs/scripts/generate_api_summary.pynew file mode 100644index 000000000..0bb412bd1--- /dev/null+++ b/docs/scripts/generate_api_summary.py@@ -0,0 +1,134 @@+from pathlib import Path+++def build_nav_structure(directory: Path, base_path: Path) -> dict:+ """Recursively build navigation structure for a directory."""+ nav = {}++ # Get all items in current directory+ items = sorted(directory.iterdir())++ # First handle all MD files in current directory+ for path in items:+ if path.suffix == ".md":+ name = path.stem+ nav[name] = str(path.relative_to(base_path))++ # Then handle all subdirectories+ for path in items:+ if path.is_dir():+ sub_nav = build_nav_structure(path, base_path)+ if sub_nav: # Only add non-empty directories+ nav[path.name] = sub_nav++ return nav+++def format_nav_section(nav_dict, indent_level=2):+ """Convert dictionary to properly indented nav section"""+ lines = []+ indent = " " * indent_level++ module_navs = []+ file_navs = []+ for key, value in sorted(nav_dict.items()):+ if isinstance(value, dict):+ # This is a section+ module_navs.append(f"{indent}- {key}:")+ module_navs.extend(format_nav_section(value, indent_level + 1))+ else:+ # This is a file+ file_navs.append(f"{indent}- {key}: {value}")++ # Put submodules' nav items before file nav items. e.g., `dspy.evaluate` before `dspy.ChainOfThought`+ # in the nav section.+ lines.extend(module_navs)+ lines.extend(file_navs)++ return lines+++def read_mkdocs_sections(filename: str = "mkdocs.yml"):+ """Read and parse the mkdocs.yml file into sections."""+ with open(filename, "r") as f:+ lines = f.readlines()++ nav_start = -1+ theme_start = -1++ # Find section boundaries+ for i, line in enumerate(lines):+ if line.strip() == "nav:":+ nav_start = i+ elif line.strip() == "theme:":+ theme_start = i+ break++ # Split content into sections+ pre_nav = lines[: nav_start + 1] # Include the 'nav:' line+ nav_content = []+ post_theme = lines[theme_start:] # Start from 'theme:' line++ # Extract nav content excluding API Reference+ i = nav_start + 1+ while i < theme_start:+ line = lines[i]+ if line.strip() == "- API Reference:":+ # Skip this line and all indented lines that follow+ i += 1+ while i < theme_start and (not lines[i].strip() or lines[i].startswith(" " * 8)):+ i += 1+ else:+ nav_content.append(line)+ i += 1++ return pre_nav, nav_content, post_theme+++def generate_api_nav():+ """Generate the API navigation structure."""+ api_nav = {}+ api_path = Path("docs/api")++ # First process each top-level module directory+ for dir_path in sorted(api_path.iterdir()):+ if dir_path.is_dir():+ category = dir_path.name+ api_nav[category] = build_nav_structure(dir_path, Path("docs"))++ # Then process any .md files directly in the api directory+ for path in sorted(api_path.glob("*.md")):+ if path.parent == api_path: # Only process files directly in api/+ name = path.stem+ api_nav[name] = str(path.relative_to(Path("docs")))++ return api_nav+++def main():+ """Main function to generate the API documentation summary."""+ # Read existing mkdocs.yml sections+ pre_nav, nav_content, post_theme = read_mkdocs_sections()++ # Generate API navigation structure+ api_nav = generate_api_nav()++ # Create API section+ api_section = [" - API Reference:"]+ api_section.extend(format_nav_section(api_nav))+ api_section.append("") # Add empty line before theme section++ # Write back to mkdocs.yml+ with open("mkdocs.yml", "w") as f:+ # Write pre-nav content+ f.writelines(pre_nav)+ # Write nav content+ f.writelines(nav_content)+ # Add API section+ f.write("\n".join(api_section) + "\n")+ # Write post-theme content+ f.writelines(post_theme)+++if __name__ == "__main__":+ main()