• Documentation
    • About ​ValidMind
    • Get Started
    • Guides
    • Support
    • Releases

    • ValidMind Library
    • Python API
    • Public REST API

    • Training Courses
  • Log In
  1. Code samples
  2. Code explainer
  3. Quickstart for model code documentation
  • ValidMind Library
  • Supported records and frameworks

  • Quickstart
  • Quickstart for documentation
  • Quickstart for validation
  • Install and initialize ValidMind
    • Install and initialize the library
    • Install and initialize the library for R
    • Use an HTTP proxy with the library
  • Store credentials in .env files

  • End-to-End Tutorials
  • Development
    • 1 — Set up ValidMind Library
    • 2 — Start the development process
    • 3 — Integrate custom tests
    • 4 — Finalize testing & documentation
  • Validation
    • 1 — Set up ValidMind Library for validation
    • 2 — Start the validation process
    • 3 — Developing a challenger
    • 4 — Finalize validation & reporting

  • How-To
  • Run tests & test suites
    • Explore tests
      • Explore tests
      • Explore test suites
    • Run tests
      • Run dataset-based tests
      • Run comparison tests
      • Configuring tests
        • Configure judge LLM and judge embeddings
        • Customize test result descriptions
        • Enable PII detection in tests
        • Dataset Column Filters when Running Tests
        • Run tests with multiple datasets
        • Understand and utilize RawData in ValidMind tests
      • Using tests in documentation
        • Document multiple results for the same test
        • Run individual documentation sections
        • Run documentation tests with custom configurations
    • Custom tests
      • Implement custom tests
      • Integrate external test providers
  • Use library features
    • Data and datasets
      • Introduction to ValidMind Dataset and Model Objects
      • Dataset inputs
        • Configure dataset features
        • Load dataset predictions
    • Metrics
      • Log metrics over time
      • Intro to Unit Metrics
    • Qualitative text
      • Generate qualitative text with the ValidMind library
    • Scoring
      • Intro to Assign Scores

  • Notebooks
  • Code samples
    • Agents
      • Document an agentic AI system
    • Capital markets
      • Quickstart for knockout option pricing model documentation
      • Quickstart for Heston option pricing model using QuantLib
    • Code explainer
      • Quickstart for model code documentation
    • Credit risk
      • Document an application scorecard model
      • Document an application scorecard model
      • Document a credit risk model
      • Document an application scorecard model
      • Document an Excel-based application scorecard model
    • NLP and LLM
      • Sentiment analysis of financial data using a large language model (LLM)
      • Summarization of financial data using a large language model (LLM)
      • Sentiment analysis of financial data using Hugging Face NLP models
      • Summarization of financial data using Hugging Face NLP models
      • Automate news summarization using LLMs
      • Prompt validation for large language models (LLMs)
      • RAG Model Benchmarking Demo
      • RAG Model Documentation Demo
    • Ongoing monitoring
      • Ongoing Monitoring for Application Scorecard
      • Quickstart for ongoing monitoring of models with ValidMind
    • Regression
      • Document a California Housing Price Prediction regression model
    • Time series
      • Document a time series forecasting model
      • Document a time series forecasting model
    • Validation
      • Validate an application scorecard model

  • Reference
  • ​ValidMind test sandbox
  • ValidMind Library Python API
  • ValidMind Public REST API

On this page

  • About Code Explainer
  • About ValidMind
    • Before you begin
    • New to ValidMind?
    • Key concepts
  • Setting up
    • Install the ValidMind Library
    • Initialize the ValidMind Library
    • Preview the documentation template
  • Common function
  • Default Behavior
  • Codebase Overview
  • Environment and Dependencies ('environment_setup')
  • Data Ingestion and Preprocessing
  • Model Implementation Details
  • Model Training Pipeline
  • Evaluation and Validation Code
  • Inference and Scoring Logic
  • Configuration and Parameters
  • Unit and Integration Testing
  • Logging and Monitoring Hooks
  • Code and Model Versioning
  • Security and Access Control
  • Example Runs and Scripts
  • Known Issues and Future Improvements
  • Edit this page
  • Report an issue
  1. Code samples
  2. Code explainer
  3. Quickstart for model code documentation

Quickstart for model code documentation

Welcome! This notebook demonstrates how to use the ValidMind code explainer to automatically generate comprehensive documentation for your codebase. The code explainer analyzes your source code and provides detailed explanations across various aspects of your implementation.

About Code Explainer

The ValidMind code explainer is a powerful tool that automatically analyzes your source code and generates comprehensive documentation. It helps you:

  • Understand the structure and organization of your codebase
  • Document dependencies and environment setup
  • Explain data processing and model implementation details
  • Document training, evaluation, and inference pipelines
  • Track configuration, testing, and security measures

This tool is particularly useful for: - Onboarding new team members - Maintaining up-to-date documentation - Ensuring code quality and best practices - Facilitating code reviews and audits

About ValidMind

ValidMind is a suite of tools for managing risk, including risk associated with AI and statistical models.

You use the ValidMind Library to automate documentation and validation tests, and then use the ValidMind Platform to collaborate on documentation. Together, these products simplify risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and validators.

Before you begin

This notebook assumes you have basic familiarity with Python, including an understanding of how functions work. If you are new to Python, you can still run the notebook but we recommend further familiarizing yourself with the language.

If you encounter errors due to missing modules in your Python environment, install the modules with pip install, and then re-run the notebook. For more help, refer to Installing Python Modules.

New to ValidMind?

If you haven't already seen our documentation on the ValidMind Library, we recommend you begin by exploring the available resources in this section. There, you can learn more about documenting records such as models and running tests, as well as find code samples and our Python Library API reference.

For access to all features available in this notebook, you'll need access to a ValidMind account.

Register with ValidMind

Key concepts

record: A tool tracked in the ValidMind inventory, such as a model. Records include traditional statistical models, legacy systems, artificial intelligence/machine learning models, large language models (LLMs), agentic AI systems, and other documentable items that benefit from oversight, testing, and lifecycle management.

model: SR 26-2 (which supersedes SR 11-7) defines a model as a "complex quantitative method, system, or approach that applies statistical, economic, or financial theories to process input data into quantitative estimates." Simple arithmetic, deterministic rule-based processes, or software without statistical, economic, or financial theories underpinning their design or use are generally outside SR 26-2’s definition of a model. Within ValidMind, a model is a type of record tracked in the inventory.

documentation, model documentation: A structured and detailed document pertaining to a record, encompassing key components such as its underlying assumptions, methodologies, data sources, inputs, performance metrics, evaluations, limitations, and intended uses. Within the realm of risk management, this documentation serves to ensure transparency, adherence to regulatory requirements, and a clear understanding of potential risks associated with the record's application.

document template: Lays out the structure of documents, segmented into various sections and sub-sections, and functions as a test suite specifying the tests that should be run, and how the results should be displayed. Document templates help automate your development, validation, monitoring, and other risk management processes. Document templates are available for default ValidMind document types as well as custom document types.

documentation template: A default ValidMind document type that serves as a standardized framework for developing and documenting records, including sections designated for record details, data descriptions, test results, and performance metrics. By outlining required documentation and recommended analyses, document templates ensure consistency and completeness across documentation and help guide developers through a systematic development process while promoting comparability and traceability of development outcomes.

test: A function contained in the ValidMind Library, designed to run a specific quantitative test on the dataset or record. Test results are logged to the ValidMind Platform, where they are attached to documents. Tests are the building blocks of ValidMind, used to evaluate and document records and datasets, and can be run individually or as part of a suite defined by your templates.

test suite: A collection of tests designed to run together to automate and generate documentation end-to-end for specific use cases. (Learn more: test_suites)

metric: A subset of tests that do not have thresholds. In the context of this notebook, metrics and tests can be thought of as interchangeable concepts.

custom test: Functions that you define to evaluate your record or dataset. These functions can be registered with the ValidMind Library to be used in the ValidMind Platform.

inputs: Objects to be evaluated and documented in the ValidMind Library. They can be any of the following:

  • model: A single record that has been initialized in ValidMind with init_model(). Despite the naming convention, model objects can be any type of record you want to test, document, validate, or monitor with ValidMind.
  • dataset: A single dataset that has been initialized in ValidMind with init_dataset().
  • models: A list of ValidMind records - usually this is used when you want to compare multiple records in your custom tests.
  • datasets: A list of ValidMind datasets - usually this is used when you want to compare multiple datasets in your custom tests. (Learn more: Run tests with multiple datasets)

parameters: Additional arguments that can be passed when running a ValidMind test, used to pass additional information to a test, customize its behavior, or provide additional context.

outputs: Custom tests can return elements like tables or plots. Tables may be a list of dictionaries (each representing a row) or a pandas DataFrame. Plots may be matplotlib or plotly figures.

Setting up

Install the ValidMind Library

To install the library:

%pip install -q validmind

Initialize the ValidMind Library

Register sample model

Let's first register a sample record (model) for use with this notebook:

  1. In a browser, log in to ValidMind.

  2. In the left sidebar, select Inventory.

  3. Under the RECORD TYPE drop-down, select Model and click + Register Model. (Learn more: Register records in the inventory)

  4. Enter the model details and click Next > to continue to assignment of inventory record stakeholders.

  5. Select your own name under the RECORD OWNER drop-down.

  6. Click Register Model to add the model to your inventory.

Apply documentation template

Once you've registered your model, let's select a documentation template. A template predefines sections for your documentation and provides a general outline to follow, making the documentation process much easier.

  1. In the left sidebar that appears for your model, click Documents and select Development.

    If you cannot locate your Development document, make sure Development type documents are enabled for model records and create a new document. (Learn more: Manage documents)

  2. Under TEMPLATE, select Model Source Code Documentation.

  3. Click Use Template to apply the template.

Can't select this template?

Your organization administrators may need to add it to your template library:
  • Download Template YAML
  • Customize Document Templates

Get your code snippet

Initialize the ValidMind Library with the code snippet unique to each record per document, ensuring your test results are uploaded to the correct record and automatically populated in the right document in the ValidMind Platform when you run the Library.

  1. On the left sidebar that appears for your model, select Getting Started and select Development from the DOCUMENT drop-down menu.

  2. Click Copy snippet to clipboard.

  3. Next, load your model identifier credentials from an .env file or replace the placeholder with your own code snippet:

# Load your model identifier credentials from an `.env` file

%load_ext dotenv
%dotenv .env

# Or replace with your code snippet

import validmind as vm

vm.init(
    # api_host="...",
    # api_key="...",
    # api_secret="...",
    # model="...",
    document="documentation",
)

Preview the documentation template

Let's verify that you have connected the ValidMind Library to the ValidMind Platform and that the appropriate template is selected for your model.

You will upload documentation and test results unique to your model based on this template later on. For now, take a look at the default structure that the template provides with the vm.preview_template() function from the ValidMind library and note the empty sections:

vm.preview_template()

Common function

The code above defines two key functions: 1. A function to read source code from 'customer_churn_full_suite.py' file 2. An 'explain_code' function that uses ValidMind's experimental agents to analyze and explain code.

source_code=""
with open("customer_churn_full_suite.py", "r") as f:
    source_code = f.read()

The vm.experimental.agents.run_task function is used to execute AI agent tasks.

It requires: - task: The type of task to run (e.g. code_explainer) - input: A dictionary containing task-specific parameters - For code_explainer, this includes: - source_code (str): The code to be analyzed - user_instructions (str): Instructions for how to analyze the code

def explain_code(content_id: str, user_instructions: str):
    """Run code explanation task and log the results.
    By default, the code explainer includes sections for:
    - Main Purpose and Overall Functionality
    - Breakdown of Key Functions or Components
    - Potential Risks or Failure Points  
    - Assumptions or Limitations
    If you want default sections, specify user_instructions as an empty string.
    
    Args:
        user_instructions (str): Instructions for how to analyze the code
        content_id (str): ID to use when logging the results
    
    Returns:
        The result object from running the code explanation task
    """
    result = vm.experimental.agents.run_task(
        task="code_explainer",
        input={
            "source_code": source_code,
            "user_instructions": user_instructions
        }
    )
    result.log(content_id=content_id)
    return result

Default Behavior

By default, the code explainer includes sections for: - Main Purpose and Overall Functionality - Breakdown of Key Functions or Components - Potential Risks or Failure Points
- Assumptions or Limitations

If you want default sections, specify user_instructions as an empty string. For example:

result = vm.experimental.agents.run_task(
    task="code_explainer",
    input={
        "source_code": source_code,
        "user_instructions": ""
    }
)

Codebase Overview

Let's analyze your codebase structure to understand the main modules, components, entry points and their relationships. We'll also examine the technology stack and frameworks that are being utilized in the implementation.

result = explain_code(
    user_instructions="""
        Please provide a summary of the following bullet points only.
        - Describe the overall structure of the source code repository.
        - Identify main modules, folders, and scripts.
        - Highlight entry points for training, inference, and evaluation.
        - State the main programming languages and frameworks used.
        """,
    content_id="code_structure_summary"
)
result = explain_code(
    user_instructions="",
    content_id="code_structure_summary"
)

Environment and Dependencies ('environment_setup')

Let's document the technical requirements and setup needed to run your code, including Python packages, system dependencies, and environment configuration files. Understanding these requirements is essential for proper development environment setup and consistent deployments across different environments.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - List Python packages and system dependencies (OS, compilers, etc.).
    - Reference environment files (requirements.txt, environment.yml, Dockerfile).
    - Include setup instructions using Conda, virtualenv, or containers.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="setup_instructions"
)

Data Ingestion and Preprocessing

Let's document how your code handles data, including data sources, validation procedures, and preprocessing steps. We'll examine the data pipeline architecture, covering everything from initial data loading through feature engineering and quality checks.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Specify data input formats and sources.
    - Document ingestion, validation, and transformation logic.
    - Explain how raw data is preprocessed and features are generated.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.    """,
    content_id="data_handling_notes"
)

Model Implementation Details

Let's document the core implementation details of your model, including its architecture, components, and key algorithms. Understanding the technical implementation is crucial for maintenance, debugging, and future improvements to the codebase. We'll examine how theoretical concepts are translated into working code.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Describe the core model code structure (classes, functions).
    - Link code to theoretical models or equations when applicable.
    - Note custom components like loss functions or feature selectors.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="model_code_description"
)

Model Training Pipeline

Let's document the training pipeline implementation, including how models are trained, optimized and evaluated. We'll examine the training process workflow, hyperparameter tuning approach, and model checkpointing mechanisms. This section provides insights into how the model learns from data and achieves optimal performance.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Explain the training process, optimization strategy, and hyperparameters.
    - Describe logging, checkpointing, and early stopping mechanisms.
    - Include references to training config files or tuning logic.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="training_logic_details"
)

Evaluation and Validation Code

Let's examine how the model's validation and evaluation code is implemented, including the metrics calculation and validation processes. We'll explore the diagnostic tools and visualization methods used to assess model performance. This section will also cover how validation results are logged and stored for future reference.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Describe how validation is implemented and metrics are calculated.
    - Include plots and diagnostic tools (e.g., ROC, SHAP, confusion matrix).
    - State how outputs are logged and persisted.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="evaluation_logic_notes"
)

Inference and Scoring Logic

Let's examine how the model performs inference and scoring on new data. This section will cover the implementation details of loading trained models, making predictions, and any required pre/post-processing steps. We'll also look at the APIs and interfaces available for both real-time serving and batch scoring scenarios.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Detail how the trained model is loaded and used for predictions.
    - Explain I/O formats and APIs for serving or batch scoring.
    - Include any preprocessing/postprocessing logic required.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="inference_mechanism"
)

Configuration and Parameters

Let's explore how configuration and parameters are managed in the codebase. We'll examine the configuration files, command-line arguments, environment variables, and other mechanisms used to control model behavior. This section will also cover parameter versioning and how different configurations are tracked across model iterations.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Describe configuration management (files, CLI args, env vars).
    - Highlight default parameters and override mechanisms.
    - Reference versioning practices for config files.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="config_control_notes"
)

Unit and Integration Testing

Let's examine the testing strategy and implementation in the codebase. We'll analyze the unit tests, integration tests, and testing frameworks used to ensure code quality and reliability. This section will also cover test coverage metrics and continuous integration practices.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - List unit and integration tests and what they cover.
    - Mention testing frameworks and coverage tools used.
    - Explain testing strategy for production-readiness.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="test_strategy_overview"
)

Logging and Monitoring Hooks

Let's analyze how logging and monitoring are implemented in the codebase. We'll examine the logging configuration, monitoring hooks, and key metrics being tracked. This section will also cover any real-time observability integrations and alerting mechanisms in place.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
    - Describe logging configuration and structure.
    - Highlight real-time monitoring or observability integrations.
    - List key events, metrics, or alerts tracked.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="logging_monitoring_notes"
)

Code and Model Versioning

Let's examine how code and model versioning is managed in the codebase. This section will cover version control practices, including Git workflows and model artifact versioning tools like DVC or MLflow. We'll also look at how versioning integrates with the CI/CD pipeline.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
      - Describe Git usage, branching, tagging, and commit standards.
      - Include model artifact versioning practices (e.g., DVC, MLflow).
      - Reference any automation in CI/CD.
    Please remove the following sections: 
      - Potential Risks or Failure Points
      - Assumptions or Limitations
      - Breakdown of Key Functions or Components
    Please don't add any other sections.
    """,
    content_id="version_tracking_description"
)

Security and Access Control

Let's analyze the security and access control measures implemented in the codebase. We'll examine how sensitive data and code are protected through access controls, encryption, and compliance measures. Additionally, we'll review secure deployment practices and any specific handling of PII data.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
      - Document access controls for source code and data.
      - Include any encryption, PII handling, or compliance measures.
      - Mention secure deployment practices.
    Please remove the following sections: 
      - Potential Risks or Failure Points
      - Assumptions or Limitations
      - Breakdown of Key Functions or Components
    Please don't add any other sections.
    """,
    content_id="security_policies_notes"
)

Example Runs and Scripts

Let's explore example runs and scripts that demonstrate how to use this codebase in practice. We'll look at working examples, command-line usage, and sample notebooks that showcase the core functionality. This section will also point to demo datasets and test scenarios that can help new users get started quickly.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
      - Provide working script examples.
      - Include CLI usage instructions or sample notebooks.
      - Link to demo datasets or test scenarios.
    Please remove the following sections: 
      - Potential Risks or Failure Points
      - Assumptions or Limitations
      - Breakdown of Key Functions or Components
    Please don't add any other sections.
    """,
    content_id="runnable_examples"
)

Known Issues and Future Improvements

Let's examine the current limitations and areas for improvement in the codebase. This section will document known technical debt, bugs, and feature gaps that need to be addressed. We'll also outline proposed enhancements and reference any existing tickets or GitHub issues tracking these improvements.

result = explain_code(
    user_instructions="""
    Please provide a summary of the following bullet points only.
      - List current limitations or technical debt.
      - Outline proposed enhancements or refactors.
      - Reference relevant tickets, GitHub issues, or roadmap items.
    Please remove Potential Risks or Failure Points and Assumptions or Limitations sections. Please don't add any other sections.
    """,
    content_id="issues_and_improvements_log"
)


Copyright © 2023-2026 ValidMind Inc. All rights reserved.
Refer to LICENSE for details.
SPDX-License-Identifier: AGPL-3.0 AND ValidMind Commercial

Quickstart for Heston option pricing model using QuantLib
Document an application scorecard model
  • ValidMind Logo
    ©
    Copyright 2026 ValidMind Inc.
    All Rights Reserved.
    Cookie preferences
    Legal
  • Get started
    • Development
    • Validation
    • Setup & admin
  • Guides
    • Access
    • Configuration
    • Integrations
    • Workflows
    • Inventory
    • Documents & templates
    • Documentation
    • Validation
    • Reporting
    • Monitoring
    • Attestation
  • ValidMind Library
    • Quickstarts
    • Development tutorial
    • Validation tutorial
    • Run tests & test suites
    • Use library features
    • Code samples
    • Python API
    • Public REST API
  • Training
    • Learning paths
    • Courses
    • Videos
  • Support
    • Troubleshooting
    • FAQ
    • Get help
  • Edit this page
  • Report an issue
  • Community
    • GitHub
    • LinkedIn
    • Events
    • Blog