Code2Prompt is a powerful command-line tool that generates comprehensive prompts from codebases, designed to streamline interactions between developers and Large Language Models (LLMs) for code analysis, documentation, and improvement tasks.
Code2Prompt is a powerful, open-source command-line tool that bridges the gap between your codebase and Large Language Models (LLMs). By converting your entire project into a comprehensive, AI-friendly prompt, Code2Prompt enables you to leverage the full potential of AI for code analysis, documentation, and improvement tasks.
--syntax-map
option. For example, you can specify that .inc
files should be treated as bash
scripts.Transform the way you interact with AI for software development. With Code2Prompt, harness the full power of your codebase in every AI conversation.
Ready to elevate your AI-assisted development? Let's dive in! πββοΈ
Choose one of the following methods to install Code2Prompt:
pip install code2prompt
pipx install code2prompt
To get started with Code2Prompt, follow these steps:
.gitignore
file if necessary.For example, to generate a prompt from a single Python file, run:
code2prompt --path /path/to/your/script.py
Generate a prompt from a single Python file:
code2prompt --path /path/to/your/script.py
Process an entire project directory and save the output:
code2prompt --path /path/to/your/project --output project_summary.md
Generate a prompt for multiple files, excluding tests:
code2prompt --path /path/to/src --path /path/to/lib --exclude "*/tests/*" --output codebase_summary.md
The basic syntax for Code2Prompt is:
code2prompt --path /path/to/your/code [OPTIONS]
For multiple paths:
code2prompt --path /path/to/dir1 --path /path/to/file2.py [OPTIONS]
To pair custom file extensions with specific syntax highlighting, use the --syntax-map
option. This allows you to specify mappings in the format extension:syntax
. For example:
code2prompt --path /path/to/your/code --syntax-map "inc:bash,customext:python,ext2:javascript"
This command will treat .inc
files as bash
scripts, .customext
files as python
, and .ext2
files as javascript
.
You can also use multiple --syntax-map
arguments or separate mappings with commas:
code2prompt --path /path/to/your/script.py --syntax-map "inc:bash"
code2prompt --path /path/to/your/project --syntax-map "inc:bash,txt:markdown" --output project_summary.md
code2prompt --path /path/to/src --path /path/to/lib --syntax-map "inc:bash,customext:python" --output codebase_summary.md
Option | Short | Description |
---|---|---|
--path |
-p |
Path(s) to the directory or file to process (required, multiple allowed) |
--output |
-o |
Name of the output Markdown file |
--gitignore |
-g |
Path to the .gitignore file |
--filter |
-f |
Comma-separated filter patterns to include files (e.g., ".py,.js") |
--exclude |
-e |
Comma-separated patterns to exclude files (e.g., ".txt,.md") |
--case-sensitive |
Perform case-sensitive pattern matching | |
--suppress-comments |
-s |
Strip comments from the code files |
--line-number |
-ln |
Add line numbers to source code blocks |
--no-codeblock |
Disable wrapping code inside markdown code blocks | |
--template |
-t |
Path to a Jinja2 template file for custom prompt generation |
--tokens |
Display the token count of the generated prompt | |
--encoding |
Specify the tokenizer encoding to use (default: "cl100k_base") | |
--create-templates |
Create a templates directory with example templates | |
--version |
-v |
Show the version and exit |
--log-level |
Set the logging level (e.g., DEBUG, INFO, WARNING, ERROR, CRITICAL) | |
--interactive |
-i |
Activate interactive mode for file selection |
--syntax-map |
Pair custom file extensions with specific syntax highlighting (e.g., "inc:bash,customext:python,ext2:javascript") |
--filter
or -f
and --exclude
or -e
The --filter
and --exclude
options allow you to specify patterns for files or directories that should be included in or excluded from processing, respectively.
--filter "PATTERN1,PATTERN2,..."
--exclude "PATTERN1,PATTERN2,..."
or
-f "PATTERN1,PATTERN2,..."
-e "PATTERN1,PATTERN2,..."
*
) and directory indicators (**
).--case-sensitive
flag to change this behavior).--exclude
patterns take precedence over --filter
patterns.Include only Python files:
--filter "**.py"
Exclude all Markdown files:
--exclude "**.md"
Include specific file types in the src directory:
--filter "src/**.{js,ts}"
Exclude multiple file types and a specific directory:
--exclude "**.log,**.tmp,**/node_modules/**"
Include all files except those in 'test' directories:
--filter "**" --exclude "**/test/**"
Complex filtering (include JavaScript files, exclude minified and test files):
--filter "**.js" --exclude "**.min.js,**test**.js"
Include specific files across all directories:
--filter "**/config.json,**/README.md"
Exclude temporary files and directories:
--exclude "**/.cache/**,**/tmp/**,**.tmp"
Include source files but exclude build output:
--filter "src/**/*.{js,ts}" --exclude "**/dist/**,**/build/**"
Exclude version control and IDE-specific files:
--exclude "**/.git/**,**/.vscode/**,**/.idea/**"
**
wildcard matches any number of directories.*
matches any characters within a single directory or filename.--filter
and --exclude
for fine-grained control over which files are processed.--case-sensitive
flag if you need to distinguish between similarly named files with different cases.By using the --filter
and --exclude
options effectively and safely (with proper quoting), you can precisely control which files are processed in your project, ensuring both accuracy and security in your command execution.
Generate documentation for a Python library:
code2prompt --path /path/to/library --output library_docs.md --suppress-comments --line-number --filter "*.py"
Prepare a codebase summary for a code review, focusing on JavaScript and TypeScript files:
code2prompt --path /path/to/project --filter "*.js,*.ts" --exclude "node_modules/*,dist/*" --template code_review.j2 --output code_review.md
Create input for an AI model to suggest improvements, focusing on a specific directory:
code2prompt --path /path/to/src/components --suppress-comments --tokens --encoding cl100k_base --output ai_input.md
Analyze comment density across a multi-language project:
code2prompt --path /path/to/project --template comment_density.j2 --output comment_analysis.md --filter "*.py,*.js,*.java"
Generate a prompt for a specific set of files, adding line numbers:
code2prompt --path /path/to/important_file1.py --path /path/to/important_file2.js --line-number --output critical_files.md
Code2Prompt supports custom output formatting using Jinja2 templates. To use a custom template:
code2prompt --path /path/to/code --template /path/to/your/template.j2
Use the --create-templates
command to generate example templates:
code2prompt --create-templates
This creates a templates
directory with sample Jinja2 templates, including:
For full template documentation, see Documentation Templating.
Code2Prompt can be integrated with Simon Willison's llm CLI tool for enhanced code analysis or qllm, or for the Rust lovers hiramu-cli.
pip install code2prompt llm
Generate a code summary and analyze it with an LLM:
code2prompt --path /path/to/your/project | llm "Analyze this codebase and provide insights on its structure and potential improvements"
Process a specific file and get refactoring suggestions:
code2prompt --path /path/to/your/script.py | llm "Suggest refactoring improvements for this code"
For more advanced use cases, refer to the Integration with LLM CLI section in the full documentation.
You can integrate Code2Prompt into your GitHub Actions workflow. Here's an example:
name: Code Analysis
on: [push]
jobs:
analyze-code:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
pip install code2prompt llm
- name: Analyze codebase
run: |
code2prompt --path . | llm "Perform a comprehensive analysis of this codebase. Identify areas for improvement, potential bugs, and suggest optimizations." > analysis.md
- name: Upload analysis
uses: actions/upload-artifact@v2
with:
name: code-analysis
path: analysis.md
Tokens are the basic units of text that language models process. They can be words, parts of words, or even punctuation marks. Different tokenizer encodings split text into tokens in various ways. Code2Prompt supports multiple token types through its --encoding
option, with "cl100k_base" as the default. This encoding, used by models like GPT-3.5 and GPT-4, is adept at handling code and technical content. Other common encodings include "p50k_base" (used by earlier GPT-3 models) and "r50k_base" (used by models like CodeX).
To count tokens in your generated prompt, use the --tokens
flag:
code2prompt --path /your/project --tokens
For a specific encoding:
code2prompt --path /your/project --tokens --encoding p50k_base
Understanding token counts is crucial when working with AI models that have token limits, ensuring your prompts fit within the model's context window.
Code2Prompt now includes a powerful feature for estimating token prices across various AI providers and models. Use the --price
option in conjunction with --tokens
to display a comprehensive breakdown of estimated costs. This feature calculates prices based on both input and output tokens, with input tokens determined by your codebase and a default of 1000 output tokens (customizable via --output-tokens
). You can specify a particular provider or model, or view prices across all available options. This functionality helps developers make informed decisions about AI model usage and cost management. For example:
code2prompt --path /your/project --tokens --price --provider openai --model gpt-4
This command will analyze your project, count the tokens, and provide a detailed price estimation for OpenAI's GPT-4 model.
code2prompt now offers a powerful feature to analyze codebases and provide a summary of file extensions. Use the --analyze
option along with the -p
(path) option to get an overview of your project's file composition. For example:
code2prompt --analyze -p code2prompt
Result:
.j2: 6 files
.json: 1 file
.py: 33 files
.pyc: 56 files
Comma-separated list of extensions:
.j2,.json,.py,.pyc
This command will analyze the 'code2prompt' directory and display a summary of all file extensions found, including their counts. You can choose between two output formats:
To use the tree-like format, add the --format tree
option:
code2prompt --analyze -p code2prompt --format tree
Result:
βββ code2prompt
βββ utils
β βββ .py
β βββ __pycache__
β βββ .pyc
βββ .py
βββ core
β βββ .py
β βββ __pycache__
β βββ .pyc
βββ comment_stripper
β βββ .py
β βββ __pycache__
β βββ .pyc
βββ __pycache__
β ββ .pyc
βββ templates
β βββ .j2
βββ data
βββ .json
Comma-separated list of extensions:
.j2,.json,.py,.pyc
The analysis also generates a comma-separated list of file extensions, which can be easily copied and used with the --filter
option for more targeted code processing.
code2prompt
offers a powerful feature for dynamic variable extraction from templates, allowing for interactive and customizable prompt generation. Using the syntax {{input:variable_name}}
, you can easily define variables that will prompt users for input during execution.
This is particularly useful for creating flexible templates for various purposes, such as generating AI prompts for Chrome extensions. Here's an example:
# AI Prompt Generator for Chrome Extension
Generate a prompt for an AI to create a Chrome extension with the following specifications:
Extension Name: {{input:extension_name}}
Main Functionality: {{input:main_functionality}}
Target Audience: {{input:target_audience}}
## Prompt:
You are an experienced Chrome extension developer. Create a detailed plan for a Chrome extension named "{{input:extension_name}}" that {{input:main_functionality}}. This extension is designed for {{input:target_audience}}.
Your response should include:
1. A brief description of the extension's purpose and functionality
2. Key features (at least 3)
3. User interface design considerations
4. Potential challenges in development and how to overcome them
5. Security and privacy considerations
6. A basic code structure for the main components (manifest.json, background script, content script, etc.)
Ensure that your plan is detailed, technically sound, and tailored to the needs of {{input:target_audience}}.
Start from this codebase:
----
## The codebase:
<codebase>
When you run code2prompt
with this template, it will automatically detect the {{input:variable_name}}
patterns and prompt the user to provide values for each variable (extension_name, main_functionality, and target_audience). This allows for flexible and interactive prompt generation, making it easy to create customized AI prompts for various Chrome extension ideas.
For example, if a user inputs:
The tool will generate a tailored prompt for an AI to create a detailed plan for this specific Chrome extension. This feature is particularly useful for developers, product managers, or anyone looking to quickly generate customized AI prompts for various projects or ideas.
The code2prompt project now supports a powerful "include file" feature, enhancing template modularity and reusability.
This feature allows you to seamlessly incorporate external file content into your main template using the {% include %}
directive. For example, in the main analyze-code.j2
template, you can break down complex sections into smaller, manageable files:
# Elite Code Analyzer and Improvement Strategist 2.0
{% include 'sections/role_and_goal.j2' %}
{% include 'sections/core_competencies.j2' %}
## Task Breakdown
1. Initial Assessment
{% include 'tasks/initial_assessment.j2' %}
2. Multi-Dimensional Analysis (Utilize Tree of Thought)
{% include 'tasks/multi_dimensional_analysis.j2' %}
// ... other sections ...
This approach allows you to organize your template structure more efficiently, improving maintainability and allowing for easy updates to specific sections without modifying the entire template. The include feature supports both relative and absolute paths, making it flexible for various project structures. By leveraging this feature, you can significantly reduce code duplication, improve template management, and create a more modular and scalable structure for your code2prompt templates.
The interactive mode allows users to select files for processing in a user-friendly manner. This feature is particularly useful when dealing with large codebases or when you want to selectively include files without manually specifying each path.
To activate interactive mode, use the --interactive
or -i
option when running the code2prompt
command. Here's an example:
code2prompt --path /path/to/your/project --interactive
This mode enhances the usability of Code2Prompt, making it easier to manage file selections in complex projects.
Code2Prompt supports a .code2promptrc
configuration file in JSON format for setting default options. Place this file in your project or home directory.
Example .code2promptrc
:
{
"suppress_comments": true,
"line_number": true,
"encoding": "cl100k_base",
"filter": "*.py,*.js",
"exclude": "tests/*,docs/*"
}
Issue: Code2Prompt is not recognizing my .gitignore file.
Solution: Run Code2Prompt from the project root, or specify the .gitignore path with --gitignore
.
Issue: The generated output is too large for my AI model.
Solution: Use --tokens
to check the count, and refine --filter
or --exclude
options.
Issue: Some files are not being processed.
Solution: Check for binary files or exclusion patterns. Use --case-sensitive
if needed.
Contributions to Code2Prompt are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
Code2Prompt is released under the MIT License. See the LICENSE file for details.
β If you find Code2Prompt useful, please give us a star on GitHub! It helps us reach more developers and improve the tool. β
Made with β€οΈ by RaphaΓ«l MANSUY. Founder of Quantalogic. Creator of qllm.