code2prompt Documentation

A CLI tool to convert your codebase into a single LLM prompt with source tree, prompt templating, and token counting.

7,728 stars Rust Rust 134 files · ~117,698 tokens #ai#chatgpt#claude#cli#command-line#command-line-tool#gpt#llm
RAW Doc

Technical Documentation: mufeedvh/code2prompt

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)


[](https://code2prompt.dev)

Code2Prompt is a powerful context engineering tool designed to ingest codebases and format them for Large Language Models. Whether you are manually copying context for ChatGPT, building AI agents via Python, or running a MCP server, Code2Prompt streamlines the context preparation process.

⚡ Quick Install

Cargo

bash
cargo install code2prompt

To enable optional Wayland support (e.g., for clipboard integration on Wayland-based systems), use the wayland feature flag:

bash
cargo install --features wayland code2prompt

Homebrew

bash
brew install code2prompt

SDK with pip 🐍

bash
pip install code2prompt-rs

🚀 Quick Start

Once installed, generating a prompt from your codebase is as simple as pointing the tool to your directory.

Basic Usage: Generate a prompt from the current directory. Output goes to stdout by default; use -c to copy it to the clipboard.

sh
code2prompt .

Save to file:

sh
code2prompt path/to/project --output-file prompt.txt

🤖 Agent Skill

Teach your coding agent to install and use code2prompt for repository navigation
and scoped context gathering with the Skills CLI:

sh
npx skills add mufeedvh/code2prompt

The code2prompt skill helps agents reduce exploration
round trips: inspect a compact map of functions and classes using sem-core, then
read relevant source files and tests together. It includes a map template and
installation instructions for the optional entity-map feature, with a directory
map fallback for standard builds. The code2prompt CLI is installed separately.

The installer adds the skill folder and its template to your agent. It may clone
the repository temporarily to retrieve them; the rest of the repository is not
installed as part of the skill.

To install it globally for a specific agent, for example Codex:

sh
npx skills add mufeedvh/code2prompt --skill code2prompt --agent codex --global

🌐 Ecosystem

Code2Prompt is more than just a CLI tool. It is a complete ecosystem for codebase context.

🧱 Core Library 💻 CLI Tool 🐍 Python SDK 🤖 MCP Server
The internal, high-speed library responsible for secure file traversal, respecting .gitignore rules, and structuring Git metadata. Designed for humans, featuring both a minimal CLI and an interactive TUI. Generate formatted prompts, track token usage, and outputs the result to your clipboard or stdout. Provides fast Python bindings to the Rust Core. Ideal for AI Agents, automation scripts, or deep integration into RAG pipelines. Available on PyPI. Run Code2Prompt as a local service, enabling agentic applications to read your local codebase efficiently without bloating your context window.

📚 Documentation

Check our online documentation for detailed instructions

✨ Features

Code2Prompt transforms your entire codebase into a well-structured prompt for large language models. Key features include:

  • Terminal User Interface (TUI): Interactive terminal interface for configuring and generating prompts
  • Smart Filtering: Include/exclude files using glob patterns and respect .gitignore rules
  • Flexible Templating: Customize prompts with Handlebars templates for different use cases
  • Automatic Code Processing: Convert codebases of any size into readable, formatted prompts
  • Token Estimates: Estimate prompt size using parallel per-file token counts and estimated template overhead, including optional line numbers. The full rendered prompt is not re-tokenized, and the estimate excludes the JSON output envelope.
  • Smart File Reading: Simplify reading various file formats for LLMs (CSV, Notebooks, JSONL, etc.)
  • Git Integration: Include diffs, logs, and branch comparisons in your prompts
  • Blazing Fast: Built in Rust for high performance and low resource usage

Stop manually copying files and formatting code for LLMs. Code2Prompt handles the tedious work so you can focus on getting insights and solutions from AI models.

Alternative Installation

Refer to the documentation for detailed installation instructions.

Binary releases

Download the latest binary for your OS from Releases.

Source build

Requires:

sh
git clone https://github.com/mufeedvh/code2prompt.git
cd code2prompt/
cargo install --path crates/code2prompt

⭐ Star Gazing

📜 License

Licensed under the MIT License, see LICENSE for more information.

Liked the project?

If you liked the project and found it useful, please give it a :star: !

👥 Contribution

Ways to contribute:

  • Suggest a feature
  • Report a bug
  • Fix something and open a pull request
  • Help me document the code
  • Spread the word

Overview (`website/README.md`)

Starlight Starter Kit: Basics

text
yarn create astro@latest -- --template starlight




🧑‍🚀 Seasoned astronaut? Delete this file. Have fun!

🚀 Project Structure

Inside of your Astro + Starlight project, you'll see the following folders and files:

text
.
├── public/
├── src/
│   ├── assets/
│   ├── content/
│   │   ├── docs/
│   └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json

Starlight looks for .md or .mdx files in the src/content/docs/ directory. Each file is exposed as a route based on its file name.

Images can be added to src/assets/ and embedded in Markdown with a relative link.

Static assets, like favicons, can be placed in the public/ directory.

🧞 Commands

All commands are run from the root of the project, from a terminal:

Command Action
yarn install Installs dependencies
yarn dev Starts local dev server at localhost:4321
yarn build Build your production site to ./dist/
yarn preview Preview your build locally, before deploying
yarn astro ... Run CLI commands like astro add, astro check
yarn astro -- --help Get help using the Astro CLI

👀 Want to learn more?

Check out Starlight’s docs, read the Astro documentation, or jump into the Astro Discord server.


Overview (`crates/code2prompt-python/README.md`)

code2prompt Python bindings

Native Python bindings for the stateful
code2prompt_core API.

Installation

bash
pip install code2prompt_rs

Python 3.11 or newer is supported.

Rust PathBuf values accept Python strings or os.PathLike objects and are exposed as
pathlib.Path objects.

Usage

Create a core configuration, move it into a session, and operate on that session just as you
would from Rust:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    ".",
    include_patterns=["**/*.py", "**/*.rs"],
    exclude_patterns=["**/tests/**"],
    line_numbers=True,
    deselected=True,
)
session = Code2PromptSession(config)

session.select_file("src/main.rs")
session.select_file("src/lib.rs")

result = session.generate_prompt()
print(result.prompt)
print(result.token_count)
print(result.files)

result.token_count estimates the prompt size from cached per-file token counts
(including optional line numbers) and estimated template overhead. The full rendered
prompt is not re-tokenized, and the JSON output envelope is not counted.

Selection methods mutate and return the same session, so calls may also be chained:

python
session.select_file("src/main.rs").deselect_file("src/generated.rs")

Configuration

Configuration values use native enum classes rather than string aliases:

python
from code2prompt_rs import (
    Code2PromptConfig,
    FileProcessorsConfig,
    FileSortMethod,
    IpynbProcessorConfig,
    OutputFormat,
    TokenFormat,
    TokenizerType,
)

config = Code2PromptConfig(
    ".",
    absolute_path=False,
    no_codeblock=False,
    output_format=OutputFormat.Markdown,
    sort_method=FileSortMethod.NameAsc,
    encoding=TokenizerType.Cl100kBase,
    token_format=TokenFormat.Raw,
    processors=FileProcessorsConfig(
        ipynb=IpynbProcessorConfig(
            max_code_cells=5,
            include_outputs=True,
            include_markdown=True,
        )
    ),
)

Code2PromptConfig exposes the user-facing fields from core 4.3. The optional Rust
entity-map feature is not included in the Python wheels.

Session API

Code2PromptSession exposes the core operational methods:

  • Pattern updates: add_include_pattern, add_exclude_pattern
  • Selection: select_file, deselect_file, toggle_file_selection,
    is_file_selected, get_selected_files, clear_user_actions, has_user_actions,
    set_deselected
  • Loading: load_codebase, load_git_diff, load_git_diff_between_branches,
    load_git_log_between_branches
  • Results: generate_prompt, raw_analysis, contextual_analysis

generate_prompt() returns a typed RenderedPrompt. Loaded codebase and Git values are
available from the typed session.data snapshot. Analysis calls return CodebaseAnalysis,
whose raw_files(), by_extension(), and token_map(options) methods return typed models.

Local development

bash
uv sync
uv run pytest

uv sync creates .venv, installs the development dependencies, and builds the native
extension in editable mode. The lockfile is committed for reproducible development environments.

To build a release wheel locally:

bash
uv run maturin build --release

Overview (`website/src/assets/examples/node_app/node_app/README.md`)

Simple Node.js app to process JSON data.
Feature idea: Add a filter function to sort users by age.


Website Src Content Docs Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Why I Developed Code2Prompt"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • AI
  • Agent
    excerpt: "The story behind code2prompt: my Open-Source quest to tackle context challenges in LLM workflows"
    authors:
  • ODAncona
    cover:
    alt: "An illustration of code2prompt streamlining code context for AI agents."
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

Introduction

I've always been fascinated by how Large Language Models (LLMs) transform coding workflows—generating tests, docstrings, or even shipping entire features in minutes. But as I pushed these models further, a few critical pain points kept surfacing:

Planning Difficulties High Token Costs Hallucinations
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

That's why I started contributing to code2prompt, a Rust-based tool to help feed just the proper context into LLMs.

In this post, I'll share my journey and explain why I'm convinced that code2prompt is relevant today and integrates so well and why it's become my go-to solution for better, faster AI coding workflows.

My First Steps with LLMs 👣

I started experimenting with LLMs on OpenAI Playground with text-davinci-003 when it gained traction in November 2023. Language models enabled a new revolution. It felt like having a brilliant new assistant who would crank out unit tests and docstrings almost on command. I enjoyed pushing the models to their limits—testing everything from small talk and ethical dilemmas to jailbreaks and complex coding tasks. However, as I took on more extensive projects, I quickly realized that the models had glaring limitations. At first, I could only fit a few hundred lines of code into the context window, and even then, the models often struggled to understand the code's purpose or structure. That's why I quickly noticed that the importance of context was paramount. The more concise my instructions were and the better the context, the better the results.

Model Evolution 🏗️

The models could produce impressive results but often struggled with larger codebases or complex tasks. I found myself spending more time crafting prompts than actually coding. At the same time, the models kept improving with the release of new versions. They increased reasoning abilities and context size, offering new perspectives and possibilities. I could fit almost two thousand lines of code into the context window then, and the results improved. I could write entire features in a matter of a few iterations, and I was amazed by how quickly I could get results. I was convinced that LLMs were the future of coding, and I wanted to be part of that revolution. I firmly believe that AI won't replace us yet. But will assist us in the form of assistants where humans are the experts still in control.

My First Projects with LLMs🚀

I started to write a ROS pathfinding module for a robotic competition, generate features for a clean architecture Flutter cross-platform app, and made a small web app to keep track of my expenses in Next.js. The fact that I built this small app in one evening, in a framework I'd never touched before, was a game-changer moment for me; LLMs weren't just tools but multipliers. I developed `bboxconverter', a package to convert bounding boxes, and the list goes on. LLMs can help you learn new technologies and frameworks quickly; that's awesome.

A New Paradigm: Software 3.0 💡

I dove deeper into LLMs and started to build agents and scaffold around them. I reproduced the famous paper RestGPT. The idea is excellent: give LLMs the ability to call some REST API with an OpenAPI specification, such as Spotify or TMDB. These capabilities introduce a new software programming paradigm, which I like to call Software 3.0.

Software 1.0 Software 2.0 Software 3.0
Rules-based Data-driven Agentic

The same idea propelled the MCP protocol, which allows LLMs to call tools and resources directly in a seamless way because, by design, the tool needs a description to be called by the LLM in the opposite of REST Apis that doesn't necessarily require OpenAPI specification.

The Limitations of LLMs 🧩

Hallucinations 🌀

While reproducing the famous paper RESTGPT, I noticed some serious limitations of LLMs. The paper's authors encountered the same issues I had: LLMs were hallucinating. They generate code that is not implemented, inventing arguments and simply following the instructions to the letter without leveraging common sense. E.g., in the original RestGPT codebase, the authors asked in the caller prompt.

"to not get clever and make up steps that don't exist in the plan."

I found this statement funny and very interesting because it was the first time I encountered someone instructing LLMs not to hallucinate.

Limited Context-Size 📏

Another limitation was the context size; LLMs perform well in finding the needle in the haystack but struggle to make sense of it. When you give too much context to the language models, they tend to get lost in the details and lose sight of the big picture, which is annoying and requires constant steering. The way I like to think about it is in a similar way as the curse of dimensionality. Replace the word "dimension" or "feature" by "context", and you get the idea.

The more context you give to the LLM, the more difficult it is to find the correct answer. I came up with a nice sentence to summarize this idea:

Provide as little context as possible but as much as necessary

This is heavily inspired by the famous quote of Alain Berset, a Swiss politician 🇨🇭 who said during the COVID-19 lockdown:

"Nous souhaitons agir aussi vite que possible, mais aussi lentement que nécessaire"

This represents the idea of compromise and applies to the context size of LLMs!

Searching for a Better Way: code2prompt 🔨

Therefore, I needed a way to load, filter, and organize my code context quickly by provisioning the least amount possible of context with the best quality possible. I tried manually copying files or snippets into prompts, but that became unwieldy and error-prone. I knew automating the tedious process of forging the context to ask better prompts would be helpful. Then, one day, I typed "code2prompt" into Google, hoping to find a tool that piped my code directly into prompts.

Lo and behold, I discovered a Rust-based project by Mufeed named code2prompt, sporting about 200 stars on GitHub. It was still basic at the time: a simple CLI tool with basic limited filter capacity and templates. I saw enormous potential and jumped in straight to contribute, implementing glob pattern matching, among other features, and soon became the main contributor.

Vision & Integrations 🔮

Today, there are several ways to provide context to LLMs. Generating from the larger context, using Retrieval-Augmented Generation (RAG), compressing the code, or even using a combination of these methods. Context forging is a hot topic that will evolve rapidly in the coming months. However, my approach is KISS: Keep It Simple, Stupid. The best way to provide context to LLMs is to use the simplest and most efficient way possible. You forge precisely the context you need; it's deterministic, contrary to RAG.

That's why I decided to push code2prompt further as a simple tool that can be used in any workflow. I wanted to make it easy to use, easy to integrate, and easy to extend. That's why I added new ways to interact with the tool.

  • Core: The core of code2prompt is a Rust library that provides the basic functionality to forge context from your codebase. It includes a simple API to load, filter, and organize your code context.
  • CLI: The command line interface is the simplest way to use code2prompt. You can forge context from your codebase and pipe it directly into your prompts.
  • Python API: The Python API is a simple wrapper around the CLI that allows you to use code2prompt in your Python scripts and agents. You can forge context from your codebase and pipe it directly into your prompts.
  • MCP: The code2prompt MCP server allows LLMs to use code2prompt as a tool, thus making themselves capable of forging the context.

The vision is described further in the vision page in the doc.

Integration with agents 👤

I believe that future agents will need to have a way to ingest context, and code2prompt is the simple and efficient way to do it for textual repositories like codebase, documentation, or notes. A propical place to use code2prompt would be in a codebase with meaningful naming conventions. For example, in clean architecture, there is a clear separation of concerns and layers. The relevant context usually resides in different files and folders but share the same name. This is a perfect use case for code2prompt, where you can use the glob pattern to grab the relevant files.

Glob Pattern-first: Precisely select or exclude files with minimal fuss.

Furthermore, the core library is designed as a stateful context manager, allowing you to add or remove files as your conversation with the LLM evolves. This is particularly useful when providing context for a specific task or goal. You can easily add or remove files from the context without re-running the process.

Stateful Context: Add or remove files as your conversation with the LLM evolves.

Those capabilities make code2prompt a perfect fit for agent-based workflows. The MCP server allows seamless integration with popular AI agent frameworks like Aider, Goose, or Cline. Let them handle complex goals while code2prompt delivers the perfect code context.

Why Code2prompt Matters ✊

As LLMs evolve and context windows expand, it might seem like purely brute-forcing entire repositories into prompts is enough. However, token costs and prompt coherence remain significant roadblocks for small companies and developers. Focusing on just the code that matters, code2prompt keeps your LLM usage efficient, cost-effective, and less prone to hallucination.

In short:

  • Reduce hallucinations by providing the right amount of context
  • Reduce token-usage costs by manually curating the proper context needed
  • Improve LLM performance by giving the right amount of context
  • Integrates the agentic stack as a context feeder for text repositories

You can join It's Open Source! 🌐

Every new contributor is welcome! Come aboard if you're interested in Rust, forging innovative AI tools, or simply want a better workflow for your code-based prompts.

Thanks for reading, and I hope my story inspired you to check out code2prompt. It's been an incredible journey, and it's just getting started!

Olivier D'Ancona


Website Src Content Docs Docs Vision (`website/src/content/docs/docs/vision.mdx`)


title: Code2Prompt's Vision

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` was created to help developers and AI agents interact with codebases more effectively.

The Problem 🚩

Large Language Models (LLMs) have revolutionized the way we interact with code. However, they still face significant challenges with code generation:

  • Planning and Reasoning: LLMs lacks the ability to plan and reason, which is crucial for tasks like code generation, refactoring, and debugging. They often struggle to get the big picture and are short sighted.
  • Context size: LLMs have a limited context window, which restricts their ability to analyze and understand large codebases.
  • Hallucination: LLMs can generate code that appears correct but is actually incorrect or nonsensical. This phenomenon, known as hallucination, occurs when the model lacks sufficient context or understanding of the codebase.

This is where code2prompt comes in.

The Solution ✅

We believe that planning and reasoning can be achieved by human or AI agents with scaffolding techniques. These agents needs to gather a high quality context of the codebase that is filtered, structured, and formatted for the task at hand.

The thumb rule would be:

This is practically difficult to achieve, especially for large codebases. However, code2prompt is a simple tool that can help developers and AI agents ingest codebase more effectively.

It automates the process of traversing a codebase, filtering files, and formatting them into structured prompts that LLMs can understand. By doing so, it helps to mitigate the challenges of planning, reasoning, and hallucination.

You can understand how code2prompt is designed to tackles these challenges in the following section.

Architecture ⛩️

code2prompt is designed in a modular way, allowing for easy integration into various workflows. It can be used as a core library, a command line interface (CLI), a software development kit (SDK), or even as a Model Context Protocol (MCP) server.

Core

code2prompt is a code ingestion tool that streamline the process of creating LLM prompts for code analysis, generation, and other tasks. It works by traversing directories, building a tree structure, and gathering informations about each file. The core library can easily be integrated into other applications.

CLI

code2prompt command line interface (CLI) was designed for humans to generate prompts directly from your codebase. The generated prompt is automatically copied to your clipboard and can also be saved to an output file. Furthermore, you can customize the prompt generation using Handlebars templates. Check out the provided prompts in the doc !

SDK

code2prompt software development kit (SDK) offers python binding to the core library. This is perfect for AI agents or automation scripts that want to interact with codebase seamlessly. The SDK is hosted on Pypi and can be installed via pip.

MCP

code2prompt is also available as a Model Context Protocol (MCP) server, which allows you to run it as a local service. This enables LLMs on steroids by providing them a tool to automatically gather a well-structured context of your codebase.


Website Src Content Docs Docs Welcome (`website/src/content/docs/docs/welcome.mdx`)


title: Code2Prompt Documentation
template: splash
hero:
tagline: Transform Your Code into AI-Optimized Prompts in Seconds
image:
file: ../../../assets/logo_dark_v0.0.1.svg
actions:
- text: Get Started 🚀
link: /docs/tutorials/getting_started
- text: Installation 📥
link: /docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Quick Start

code2prompt is a powerful code ingestion tool designed to generate prompts for code analysis, generation, and other tasks. It works by traversing directories, building a tree structure, and gathering informations about each file.

It simplifies the process of combining and formatting code, making it easy to analyze, document, or refactor code using LLMs

You can use code2prompt the following ways:

Core library blazingly fast for code ingestion Command Line Interface specially designed for humans Software Development Kit for AI agents and automation scripts Model Context Protocol server for LLMs on steroids ---

Key Features

  • Generate LLM Prompts: Quickly convert entire codebases into structured LLM prompts.
  • Glob Pattern Filtering: Include or exclude specific files and directories using glob patterns.
  • Customizable Templates: Tailor prompt generation with Handlebars templates.
  • Token Counting: Analyze token usage and optimize for LLMs with varying context windows.
  • Git Integration: Include Git diffs and commit messages in prompts for code reviews.
  • Respects .gitignore: Automatically ignores files listed in .gitignore to streamline prompt generation.

Why `code2prompt`?

Instead of just blindly concatenating files together, code2prompt is built to curate the perfect context window for your LLM, saving you money and preventing model hallucination.

  1. Smart Data Extraction: Stop blowing up your token limits on raw data. When code2prompt encounters a .csv, .tsv, .jsonl, or Jupyter Notebook (.ipynb), it intelligently extracts only the structural schema and sample rows/cells, giving the LLM the context it needs without the bloat.

  2. Precision Context Filtering: It natively respects your .gitignore and uses an advanced glob pattern engine (--include and --exclude) so you can isolate exactly which modules you want to send.

  3. Zero-Overhead Token Math: It uses native Tiktoken encodings (like o200k and cl100k) to calculate exact token counts locally before you send a massive payload to an API.

  4. Template-Driven Workflows: Use powerful Handlebars templates to automatically inject your project's directory tree, git diffs, and source code into specialized, repeatable prompts.

  5. Built for Any Environment: Navigate visually with the built-in TUI, automate tasks via the CLI, or give LLM agents direct repository access using the MCP server.


Example Use Cases

  • One-Shot PR & Commit Generation: Leverage built-in Git integration to compare branch diffs and let your LLM write highly detailed, context-aware PR descriptions automatically.

  • CTF & Security Analysis: Use built-in templates explicitly designed for Web, Cryptography, or Binary Exploitation CTF solving, handing the LLM the exact file constraints it needs to spot vulnerabilities.

  • Architectural Refactoring: Feed a specific module—along with the visual directory tree—into a cleanup template to get refactoring suggestions that respect your project's overall structure.

  • Instant Onboarding & Documentation: Generate a full repository token map and structural overview to quickly understand massive new codebases, or auto-generate robust README.md files.


Website Src Content Docs De Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/de/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Warum ich Code2Prompt entwickelt habe"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • KI
  • Agent
    excerpt: "Die Geschichte hinter code2prompt: meine Open-Source-Suche nach Lösungen für Kontext-Herausforderungen in LLM-Workflows"
    authors:
  • ODAncona
    cover:
    alt: "Eine Illustration von code2prompt, das den Code-Kontext für KI-Agenten optimiert."
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

Einführung

Ich bin seit jeher fasziniert davon, wie große Sprachmodelle (LLMs) die Codierungs-Workflows verändern - sei es durch die Generierung von Tests, Docstrings oder sogar ganzen Features in Minuten. Aber als ich diese Modelle weiterentwickelte, traten einige kritische Schmerzpunkte auf:

Planungsprobleme Hohe Token-Kosten Halluzinationen
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

Deshalb begann ich, mich mit code2prompt zu beschäftigen, einem Rust-basierten Tool, das dabei hilft, den richtigen Kontext für LLMs bereitzustellen.

In diesem Beitrag teile ich meine Reise und erkläre, warum ich davon überzeugt bin, dass code2prompt heute relevant ist und sich so gut integrieren lässt, und warum es zu meiner bevorzugten Lösung für bessere, schnellere KI-Codierungs-Workflows geworden ist.

Meine ersten Schritte mit LLMs 👣

Ich begann im November 2023 mit Experimenten mit LLMs auf OpenAI Playground mit text-davinci-003. Die Sprachmodelle ermöglichten eine neue Revolution. Es fühlte sich an, als hätte ich einen brillanten neuen Assistenten, der auf Kommando Unit-Tests und Docstrings erstellen konnte. Ich genoss es, die Modelle an ihre Grenzen zu bringen - von Small Talk und ethischen Dilemmata bis hin zu Jailbreaks und komplexen Codierungsaufgaben. Als ich jedoch an umfangreicheren Projekten arbeitete, erkannte ich schnell, dass die Modelle offensichtliche Einschränkungen aufwiesen. Zunächst konnte ich nur wenige hundert Zeilen Code in das Kontextfenster einfügen, und selbst dann hatten die Modelle oft Schwierigkeiten, den Zweck oder die Struktur des Codes zu verstehen. Deshalb erkannte ich schnell, dass der Kontext von größter Bedeutung war. Je präziser meine Anweisungen waren und je besser der Kontext, desto besser die Ergebnisse.

Modell-Evolution 🏗️

Die Modelle konnten beeindruckende Ergebnisse liefern, aber oft hatten sie Schwierigkeiten mit größeren Codebasen oder komplexen Aufgaben. Ich fand mich immer wieder dabei, mehr Zeit für die Erstellung von Prompts aufzuwenden als tatsächlich zu codieren. Gleichzeitig verbesserten sich die Modelle mit der Veröffentlichung neuer Versionen. Sie erhöhten ihre Denkfähigkeiten und Kontextgröße, boten neue Perspektiven und Möglichkeiten. Ich konnte fast zweitausend Zeilen Code in das Kontextfenster einfügen, und die Ergebnisse verbesserten sich. Ich konnte ganze Features in wenigen Iterationen schreiben, und ich war beeindruckt davon, wie schnell ich Ergebnisse erzielen konnte. Ich war überzeugt, dass LLMs die Zukunft des Codierens waren, und ich wollte Teil dieser Revolution sein. Ich bin fest davon überzeugt, dass KI uns nicht ersetzen wird, sondern uns als Assistenten unterstützen wird, während Menschen immer noch die Experten sind.

Meine ersten Projekte mit LLMs 🚀

Ich begann, ein ROS-Pathfinding-Modul für einen Roboter-Wettbewerb zu schreiben, generierte Features für eine saubere Architektur-Flutter-Cross-Plattform-App und entwickelte eine kleine Web-App, um meine Ausgaben in Next.js zu verfolgen. Die Tatsache, dass ich diese kleine App an einem Abend in einem Framework, das ich noch nie zuvor verwendet hatte, erstellte, war ein gamechanger für mich; LLMs waren nicht nur Werkzeuge, sondern Multiplikatoren. Ich entwickelte bboxconverter, ein Paket zum Konvertieren von Bounding-Boxes, und vieles mehr. LLMs können Ihnen helfen, neue Technologien und Frameworks schnell zu erlernen; das ist großartig.

Ein neues Paradigma: Software 3.0 💡

Ich tauchte tiefer in LLMs ein und begann, Agenten und Scaffoldings darum herum zu bauen. Ich reproduzierte das berühmte Paper RestGPT. Die Idee ist großartig: Geben Sie LLMs die Möglichkeit, einige REST-APIs mit einer OpenAPI-Spezifikation aufzurufen, wie z.B. Spotify oder TMDB. Diese Fähigkeiten führen ein neues Software-Programmierparadigma ein, das ich Software 3.0 nenne.

Software 1.0 Software 2.0 Software 3.0
Regelbasiert Datengesteuert Agentisch

Die gleiche Idee trieb das MCP-Protokoll voran, das es LLMs ermöglicht, Tools und Ressourcen direkt auf eine nahtlose Weise aufzurufen, da das Tool per Design eine Beschreibung benötigt, um vom LLM aufgerufen zu werden, im Gegensatz zu REST-APIs, die nicht unbedingt eine OpenAPI-Spezifikation erfordern.

Die Einschränkungen von LLMs 🧩

Halluzinationen 🌀

Während ich das berühmte Paper RESTGPT reproduzierte, bemerkte ich einige schwerwiegende Einschränkungen von LLMs. Die Autoren des Papiers begegneten den gleichen Problemen wie ich: LLMs halluzinierten. Sie generierten Code, der nicht implementiert war, erfanden Argumente und folgten einfach den Anweisungen buchstäblich, ohne gesunden Menschenverstand zu verwenden. Zum Beispiel fragten die Autoren in dem Caller-Prompt.

"Nicht clever werden und Schritte erfinden, die nicht im Plan existieren."

Ich fand diese Aussage lustig und sehr interessant, weil es das erste Mal war, dass ich jemanden sah, der LLMs anwies, nicht zu halluzinieren.

Begrenzte Kontextgröße 📏

Eine weitere Einschränkung war die Kontextgröße; LLMs funktionieren gut beim Finden der Nadel im Heuhaufen, aber haben Schwierigkeiten, einen Sinn daraus zu machen. Wenn Sie den Sprachmodellen zu viel Kontext geben, tendieren sie dazu, sich in den Details zu verlieren und die Übersicht zu verlieren, was ärgerlich ist und ständige Steuerung erfordert. Die Art und Weise, wie ich darüber nachdenke, ist ähnlich wie bei dem Fluch der Dimensionalität. Ersetzen Sie das Wort "Dimension" oder "Feature" durch "Kontext", und Sie erhalten die Idee.

Je mehr Kontext Sie dem LLM geben, desto schwieriger ist es, die richtige Antwort zu finden. Ich kam auf einen schönen Satz, um diese Idee zusammenzufassen:

Stellen Sie so wenig Kontext wie möglich, aber so viel wie nötig bereit.

Dies ist stark inspiriert von dem berühmten Zitat von Alain Berset, einem Schweizer Politiker 🇨🇭, der während des COVID-19-Lockdowns sagte:

"Wir möchten so schnell wie möglich handeln, aber auch so langsam wie nötig."

Dies repräsentiert die Idee des Kompromisses und gilt für die Kontextgröße von LLMs!

Die Suche nach einem besseren Weg: code2prompt 🔨

Deshalb benötigte ich eine Möglichkeit, meinen Code-Kontext schnell zu laden, zu filtern und zu organisieren, indem ich die kleinstmögliche Menge an Kontext mit der besten Qualität bereitstellte. Ich versuchte, Dateien oder Code-Snippets manuell in Prompts zu kopieren, aber das wurde unhandlich und fehleranfällig. Ich wusste, dass die Automatisierung des mühsamen Prozesses der Kontextgestaltung, um bessere Prompts zu stellen, hilfreich sein würde. Dann gab ich eines Tages "code2prompt" in Google ein, in der Hoffnung, ein Tool zu finden, das meinen Code direkt in Prompts einspeist.

Und tatsächlich entdeckte ich ein Rust-basiertes Projekt von Mufeed namens code2prompt, das etwa 200 Sterne auf GitHub hatte. Es war damals noch einfach: ein einfaches CLI-Tool mit grundlegender Filterkapazität und Vorlagen. Ich sah enormes Potenzial und sprang direkt ein, um beizutragen, implementierte unter anderem die glob-Musterübereinstimmung und wurde bald zum Hauptmitarbeiter.

Vision & Integrationen 🔮

Heute gibt es mehrere Möglichkeiten, Kontext für LLMs bereitzustellen. Generierung aus dem größeren Kontext, Verwendung von Retrieval-Augmented Generation (RAG), Komprimierung des Codes oder sogar Verwendung einer Kombination dieser Methoden. Kontextgestaltung ist ein heißes Thema, das sich in den kommenden Monaten schnell entwickeln wird. Mein Ansatz ist jedoch KISS: Keep It Simple, Stupid. Die beste Möglichkeit, Kontext für LLMs bereitzustellen, besteht darin, die einfachste und effizienteste Methode zu verwenden. Sie gestalten genau den Kontext, den Sie benötigen; es ist deterministisch, im Gegensatz zu RAG.

Deshalb beschloss ich, code2prompt weiterzuentwickeln, als ein einfaches Tool, das in jedem Workflow verwendet werden kann. Ich wollte es einfach zu bedienen, einfach zu integrieren und einfach zu erweitern machen. Deshalb fügte ich neue Möglichkeiten hinzu, mit dem Tool zu interagieren.

  • Core: Der Core von code2prompt ist eine Rust-Bibliothek, die die grundlegende Funktionalität bietet, um Kontext aus Ihrem Code-Bestand zu gestalten. Sie enthält eine einfache API, um Ihren Code-Kontext zu laden, zu filtern und zu organisieren.
  • CLI: Die Kommandozeilen-Schnittstelle ist die einfachste Möglichkeit, code2prompt zu verwenden. Sie können Kontext aus Ihrem Code-Bestand gestalten und direkt in Ihre Prompts einspeisen.
  • Python-API: Die Python-API ist eine einfache Wrapper-Funktion um die CLI, die es Ihnen ermöglicht, code2prompt in Ihren Python-Skripten und Agenten zu verwenden. Sie können Kontext aus Ihrem Code-Bestand gestalten und direkt in Ihre Prompts einspeisen.
  • MCP: Der code2prompt-MCP-Server ermöglicht es LLMs, code2prompt als Tool zu verwenden, und macht sie dadurch in der Lage, Kontext zu gestalten.

Die Vision wird auf der Vision-Seite im Detail beschrieben.

Integration mit Agenten 👤

Ich bin davon überzeugt, dass zukünftige Agenten eine Möglichkeit benötigen, Kontext zu verdauen, und code2prompt ist die einfache und effiziente Möglichkeit, dies für Text-Repositorys wie Code-Bestand, Dokumentation oder Notizen zu tun. Ein typischer Ort, an dem code2prompt verwendet werden kann, ist in einem Code-Bestand mit sinnvollen Benennungskonventionen. Zum Beispiel gibt es in einer sauberen Architektur eine klare Trennung von Belangen und Schichten. Der relevante Kontext befindet sich normalerweise in verschiedenen Dateien und Ordnern, teilt aber denselben Namen. Dies ist ein perfektes Anwendungsbeispiel für code2prompt, bei dem Sie die glob-Musterübereinstimmung verwenden können, um die relevanten Dateien zu erfassen.

Glob-Muster zuerst: Wählen Sie Dateien präzise aus oder schließen Sie sie aus mit minimalem Aufwand.

Darüber hinaus ist die Core-Bibliothek als zustandsbehafteter Kontext-Manager konzipiert, der es Ihnen ermöglicht, Dateien hinzuzufügen oder zu entfernen, während Ihre Unterhaltung mit dem LLM fortschreitet. Dies ist besonders nützlich, wenn Sie Kontext für eine bestimmte Aufgabe oder ein bestimmtes Ziel bereitstellen. Sie können Dateien leicht hinzufügen oder entfernen, ohne den Prozess neu zu starten.

Zustandsbehafteter Kontext: Fügen Sie Dateien hinzu oder entfernen Sie sie, während Ihre Unterhaltung mit dem LLM fortschreitet.

Diese Fähigkeiten machen code2prompt zu einem perfekten Fit für agentenbasierte Workflows. Der MCP-Server ermöglicht eine nahtlose Integration mit beliebten KI-Agenten-Frameworks wie Aider, Goose oder Cline. Lassen Sie sie komplexe Ziele bearbeiten, während code2prompt den perfekten Code-Kontext liefert.

Warum Code2prompt wichtig ist ✊

Wenn LLMs sich weiterentwickeln und Kontextfenster expandieren, könnte es scheinen, als ob das bloße Brute-Forcen ganzer Repositorys in Prompts ausreicht. Allerdings bleiben Token-Kosten und Prompt-Kohärenz erhebliche Hindernisse für kleine Unternehmen und Entwickler. Indem Sie sich auf den relevanten Code konzentrieren, hält code2prompt Ihre LLM-Nutzung effizient, kosteneffektiv und weniger anfällig für Halluzinationen.

In Kürze:

  • Reduzieren Sie Halluzinationen, indem Sie den richtigen Kontext bereitstellen
  • Reduzieren Sie Token-Verbrauchs-Kosten, indem Sie den richtigen Kontext manuell kuratieren
  • Verbessern Sie die LLM-Leistung, indem Sie den richtigen Kontext bereitstellen
  • Integriert die agentische Stack als Kontext-Feeder für Text-Repositorys

Sie können sich anschließen! 🌐

Jeder neue Mitwirkende ist willkommen! Kommen Sie an Bord, wenn Sie an Rust, der Gestaltung innovativer KI-Tools oder einfach nur an einem besseren Workflow für Ihre Code-basierten Prompts interessiert sind.

Vielen Dank für das Lesen, und ich hoffe, meine Geschichte hat Sie inspiriert, code2prompt zu überprüfen. Es war eine unglaubliche Reise, und sie fängt gerade erst an!

Olivier D'Ancona

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Vision (`website/src/content/docs/de/docs/vision.mdx`)


title: Die Vision von Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` wurde entwickelt, um Entwicklern und KI-Agenten eine effektivere Interaktion mit Codebasen zu ermöglichen.

Das Problem 🚩

Große Sprachmodelle (LLMs) haben die Art und Weise, wie wir mit Code interagieren, revolutioniert. Sie stehen jedoch immer noch vor erheblichen Herausforderungen bei der Codegenerierung:

  • Planung und Argumentation: LLMs fehlt die Fähigkeit, zu planen und zu argumentieren, was für Aufgaben wie Codegenerierung, Refaktorisierung und Debugging entscheidend ist. Sie haben oft Schwierigkeiten, das große Ganze zu überblicken und sind kurzsichtig.
  • Kontextgröße: LLMs haben ein begrenztes Kontextfenster, das ihre Fähigkeit, große Codebasen zu analysieren und zu verstehen, einschränkt.
  • Halluzination: LLMs können Code generieren, der korrekt erscheint, aber tatsächlich falsch oder unsinnig ist. Dieses Phänomen, bekannt als Halluzination, tritt auf, wenn das Modell nicht genügend Kontext oder Verständnis der Codebasis hat.

Hier kommt code2prompt ins Spiel.

Die Lösung ✅

Wir glauben, dass Planung und Argumentation durch menschliche oder KI-Agenten mit Gerüsttechniken erreicht werden können. Diese Agenten müssen einen hochwertigen Kontext der Codebasis sammeln, der für die jeweilige Aufgabe gefiltert, strukturiert und formatiert ist.

Die Faustregel lautet:

Dies ist praktisch schwierig zu erreichen, insbesondere bei großen Codebasen. code2prompt ist jedoch ein einfaches Tool, das Entwicklern und KI-Agenten hilft, Codebasen effektiver zu verdauen.

Es automatisiert den Prozess des Durchquerens einer Codebasis, Filterns von Dateien und Formatierens in strukturierte Prompts, die LLMs verstehen können. Dadurch hilft es, die Herausforderungen der Planung, Argumentation und Halluzination zu mildern.

Sie können verstehen, wie code2prompt diese Herausforderungen in folgendem Abschnitt angeht.

Architektur ⛩️

code2prompt ist modular konzipiert, um eine einfache Integration in verschiedene Workflows zu ermöglichen. Es kann als Core-Bibliothek, Kommandozeilen-Interface (CLI), Software-Entwicklungskit (SDK) oder sogar als Model Context Protocol (MCP)-Server verwendet werden.

Core

code2prompt ist ein Code-Ingestion-Tool, das den Prozess der Erstellung von LLM-Prompts für Codeanalyse, -generierung und andere Aufgaben optimiert. Es funktioniert, indem es Verzeichnisse durchquert, eine Baumstruktur aufbaut und Informationen über jede Datei sammelt. Die Core-Bibliothek kann leicht in andere Anwendungen integriert werden.

CLI

Das Kommandozeilen-Interface (CLI) von code2prompt wurde für Menschen entwickelt, um Prompts direkt aus Ihrer Codebasis zu generieren. Der generierte Prompt wird automatisch in die Zwischenablage kopiert und kann auch in eine Ausgabedatei gespeichert werden. Darüber hinaus können Sie die Prompt-Generierung mithilfe von Handlebars-Vorlagen anpassen. Schauen Sie sich die bereitgestellten Prompts in der Dokumentation an!

SDK

Das Software-Entwicklungskit (SDK) von code2prompt bietet eine Python-Bindung für die Core-Bibliothek. Dies ist perfekt für KI-Agenten oder Automatisierungsskripte, die nahtlos mit Codebasen interagieren möchten. Das SDK ist auf Pypi gehostet und kann über pip installiert werden.

MCP

code2prompt ist auch als Model Context Protocol (MCP)-Server verfügbar, der es ermöglicht, ihn als lokalen Dienst auszuführen. Dies ermöglicht LLMs auf Steroiden, indem es ihnen ein Tool bereitstellt, um automatisch einen gut strukturierten Kontext Ihrer Codebasis zu sammeln.

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Welcome (`website/src/content/docs/de/docs/welcome.mdx`)


title: Code2Prompt-Dokumentation
template: splash
hero:
tagline: Verwandeln Sie Ihren Code in Sekunden in KI-optimierte Prompts
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: Loslegen 🚀
link: /docs/tutorials/getting_started
- text: Installation 📥
link: /docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Schnellstart

code2prompt ist ein leistungsstarkes Code-Ingestion-Tool, das entwickelt wurde, um Prompts für Code-Analyse, -Generierung und andere Aufgaben zu erstellen. Es funktioniert, indem es Verzeichnisse durchläuft, eine Baumstruktur aufbaut und Informationen über jede Datei sammelt.

Es vereinfacht den Prozess der Kombination und Formatierung von Code, wodurch es leicht wird, Code mit LLMs zu analysieren, zu dokumentieren oder zu refactoren.

Sie können code2prompt auf folgende Weise verwenden:

Core-Bibliothek blitzschnell für Code-Ingestion Kommandozeilen-Interface speziell für Menschen entwickelt Software Development Kit für KI-Agenten und Automatisierungsskripte Model Context Protocol-Server für LLMs auf Steroiden ---

Hauptfunktionen

  • LLM-Prompts generieren: Schnell vollständige Codebasen in strukturierte LLM-Prompts umwandeln.
  • Glob-Muster-Filterung: Bestimmte Dateien und Verzeichnisse mithilfe von Glob-Mustern ein- oder ausschließen.
  • Benutzerdefinierte Vorlagen: Prompt-Generierung mit Handlebars-Vorlagen anpassen.
  • Token-Zählung: Token-Verwendung analysieren und für LLMs mit variierenden Kontextfenstern optimieren.
  • Git-Integration: Git-Diffs und Commit-Nachrichten in Prompts für Code-Reviews einschließen.
  • Respektiert .gitignore: Dateien, die in .gitignore aufgeführt sind, automatisch ignorieren, um die Prompt-Generierung zu optimieren.

Warum `code2prompt`?

  1. Zeit sparen:

    • Automatisiert den Prozess der Durchquerung einer Codebasis und der Formatierung von Dateien für LLMs.
    • Vermeidet wiederholtes Kopieren und Einfügen von Code.
  2. Produktivität steigern:

    • Bietet ein strukturiertes und konsistentes Format für Code-Analyse.
    • Hilft dabei, Bugs zu identifizieren, Code zu refactoren und Dokumentation schneller zu schreiben.
  3. Große Codebasen verarbeiten:

    • Entwickelt, um nahtlos mit großen Codebasen zu arbeiten, unter Berücksichtigung der Kontextlimits von LLMs.
  4. Benutzerdefinierte Workflows:

    • Flexible Optionen für die Filterung von Dateien, die Verwendung von Vorlagen und die Generierung gezielter Prompts.

Beispielanwendungsfälle

  • Code-Dokumentation:
    Automatisch Dokumentation für öffentliche Funktionen, Methoden und Klassen generieren.

  • Bug-Erkennung:
    Potenzielle Bugs und Schwachstellen durch Analyse der Codebasis mit LLMs finden.

  • Refactoring:
    Code vereinfachen und optimieren, indem Prompts für Code-Qualitätsverbesserungen generiert werden.

  • Lernen und Erkunden:
    Neue Codebasen verstehen, indem Zusammenfassungen und detaillierte Aufschlüsselungen generiert werden.

  • Git-Commit- und PR-Beschreibungen:
    Sinnvolle Commit-Nachrichten und Pull-Request-Beschreibungen aus Git-Diffs generieren.

text
> Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.

Website Src Content Docs Docs Explanations Glob Pattern Filter (`website/src/content/docs/docs/explanations/glob_pattern_filter.mdx`)


title: How the Glob Pattern Filter Works

Code2Prompt uses glob patterns to include or exclude files and directories, working similarly to tools like tree or grep. It lets you pass two independent lists of glob patterns:

  • include list (--include or -i) - “these patterns allow files”
  • exclude list (--exclude or -e) - “these patterns disallow files”

Code2prompt must decide, for every file in the project, whether it is kept or discarded. This page explains the rules, and the design choices behind them.


1. Sets and Symbols

Throughout the explanation we use the usual set notation

Symbol Meaning
$A$ set of files that match at least one include pattern
$B$ set of files that match at least one exclude pattern
$\Omega$ the whole project tree (the universe)
$C = A \cap B$ files that match both lists (the overlap)
$D = \Omega \setminus (A \cup B)$ files that match neither list

2. Four Situations

Overview of the four situations

Include list Exclude list Files kept
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. No include list, no exclude list

    If no patterns are specified, all files are kept (Ω).

  2. Exclude list only

    In this case, Code2Prompt acts as a blacklist, removing files that match the excluded patterns ( Ω \ B = ¬B).

  3. Include list only

    If only an include list is specified, Code2Prompt acts as a whitelist, keeping only files that match the included patterns (A).

  4. Include and exclude lists

    If both lists are specified, Code2Prompt keeps files that match the include patterns, but removes those that match the exclude patterns (A \ B).


3. More on the overlap

With both lists present (A ≠ ∅, B ≠ ∅) you have four logical possibilities
for the overlap C and the rest D.

Want C? Want D? Reasonable?
No No Default behaviour (A \ B)
Yes No Same behavior as case 3 (A)
No Yes surprising (“discard what I asked for C, keep what I didn't”)
Yes Yes Same behavior as case 1 (Ω)

This is for this reason that the --include-priority option was removed. Because, it would be the same result as if you had only an include list (case 3).

4. Quick reference table

Want to keep… Use
everything no -i, no -e
everything except some patterns -e only
only what matches the patterns -i only
what matches -i, minus what matches -e -i and -e

This design keeps the mental model simple:

  • The include list is a whitelist as soon as it exists.
  • The exclude list is a blacklist layered on top.
  • The overlap is discarded by default

Website Src Content Docs Docs Explanations Glob Patterns (`website/src/content/docs/docs/explanations/glob_patterns.md`)


title: Understanding Glob Patterns

Glob patterns are a simple yet powerful way to match file names and paths using wildcard characters. They are commonly used in command-line interfaces and programming languages to specify sets of filenames or directories. Here's a breakdown of the most commonly used glob patterns:

Basic Wildcards

  • *: Matches any number of characters, including zero characters.

    • Example: *.txt matches all files ending with .txt.
  • ?: Matches exactly one character.

    • Example: file?.txt matches file1.txt, fileA.txt, but not file10.txt.
  • []: Matches any one of the enclosed characters.

    • Example: file[1-3].txt matches file1.txt, file2.txt, file3.txt.
  • [!] or [^]: Matches any character not enclosed.

    • Example: file[!1-3].txt matches file4.txt, fileA.txt, but not file1.txt.

Advanced Patterns

  • **: Matches any number of directories and subdirectories recursively.

    • Example: **/*.txt matches all .txt files in the current directory and all subdirectories.
  • {}: Matches any of the comma-separated patterns enclosed.

    • Example: file{1,2,3}.txt matches file1.txt, file2.txt, file3.txt.

Examples

  1. Matching all text files in a directory:

    sh
    *.txt
  2. Matching all files with a single digit before the extension:

    sh
    file?.txt
  3. Matching files with extensions .jpg or .png:

    sh
    *.{jpg,png}
  4. Matching all .txt files in any subdirectory:

    sh
    **/*.txt
  5. Matching files that start with a or b and end with .txt:

    sh
    {a,b}*.txt

Use Cases

  • Command-Line Tools: Glob patterns are extensively used in command-line tools like ls, cp, mv, and rm to specify multiple files or directories.
  • Programming Languages: Languages like Python, JavaScript, and Ruby support glob patterns for file matching through libraries like glob in Python.
  • Build Systems: Tools like Makefile use glob patterns to specify source files and dependencies.

Conclusion

Glob patterns provide a flexible and intuitive way to match filenames and paths, making them invaluable for scripting, automation, and file management tasks. Understanding and utilizing these patterns can significantly enhance your productivity and efficiency in handling files and directories.


Website Src Content Docs Docs Explanations Tokenizers (`website/src/content/docs/docs/explanations/tokenizers.md`)


title: Tokenization in Code2Prompt

When working with language models, text needs to be transformed into a format that the model can understand : tokens, which are sequences of numbers. This transformation is handled by a tokenizer.


What is a Tokenizer?

A tokenizer converts raw text into tokens, which are the building blocks for how language models process input. These tokens can represent words, subwords, or even individual characters, depending on the tokenizer's design.

For code2prompt, we use the tiktoken tokenizer. It’s efficient, robust, and optimized for OpenAI models.
You can explore its functionality in the official repository

👉 tiktoken GitHub Repository

If you want to see a tokenizer in action and play with it, check out the

👉 Tiktokenizer

If you want to learn more about tokenizer in general, check out the

👉 Mistral Tokenization Guide

If you want a technical deep dive into tokenizers, check out Andrej Karpathy's blog post on building your own tokenizer.

👉 Build Your Own Tokenizer

Implementation in `code2prompt`

The reported prompt token count is an estimate. Files are tokenized in parallel
after processing and optional line numbering. Code2Prompt adds estimated template
overhead by rendering the template with empty file contents, avoiding another
tokenization pass over the full prompt.

Token boundaries between fragments, template escaping, and custom templates that
omit, repeat, or conditionally render content can make the actual count differ.
The estimate is not a guaranteed upper bound. For JSON output, token_count
estimates the embedded prompt; the JSON envelope and serialization escapes are
not counted. The CLI and TUI label this value as estimated, while the numeric
token_count field retains its name in Rust, Python, and JSON output.

Tokenization is implemented using tiktoken-rs. tiktoken supports these encodings used by OpenAI models:

CLI Argument Encoding name OpenAI models
cl100k cl100k_base ChatGPT models, text-embedding-ada-002
p50k p50k_base Code models, text-davinci-002, text-davinci-003
p50k_edit p50k_edit Use for edit models like text-davinci-edit-001, code-davinci-edit-001
r50k r50k_base (or gpt2) GPT-3 models like davinci
gpt2 o200k_base GPT-4o models

For more context on the different tokenizers, see the OpenAI Cookbook


Website Src Content Docs Docs How To Cli (`website/src/content/docs/docs/how_to/cli.mdx`)


title: Code2Prompt basic usage

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

Welcome to the `Code2Prompt` usage guide.

Usage

Generate a prompt from a codebase:

sh
code2prompt path/to/codebase

Generate a prompt and copy it to the clipboard:

sh
code2prompt path/to/codebase -c

Launch the interactive TUI:

sh
code2prompt path/to/codebase --tui

Display the token-map

sh
code2prompt path/to/codebase --token-map

Use a custom Handlebars template file:

sh
code2prompt path/to/codebase -t path/to/template.hbs

Filter files using glob patterns:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Exclude files using glob patterns:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

Exclude files/folders from the source tree based on exclude patterns:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

Filtered-out paths are pruned from the source tree by default. Use --full-directory-tree to print the whole tree regardless of the include/exclude patterns.

Display the token count of the generated prompt:

sh
code2prompt path/to/codebase --token-format=format

Specify a tokenizer for token count:

sh
code2prompt path/to/codebase --encoding=p50k

Supported tokenizers: cl100k, p50k, p50k_edit, r50k_bas.

Save the generated prompt to an output file:

sh
code2prompt path/to/codebase -O output.txt

Print output as XML:

sh
code2prompt path/to/codebase -F JSON

The JSON output will have the following structure:

json
{
  "prompt": "<Generated Prompt>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT models, text-embedding-ada-002",
  "files": []
}

Generate a Git commit message (for staged files):

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Generate a Pull Request with branch comparing (for staged files):

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Add line numbers to source code blocks:

sh
code2prompt path/to/codebase --line-numbers

Disable wrapping code inside markdown code blocks:

sh
code2prompt path/to/codebase --no-codeblock

Code2prompt is a nice way to generate prompts in a token efficient way. It can be practical for a variety of use cases, such as:

  • Rewrite the code to another language.
  • Find bugs/security vulnerabilities.
  • Document the code.
  • Implement new features.

Website Src Content Docs Docs How To Config (`website/src/content/docs/docs/how_to/config.mdx`)


title: Create a `.c2pconfig` File

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

In this guide, you'll learn how to create and use a `.c2pconfig` file to automate your prompt generation workflow.

Manually typing long exclude patterns, tokenizer settings, or custom variables every time you run Code2Prompt can become tedious. By creating a .c2pconfig configuration file, you can "set and forget" your project preferences. Code2Prompt will automatically look for this file in your current working directory and apply your rules seamlessly.

Here is a step-by-step guide to setting up your first configuration file.


Initialize your Configuration File

Navigate to the root directory of your project using your terminal and create a file named .c2pconfig.

bash
cd path/to/your/project
touch .c2pconfig

Step 2: Define your Base Behavior (TOML Format)

Open the .c2pconfig file in your preferred text editor. The file uses TOML syntax. Paste the following baseline configuration into the file:

toml
# Default behavior configuration
default_output = "clipboard"    # Options: stdout, clipboard, file
output_format = "xml"           # Options: markdown, json, xml
line_numbers = false            # Adds line numbers to your code blocks
encoding = "o200k"              # Matches the tokenizer to your target LLM

# Global filtering rules
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**", 
    "**/target/**", 
    "tests/fixtures/**",
    "package-lock.json"
]

Step 3: Run with Zero Arguments

Once your .c2pconfig file is saved at the root of your codebase, you no longer need to pass complex flags. Simply run the tool:

bash
code2prompt .

Code2Prompt will automatically read your .c2pconfig, filter your files using your glob patterns, attach line numbers, and format the output based on your choices.


Next Steps

To dive deeper into setting up advanced workflows, variables, and default configuration keys:


Website Src Content Docs Docs How To Install (`website/src/content/docs/docs/how_to/install.mdx`)


title: Installing Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Welcome to the `Code2Prompt` installation guide. This document provides step-by-step instructions for installing it on various platforms, including Windows, macOS, and Linux.

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

Prerequisite

Make sure Rust and cargo are installed on your system.

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

This is the official way to install the latest stable version of Rust and Cargo.
Make sure to refresh your PATH variable after installing Rust. Restart your terminal or run the instructions proposed by the installer.

sh
source $HOME/.cargo/env

You can check that everything is installed correctly by running:

sh
cargo --version
git --version

Command Line Interface (CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 Install the latest (unpublished) version from GitHub

If you want the latest features or fixes before they're released on crates.io:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

Source build

Ideal for developers that want to build from source or contribute to the project.

  1. 🛠️ Install Prerequisites :

  2. 📥 Clone the repository :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 Install the binary :

    To build and install from source:

    sh
    cargo install --path crates/code2prompt

    To build the binary without installing it:

    sh
    cargo build --release

    The binary will be available in the target/release directory.

  4. 🚀 Run it :

    sh
    code2prompt --help

Binary releases

Best for users that want to use the latest version without building from source.

Download the latest binary for your OS from Releases.

⚠️ Binary releases may lag behind the latest GitHub version. For cutting-edge features, consider building from source.

AUR

Specifically for Arch Linux users, code2prompt is available in the AUR.

code2prompt is available in the AUR. Install it via any AUR helpers.

sh
paru/yay -S code2prompt

Nix

If you're using Nix, you can install it using either nix-env or nix profile.

sh
# without flakes:
nix-env -iA nixpkgs.code2prompt
# with flakes:
nix profile install nixpkgs#code2prompt

Software Development Kit (SDK) 🐍

Pypi

You can download the python bindings from Pypi

sh
pip install code2prompt_rs

Source build

  1. 🛠️ Install Prerequisites :

  2. 📥 Clone the repository :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 Install the dependencies :

    uv creates .venv, locks the development dependencies, and builds the native extension in editable mode.

    sh
    uv sync
  4. 🧪 Run the tests :

    Run the project's test command in the synchronized environment.

    sh
    uv run pytest

Model Context Protocol (MCP) 🤖

Automated installation

The code2prompt MCP server will soon be available in MCP registries.

Manual installation

The code2prompt MCP server is still a prototype and will be integrated to the main repository soon.

To run the MCP server, locally to use it with Cline, Goose or Aider:

  1. 🛠️ Install Prerequisites :

  2. 📥 Clone the repository :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 Install the dependencies :

    The rye command will create a virtual environment and install all the dependencies in the .venv folder.

    sh
    rye sync
  4. 🚀 Run the server :

    The MCP server is now installed. You can run it using:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 Integrate with Agents :

    text
    For instance, you can integrate it with `Cline`, using a similar configuration:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

Website Src Content Docs Docs How To Ssh (`website/src/content/docs/docs/how_to/ssh.mdx`)


title: Use Code2prompt CLI with SSH

import { Card } from "@astrojs/starlight/components";

Welcome to the how to use `Code2Prompt` with SSH guide.

Why it doesn't work?

When you try to run the code2prompt . -c with the CLI on a remote server via SSH, the command is unable to find the clipboard. This is because the code2prompt CLI uses the clipboard to copy the generated prompt, and SSH sessions typically do not have access to the local clipboard.

Solution

To use the code2prompt CLI with SSH, you can redirect the output to a file instead of copying it to the clipboard. This way, you can still generate the prompt and save it for later use.

Use the --output-file option to specify the output file where the generated prompt will be saved. For example:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

Website Src Content Docs Docs How To Tui (`website/src/content/docs/docs/how_to/tui.mdx`)


title: Use Code2prompt Terminal User Interface (TUI)

import { Card } from "@astrojs/starlight/components";


Website Src Content Docs Docs Tutorials Configuration (`website/src/content/docs/docs/tutorials/configuration.mdx`)


title: Configuring Code2Prompt 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

Manually typing long exclude patterns or specific tokenizer settings every time can be tedious. Therefore this tutorial shows you **how to use a `.c2pconfig` configuration file** to "set and forget" your project settings.

Prerequisites

Ensure you have code2prompt installed. If you haven't installed it yet, refer to the Installation Guide. Familiarity with TOML syntax is helpful but not required.


What is .c2pconfig?

The .c2pconfig file is a configuration file written in TOML format. When you run code2prompt, it automatically searches for this file in your current working directory.

It allows you to define:

  • Filtering Rules: Persistent include/exclude patterns.
  • Output Formats: Default to JSON, Markdown, or XML.
  • Template Context: Pre-define variables for your Handlebars templates.

Quick Start

Create a file named .c2pconfig at the root of your project to define your base behavior.

toml
# .c2pconfig example
default_output = "stdout" # Options: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MyAwesomeProject"
author = "Developer"

Configuration Reference

The following table describes the keys available in the configuration file.

Key Type Description
path String Default path to codebase (usually .).
include_patterns Array Glob patterns of files to include.
exclude_patterns Array Glob patterns of files to exclude.
line_numbers Boolean If true, adds line numbers to code blocks.
absolute_path Boolean Use absolute paths instead of relative paths.
full_directory_tree Boolean Generate the full tree even for excluded files.
output_format String markdown, json, or xml.
sort_method String name_asc, name_desc, date_asc, date_desc.
encoding String Tokenizer: cl100k, p50k, o200k.
diff_enabled Boolean Include git diff (HEAD vs Index).
token_map_enabled Boolean Display a hierarchical token usage map.

Implementation Guide

Follow these steps to integrate a configuration file into your workflow.

  1. Initialize your Configuration
    Navigate to your project root and create the config file:
    bash touch .c2pconfig

  2. Define your Source of Truth
    Exclude heavy directories like node_modules or build artifacts to keep the LLM context clean.
    toml exclude_patterns = [ "**/node_modules/**", "package-lock.json", "dist/**" ]

  3. Set your Model Encoding
    Match the tokenizer to your target LLM. Use o200k for GPT-4o, or cl100k for Claude and GPT-4.
    toml encoding = "o200k"

  4. Inject Custom Context
    Use the [user_variables] section to pass data into your Handlebars templates.
    toml [user_variables] project_goal = "Refactor the authentication module for better security."

  5. Run with Zero Arguments
    Simply run the tool. It will now respect all your predefined rules without extra CLI flags.
    bash code2prompt .


Understanding Precedence

It is important to understand how code2prompt decides which settings to use when multiple sources conflict.


Example: The "Review-Ready" Config

Use this setup if your primary goal is generating prompts for code reviews.

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

Next Steps


Website Src Content Docs Docs Tutorials Getting Started (`website/src/content/docs/docs/tutorials/getting_started.mdx`)


title: Getting Started with Code2Prompt

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Welcome to Code2Prompt! This tutorial provides an introduction to using Code2Prompt to generate AI-ready prompts from your codebases. We'll explore its core functionality and demonstrate its usage across different integration methods.

What is Code2Prompt?

Code2Prompt is a system tool designed to extract codebase informations for LLMs. It extracts relevant code snippets, applies filtering, and formats the information into structured prompts optimized for LLM. This simplifies tasks like code documentation, bug detection, refactoring, and more.

Code2Prompt offers different flavors to suit various use cases:

A core rust library that provides the foundation for code ingestion and prompt A user-friendly command-line interface for quick prompt generation. Ideal for interactive use and one-off tasks. A powerful Software Development Kit (SDK) for seamless integration into your Python projects. Perfect for automating prompt generation within larger workflows. A Model Context Protocol (MCP) server for integration with LLM agents. Enables sophisticated, real-time interactions with your codebase.

📥 Installation

For detailed installation instructions for all methods (CLI, SDK, MCP), please refer to the

🏁 Generating Prompts: A CLI Example

Let's start with a simple example using the CLI. Create a sample project:

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Now, generate a prompt:

bash
code2prompt my_project

This copies a prompt to your clipboard. You can customize this:

  • Filtering: code2prompt my_project --include="*.rs" --exclude="tests/*" (includes only .rs files, excludes tests directory)
  • Output File: code2prompt my_project --output-file=my_prompt.txt
  • JSON Output: code2prompt my_project -O json (structured JSON output)
  • Custom Templates: code2prompt my_project -t my_template.hbs (requires creating my_template.hbs)

To learn more about code2prompt, check out the following tutorials:


🐍 SDK Integration (Python)

For programmatic control, use the Python SDK:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

This requires installing the SDK (pip install code2prompt_rs). Refer to the SDK documentation for more details.

🤖 Harness Integration

To reduce token usage of your harness, you can let your agent run code2prompt as a MCP server or as a skill. This allows agents to request code context dynamically in a way that replaces multiple find, glob and grep calls.


Website Src Content Docs Docs Tutorials Learn Filters (`website/src/content/docs/docs/tutorials/learn_filters.mdx`)


title: Learn Context Filtering with Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

This tutorial demonstrates how to use the **glob pattern tool** in `code2prompt` CLI to filter and manage files based on include and exclude patterns. It will drive you through a small playground to practice different filtering scenarios.

Prerequisites

Ensure you have code2prompt installed. If you haven't installed it yet, refer to the

Glob patterns work similarly to tools like tree or grep,
providing powerful filtering capabilities. If you never heard about what is a glob pattern, check out the


for more informations.


Setting Up the Environment

To practice with glob patterns, let's create a sample folder structure with some files as a playground.

Generate Test Structure

Run this script to set up a temporary directory structure

bash
#!/bin/bash

# Create base directory
mkdir -p test_dir/{lowercase,uppercase,.secret}

# Create files in the structure
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

To clean up the structure later, run:

bash
rm -rf test_dir

It will create the following directory structure:

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.py - BAR.py - BAZ.py - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

General Usage of `code2prompt`

By default, code2prompt includes all files in the specified directory respecting the .gitignore.

Filtering Files with Include and Exclude Patterns

The Include and Exclude options allow you to filter files dynamically based on glob patterns.

Glob patterns allow you to specify rules for filtering files and directories.

  • Include Patterns (--include or -i): Specify files and directories you want to include.
  • Exclude Patterns (--exclude or -e): Specify files and directories you want to exclude.

If you want to learn more about the internals you can check out the

Case 1: Default Behavior (No Filters)

Command:

bash
code2prompt test_dir

Result

All files are included:

  • lowercase/foo.py
  • lowercase/bar.py ...
  • uppercase/FOO.py ...
  • .secret/secret.txt

Case 2: Exclude Specific File Types

Exclude .txt or .md files:

bash
code2prompt test_dir --exclude="*.txt,*.md"

Result

Excluded:

  • All .txt or .md files

Included:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

Case 3: Include Specific File Types

Include only Python files:

bash
code2prompt test_dir --include="*.py"

Result

Included:

  • All .py files

Excluded:

  • .secret/secret.txt

Case 4: Include and Exclude with Priority

Include .py files but exclude files in the uppercase folder:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

Result

Included:

  • All lowercase/1 files having .py extension

Excluded:

  • All uppercase files
  • .secret/secret.txt

Case 5: Exclude Specific Directory

Exclude the uppercase directory:

bash
code2prompt test_dir --exclude "**/uppercase*"

or with short syntax:

bash
code2prompt test_dir -e "uppercase*"

Result

Included:

  • All files in lowercase and .secret

Excluded:

  • All files in uppercase

Summary

The glob pattern tool in code2prompt allows you to filter files and directories effectively using:

  • --include for specifying files to include
  • --exclude for files to exclude
  • --include-priority for resolving conflicts between patterns

To practice, set up the sample directory, try out the commands, and see how the tool filters files dynamically.


Website Src Content Docs Docs Tutorials Learn Templates (`website/src/content/docs/docs/tutorials/learn_templates.mdx`)


title: Learn Handlebar Templates with Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

This tutorial demonstrates how to use and create custom Handlebars templates for prompt generation in `code2prompt` CLI.

Prerequisites

Ensure you have code2prompt installed. If you haven't installed it yet, refer to the


What are Handlebars Templates ?

Handlebars is a popular templating engine that allows you to create dynamic templates using placeholders.
In code2prompt, Handlebars templates are used to format the generated prompts based on the codebase structure and user-defined variables.

How to use Handlebars Templates ?

You can use these templates by passing the -t or --template flag followed by the path to the template file. For example:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

Template Syntax

Handlebars templates use a simple syntax for placeholders and expressions. You will place variables in double curly braces {{variable_name}} to include them in the generated prompt.
Code2prompt provides a set of default variables that you can use in your templates:

  • absolute_code_path: The absolute path to the codebase.
  • source_tree: The source tree of the codebase, which includes all files and directories.
  • files: A list of files in the codebase, including their paths and contents.
  • git_diff: The git diff of the codebase, if applicable.
  • code: The code content of the file being processed.
  • path: The path of the file being processed.

You can also use Handlebars helpers to perform conditional logic, loops, and other operations within your templates. For example:

handlebars
{{#if files}}
  {{#each files}}
    File:
    {{this.path}}
    Content:
    {{this.content}}
  {{/each}}
{{else}}
  No files found.
{{/if}}

Existing Templates

code2prompt comes with a set of built-in templates for common use cases. You can find them in the templates directory.

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

Use this template to generate prompts for documenting the code. It will add documentation comments to all public functions, methods, classes and modules in the codebase.

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

Use this template to generate prompts for finding potential security vulnerabilities in the codebase. It will look for common security issues and provide recommendations on how to fix or mitigate them.

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

Use this template to generate prompts for cleaning up and improving the code quality. It will look for opportunities to improve readability, adherence to best practices, efficiency, error handling, and more.

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

Use this template to generate prompts for fixing bugs in the codebase. It will help diagnose issues, provide fix suggestions, and update the code with proposed fixes.

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

Use this template to create GitHub pull request description in markdown by comparing the git diff and git log of two branches.

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

Use this template to generate a high-quality README file for the project, suitable for hosting on GitHub. It will analyze the codebase to understand its purpose and functionality, and generate the README content in Markdown format.

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

Use this template to generate git commits from the staged files in your git directory. It will analyze the codebase to understand its purpose and functionality, and generate the git commit message content in Markdown format.

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

Use this template to generate prompts for improving the performance of the codebase. It will look for optimization opportunities, provide specific suggestions, and update the code with the changes.

User Defined Variables

code2prompt supports the use of user defined variables in the Handlebars templates. Any variables in the template that are not part of the default context (absolute_code_path, source_tree, files) will be treated as user defined variables.

During prompt generation, code2prompt will prompt the user to enter values for these user defined variables. This allows for further customization of the generated prompts based on user input.

For example, if your template includes {{challenge_name}} and {{challenge_description}}, you will be prompted to enter values for these variables when running code2prompt.

This feature enables creating reusable templates that can be adapted to different scenarios based on user provided information.


Website Src Content Docs Docs Tutorials Tui (`website/src/content/docs/docs/tutorials/tui.mdx`)


title: Using the Terminal UI (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2prompt` features a fully interactive Terminal User Interface (TUI). This guide walks you through launching the TUI and mastering its five core tabs.

Launching the TUI

To open the interactive interface, simply append the --tui flag to your command alongside your project path:

bash
code2prompt path/to/your/codebase --tui

1. Selection Tab (File Tree)

The Selection tab is where you curate the exact context you want to send to the LLM. It displays a hierarchical view of your project, respecting your .gitignore and .c2pconfig rules.

  • Navigation: Use ↑ / ↓ to move the cursor, and ← / → to expand or collapse directories.
  • Selection: Press Space to select or deselect a file or an entire directory.
  • Search Mode: Press s or / to enter Search Mode.
  • You can type text or use wildcards (*, ?) to instantly filter the tree.
  • Press Enter or Esc to exit Search Mode and return to normal navigation.

2. Settings Tab

Need to tweak how the output is formatted before generating? The Settings tab gives you visual checkboxes and dropdowns for your active session.


3. Statistics Tab

Before you spend money sending a massive prompt to an LLM, use the Statistics tab to understand your token budget.

Use ← / → to switch between three powerful views:


4. Template Tab

The Template tab is where the magic happens. It features a responsive multi-column layout to help you craft the perfect Handlebars template.

When you are in the Template tab, you can instantly snap your focus between three sub-panels using keyboard shortcuts:


5. Output Tab

Once you've selected your files, tweaked your settings, and chosen your template, press Enter to generate the final output.

The Output tab displays the final prompt exactly as it will be sent to the LLM.

  • Scroll: Use ↑ / ↓, PgUp, or PgDn to review the generated text.
  • Copy: Press c to instantly copy the entire prompt to your system clipboard.
  • Save: Press s to save the prompt directly to a local Markdown file (e.g., prompt_20260613_204753.md).

If you realize you missed a file, simply press 1 to jump back to the Selection tab, check the file, and press Enter to regenerate the output in real-time.


Website Src Content Docs Es Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/es/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Por qué desarrollé Code2Prompt"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • AI
  • Agent
    excerpt: "La historia detrás de code2prompt: mi búsqueda de código abierto para abordar los desafíos de contexto en los flujos de trabajo de LLM"
    authors:
  • ODAncona
    cover:
    alt: "Una ilustración de code2prompt que agiliza el contexto del código para agentes de inteligencia artificial."
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

Introducción

Siempre me ha fascinado cómo los modelos de lenguaje grandes (LLM) transforman los flujos de trabajo de codificación, generando pruebas, docstrings o incluso enviando características completas en minutos. Pero a medida que empujaba a estos modelos más lejos, surgían algunos puntos críticos:

Dificultades de planificación Altos costos de tokens Alucinaciones
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

Es por eso que comencé a contribuir a code2prompt, una herramienta basada en Rust para ayudar a proporcionar el contexto adecuado a los LLM.

En este post, compartiré mi viaje y explicaré por qué estoy convencido de que code2prompt es relevante hoy en día y se integra tan bien, y por qué se ha convertido en mi solución para flujos de trabajo de codificación con inteligencia artificial más rápidos y mejores.

Mis primeros pasos con LLM 👣

Comencé a experimentar con LLM en OpenAI Playground con text-davinci-003 cuando ganó popularidad en noviembre de 2023. Los modelos de lenguaje permitieron una nueva revolución. Se sintió como tener un asistente brillante que generaba pruebas unitarias y docstrings casi a pedido. Disfruté empujando a los modelos a sus límites, probando todo, desde charlas pequeñas y dilemas éticos hasta jailbreaks y tareas de codificación complejas. Sin embargo, a medida que asumí proyectos más extensos, rápidamente me di cuenta de que los modelos tenían limitaciones evidentes. Al principio, solo podía ajustar unas pocas cientos de líneas de código en la ventana de contexto, y ni siquiera entonces, los modelos a menudo luchaban por comprender el propósito o la estructura del código. Es por eso que rápidamente noté que la importancia del contexto era fundamental. Cuanto más concisas eran mis instrucciones y mejor era el contexto, mejores eran los resultados.

Evolución del modelo 🏗️

Los modelos podían producir resultados impresionantes, pero a menudo luchaban con bases de código más grandes o tareas complejas. Me encontré pasando más tiempo elaborando indicaciones que codificando. Al mismo tiempo, los modelos seguían mejorando con el lanzamiento de nuevas versiones. Aumentaron las habilidades de razonamiento y el tamaño del contexto, ofreciendo nuevas perspectivas y posibilidades. Pude ajustar casi dos mil líneas de código en la ventana de contexto, y los resultados mejoraron. Pude escribir características completas en cuestión de unas pocas iteraciones, y me asombré de lo rápido que podía obtener resultados. Estaba convencido de que los LLM eran el futuro de la codificación, y quería ser parte de esa revolución. Creo firmemente que la inteligencia artificial no nos reemplazará todavía. Pero nos asistirá en forma de asistentes donde los humanos siguen siendo los expertos en control.

Mis primeros proyectos con LLM 🚀

Comencé a escribir un módulo de búsqueda de rutas ROS para una competencia robótica, generar características para una aplicación multiplataforma Flutter de arquitectura limpia, y creé una pequeña aplicación web para rastrear mis gastos en Next.js. El hecho de que construyera esta pequeña aplicación en una noche, en un marco que nunca había tocado antes, fue un momento que cambió el juego para mí; los LLM no eran solo herramientas, sino multiplicadores. Desarrollé bboxconverter, un paquete para convertir cajas de límites, y la lista sigue. Los LLM pueden ayudarlo a aprender nuevas tecnologías y marcos rápidamente; eso es genial.

Un nuevo paradigma: Software 3.0 💡

Me sumergí más en los LLM y comencé a construir agentes y andamiaje alrededor de ellos. Reproduje el famoso artículo RestGPT. La idea es excelente: dar a los LLM la capacidad de llamar a algunas API REST con una especificación OpenAPI, como Spotify o TMDB. Estas capacidades introducen un nuevo paradigma de programación de software, que me gusta llamar Software 3.0.

Software 1.0 Software 2.0 Software 3.0
Basado en reglas Impulsado por datos Agente

La misma idea impulsó el protocolo MCP, que permite a los LLM llamar a herramientas y recursos directamente de manera fluida porque, por diseño, la herramienta necesita una descripción para ser llamada por el LLM en el opuesto de las API REST que no requieren necesariamente una especificación OpenAPI.

Las limitaciones de los LLM 🧩

Alucinaciones 🌀

Mientras reproducía el famoso artículo RESTGPT, noté algunas limitaciones graves de los LLM. Los autores del artículo encontraron los mismos problemas que yo: los LLM estaban alucinando. Generan código que no se implementa, inventando argumentos y simplemente siguiendo las instrucciones al pie de la letra sin aprovechar el sentido común. Por ejemplo, en el código base original de RestGPT, los autores preguntaron en la indicación del llamador.

"para no ser astuto y hacer pasos que no existen en el plan".

Encontré esta afirmación divertida y muy interesante porque fue la primera vez que encontré a alguien instruyendo a los LLM para que no alucinaran.

Tamaño de contexto limitado 📏

Otra limitación fue el tamaño del contexto; los LLM se desempeñan bien para encontrar la aguja en el pajar, pero luchan por entenderlo. Cuando le das demasiado contexto a los modelos de lenguaje, tienden a perderse en los detalles y perder de vista la imagen general, lo cual es molesto y requiere una dirección constante. La forma en que me gusta pensar al respecto es de manera similar a la maldición de la dimensionalidad. Reemplaza la palabra "dimensión" o "característica" por "contexto", y obtienes la idea.

Cuanto más contexto le das al LLM, más difícil es encontrar la respuesta correcta. Surgí con una frase agradable para resumir esta idea:

Proporcionar la menor cantidad de contexto posible pero la necesaria

Esto está fuertemente inspirado en la famosa cita de Alain Berset, un político suizo 🇨🇭 que dijo durante el bloqueo de COVID-19:

"Queremos actuar lo más rápido posible, pero también lo más lentamente necesario".

Esto representa la idea de compromiso y se aplica al tamaño del contexto de los LLM.

Buscando una mejor manera: code2prompt 🔨

Por lo tanto, necesitaba una forma de cargar, filtrar y organizar mi contexto de código rápidamente proporcionando la menor cantidad posible de contexto con la mejor calidad posible. Intenté copiar manualmente archivos o fragmentos en indicaciones, pero eso se volvió engorroso y propenso a errores. Sabía que automatizar el proceso tedioso de forjar el contexto para hacer mejores indicaciones sería útil. Luego, un día, escribí "code2prompt" en Google, esperando encontrar una herramienta que canalizara mi código directamente en indicaciones.

Y he aquí, descubrí un proyecto basado en Rust de Mufeed llamado code2prompt, con alrededor de 200 estrellas en GitHub. Todavía era básico en ese momento: una herramienta CLI simple con capacidad de filtro limitada y plantillas. Vi un enorme potencial y me uní directamente para contribuir, implementando la coincidencia de patrones glob, entre otras características, y pronto me convertí en el principal contribuyente.

Visión e integraciones 🔮

Hoy en día, hay varias formas de proporcionar contexto a los LLM. Generar a partir del contexto más grande, utilizando la generación aumentada de recuperación (RAG), comprimiendo el código, o incluso utilizando una combinación de estos métodos. La creación de contexto es un tema candente que evolucionará rápidamente en los próximos meses. Sin embargo, mi enfoque es KISS: Manténlo simple, estúpido. La mejor forma de proporcionar contexto a los LLM es utilizar la forma más simple y eficiente posible. Forjas precisamente el contexto que necesitas; es determinista, a diferencia de RAG.

Es por eso que decidí impulsar code2prompt más lejos como una herramienta simple que se puede utilizar en cualquier flujo de trabajo. Quería hacerlo fácil de usar, fácil de integrar y fácil de extender. Es por eso que agregué nuevas formas de interactuar con la herramienta.

  • Núcleo: El núcleo de code2prompt es una biblioteca de Rust que proporciona la funcionalidad básica para forjar contexto a partir de tu base de código. Incluye una API simple para cargar, filtrar y organizar tu contexto de código.
  • CLI: La interfaz de línea de comandos es la forma más simple de usar code2prompt. Puedes forjar contexto a partir de tu base de código y canalizarlo directamente en tus indicaciones.
  • API de Python: La API de Python es un envoltorio simple alrededor de la CLI que te permite usar code2prompt en tus scripts y agentes de Python. Puedes forjar contexto a partir de tu base de código y canalizarlo directamente en tus indicaciones.
  • MCP: El servidor MCP de code2prompt permite a los LLM usar code2prompt como una herramienta, lo que les permite ser capaces de forjar el contexto.

La visión se describe más a fondo en la página de visión en el documento.

Integración con agentes 👤

Creo que los agentes futuros necesitarán tener una forma de ingerir contexto, y code2prompt es la forma simple y eficiente de hacerlo para repositorios textuales como bases de código, documentación o notas. Un lugar propicio para usar code2prompt sería en una base de código con convenciones de nombres significativas. Por ejemplo, en la arquitectura limpia, hay una clara separación de preocupaciones y capas. El contexto relevante suele residir en diferentes archivos y carpetas pero comparte el mismo nombre. Este es un caso de uso perfecto para code2prompt, donde puedes usar el patrón glob para agarrar los archivos relevantes.

Basado en patrones glob: Selecciona o excluye archivos con minimal molestia.

Además, la biblioteca central está diseñada como un administrador de contexto estatal, lo que te permite agregar o eliminar archivos a medida que evoluciona tu conversación con el LLM. Esto es particularmente útil cuando proporcionas contexto para una tarea o objetivo específico. Puedes agregar o eliminar archivos del contexto sin volver a ejecutar el proceso.

Contexto estatal: Agrega o elimina archivos a medida que evoluciona tu conversación con el LLM.

Estas capacidades hacen que code2prompt sea un ajuste perfecto para flujos de trabajo basados en agentes. El servidor MCP permite una integración perfecta con marcos de agentes de inteligencia artificial populares como Aider, Goose, o Cline. Dejan que manejen objetivos complejos mientras code2prompt entrega el contexto de código perfecto.

Por qué Code2prompt importa ✊

A medida que los LLM evolucionan y las ventanas de contexto se expanden, puede parecer que simplemente forzar a los repositorios enteros en indicaciones es suficiente. Sin embargo, los costos de tokens y la coherencia de las indicaciones siguen siendo importantes obstáculos para las pequeñas empresas y los desarrolladores. Centrándose solo en el código que importa, code2prompt mantiene tu uso de LLM eficiente, rentable y menos propenso a la alucinación.

En resumen:

  • Reduce las alucinaciones proporcionando la cantidad adecuada de contexto
  • Reduce los costos de tokens mediante la curación manual del contexto adecuado necesario
  • Mejora el rendimiento de LLM proporcionando la cantidad adecuada de contexto
  • Integra la pila agéntica como un alimentador de contexto para repositorios textuales

Puedes unirte ¡Es de código abierto! 🌐

¡Todos los nuevos contribuyentes son bienvenidos! ¡Ven a bordo si estás interesado en Rust, forjando herramientas innovadoras de inteligencia artificial o simplemente quieres un mejor flujo de trabajo para tus indicaciones basadas en código!

Gracias por leer, y espero que mi historia te haya inspirado a revisar code2prompt. Ha sido un viaje increíble, y apenas está empezando.

Olivier D'Ancona

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Vision (`website/src/content/docs/es/docs/vision.mdx`)


title: La visión de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` fue creado para ayudar a los desarrolladores y agentes de inteligencia artificial a interactuar con bases de código de manera más efectiva.

El problema 🚩

Los modelos de lenguaje grandes (LLM) han revolucionado la forma en que interactuamos con el código. Sin embargo, todavía enfrentan desafíos significativos con la generación de código:

  • Planificación y razonamiento: Los LLM carecen de la capacidad de planificar y razonar, lo cual es crucial para tareas como la generación de código, la refactorización y la depuración. A menudo luchan por obtener una visión general y son cortoplacistas.
  • Tamaño del contexto: Los LLM tienen una ventana de contexto limitada, lo que restringe su capacidad para analizar y comprender bases de código grandes.
  • Alucinación: Los LLM pueden generar código que parece correcto pero que en realidad es incorrecto o absurdo. Este fenómeno, conocido como alucinación, ocurre cuando el modelo carece de contexto suficiente o comprensión de la base de código.

Aquí es donde entra en juego code2prompt.

La solución ✅

Creemos que la planificación y el razonamiento pueden lograrse mediante técnicas de andamiaje con agentes humanos o de inteligencia artificial. Estos agentes necesitan recopilar un contexto de alta calidad de la base de código que esté filtrado, estructurado y formateado para la tarea en cuestión.

La regla general sería:

Esto es prácticamente difícil de lograr, especialmente para bases de código grandes. Sin embargo, code2prompt es una herramienta simple que puede ayudar a los desarrolladores y agentes de inteligencia artificial a ingerir la base de código de manera más efectiva.

Automatiza el proceso de recorrer una base de código, filtrar archivos y formatearlos en indicaciones estructuradas que los LLM pueden comprender. Al hacerlo, ayuda a mitigar los desafíos de planificación, razonamiento y alucinación.

Puede entender cómo code2prompt está diseñado para abordar estos desafíos en la siguiente sección.

Arquitectura ⛩️

code2prompt está diseñado de manera modular, lo que permite una fácil integración en varios flujos de trabajo. Puede utilizarse como una biblioteca central, una interfaz de línea de comandos (CLI), un kit de desarrollo de software (SDK) o incluso como un servidor de protocolo de contexto de modelo (MCP).

Central

code2prompt es una herramienta de ingesta de código que agiliza el proceso de crear indicaciones de LLM para análisis de código, generación y otras tareas. Funciona recorriendo directorios, construyendo una estructura de árbol y recopilando información sobre cada archivo. La biblioteca central se puede integrar fácilmente en otras aplicaciones.

CLI

La interfaz de línea de comandos (CLI) de code2prompt fue diseñada para que los humanos generen indicaciones directamente desde su base de código. La indicación generada se copia automáticamente al portapapeles y también se puede guardar en un archivo de salida. Además, puede personalizar la generación de indicaciones utilizando plantillas de Handlebars. ¡Eche un vistazo a las indicaciones proporcionadas en la documentación!

SDK

El kit de desarrollo de software (SDK) de code2prompt ofrece una vinculación de Python a la biblioteca central. Esto es perfecto para agentes de inteligencia artificial o scripts de automatización que desean interactuar con la base de código sin problemas. El SDK se hospeda en Pypi y se puede instalar mediante pip.

MCP

code2prompt también está disponible como un servidor de protocolo de contexto de modelo (MCP), lo que permite ejecutarlo como un servicio local. Esto permite a los LLM en esteroides proporcionarles una herramienta para recopilar automáticamente un contexto bien estructurado de su base de código.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Welcome (`website/src/content/docs/es/docs/welcome.mdx`)


title: Documentación de Code2Prompt
template: splash
hero:
tagline: Transforma tu código en indicaciones optimizadas para IA en segundos
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: Empezar 🚀
link: /docs/tutorials/getting_started
- text: Instalación 📥
link: /docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Inicio rápido

code2prompt es una poderosa herramienta de ingesta de código diseñada para generar indicaciones para análisis de código, generación y otras tareas. Funciona recorriendo directorios, construyendo una estructura de árbol y recopilando información sobre cada archivo.

Simplifica el proceso de combinar y formatear código, lo que facilita el análisis, la documentación o la refactorización de código utilizando LLMs.

Puedes utilizar code2prompt de las siguientes maneras:

Biblioteca central extremadamente rápida para ingesta de código Interfaz de línea de comandos especialmente diseñada para humanos Kit de desarrollo de software para agentes de IA y scripts de automatización Servidor de protocolo de contexto de modelo para LLMs mejorados

Características clave

  • Generar indicaciones LLM: Convierte rápidamente bases de código enteras en indicaciones estructuradas para LLM.
  • Filtrado de patrones Glob: Incluye o excluye archivos y directorios específicos utilizando patrones Glob.
  • Plantillas personalizables: Adapta la generación de indicaciones con plantillas Handlebars.
  • Conteo de tokens: Analiza el uso de tokens y optimiza para LLMs con ventanas de contexto variables.
  • Integración con Git: Incluye diferencias de Git y mensajes de confirmación en las indicaciones para revisiones de código.
  • Respeta .gitignore: Ignora automáticamente archivos listados en .gitignore para agilizar la generación de indicaciones.

¿Por qué `code2prompt`?

  1. Ahorra tiempo:

    • Automatiza el proceso de recorrer una base de código y formatear archivos para LLMs.
    • Evita copiar y pegar repetidamente código.
  2. Mejora la productividad:

    • Proporciona un formato estructurado y consistente para el análisis de código.
    • Ayuda a identificar errores, refactorizar código y escribir documentación más rápido.
  3. Maneja bases de código grandes:

    • Diseñado para funcionar sin problemas con bases de código grandes, respetando los límites de contexto de LLMs.
  4. Flujos de trabajo personalizables:

    • Opciones flexibles para filtrar archivos, utilizar plantillas y generar indicaciones específicas.

Casos de uso ejemplo

  • Documentación de código:
    Genera automáticamente documentación para funciones públicas, métodos y clases.

  • Detección de errores:
    Encuentra posibles errores y vulnerabilidades analizando tu base de código con LLMs.

  • Refactorización:
    Simplifica y optimiza código generando indicaciones para mejoras en la calidad del código.

  • Aprendizaje y exploración:
    Entiende nuevas bases de código generando resúmenes y descomposiciones detalladas.

  • Descripciones de confirmaciones de Git y PR:
    Genera mensajes de confirmación significativos y descripciones de solicitudes de extracción a partir de diferencias de Git.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Fr Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/fr/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Pourquoi j'ai développé Code2Prompt"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • IA
  • Agent
    excerpt: "L'histoire derrière code2prompt : ma quête Open-Source pour relever les défis de contexte dans les flux de travail LLM"
    authors:
  • ODAncona
    cover:
    alt: "Une illustration de code2prompt simplifiant le contexte de code pour les agents IA."
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

Introduction

Je suis toujours fasciné par la façon dont les modèles de langage à grande échelle (LLM) transforment les flux de travail de codage - générant des tests, des docstrings ou même des fonctionnalités entières en quelques minutes. Mais à mesure que je poussais ces modèles plus loin, quelques points de douleur critiques continuaient à émerger :

Difficultés de planification Coûts de jetons élevés Hallucinations
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

C'est pourquoi j'ai commencé à contribuer à code2prompt, un outil basé sur Rust pour aider à fournir juste le contexte approprié aux LLM.

Dans cet article, je partagerai mon parcours et expliquerai pourquoi je suis convaincu que code2prompt est pertinent aujourd'hui et s'intègre si bien, et pourquoi il est devenu ma solution incontournable pour des flux de travail de codage IA meilleurs et plus rapides.

Mes premiers pas avec les LLM 👣

J'ai commencé à expérimenter avec les LLM sur OpenAI Playground avec text-davinci-003 lorsqu'il a gagné en popularité en novembre 2023. Les modèles de langage ont permis une nouvelle révolution. Cela ressemblait à avoir un assistant brillant qui pouvait produire des tests unitaires et des docstrings presque sur commande. J'ai apprécié pousser les modèles à leurs limites - testant tout, des conversations informelles et des dilemmes éthiques aux jailbreaks et aux tâches de codage complexes. Cependant, à mesure que j'ai abordé des projets plus importants, j'ai rapidement réalisé que les modèles avaient des limitations criantes. Au début, je ne pouvais adapter que quelques centaines de lignes de code dans la fenêtre de contexte, et même alors, les modèles avaient souvent du mal à comprendre le but ou la structure du code. C'est pourquoi j'ai rapidement remarqué que l'importance du contexte était primordiale. Plus mes instructions étaient concises et meilleur était le contexte, meilleurs étaient les résultats.

Évolution des modèles 🏗️

Les modèles pouvaient produire des résultats impressionnants mais avaient souvent du mal avec des bases de code plus importantes ou des tâches complexes. Je me suis retrouvé à passer plus de temps à élaborer des invites qu'à coder réellement. Dans le même temps, les modèles continuaient à s'améliorer avec la sortie de nouvelles versions. Ils ont augmenté leurs capacités de raisonnement et la taille du contexte, offrant de nouvelles perspectives et possibilités. Je pouvais adapter presque deux mille lignes de code dans la fenêtre de contexte, et les résultats se sont améliorés. Je pouvais écrire des fonctionnalités entières en quelques itérations, et j'ai été impressionné par la rapidité avec laquelle je pouvais obtenir des résultats. J'étais convaincu que les LLM étaient l'avenir du codage, et je voulais en faire partie. Je crois fermement que l'IA ne nous remplacera pas encore. Mais nous assistera sous la forme d'assistants où les humains sont les experts encore en contrôle.

Mes premiers projets avec les LLM 🚀

J'ai commencé à écrire un module de recherche de chemin ROS pour un concours de robotique, à générer des fonctionnalités pour une application Flutter multiplateforme d'architecture propre, et j'ai créé une petite application Web pour suivre mes dépenses en Next.js. Le fait que j'ai construit cette petite application en une soirée, dans un framework que je n'avais jamais utilisé auparavant, a été un moment décisif pour moi ; les LLM n'étaient pas seulement des outils mais des multiplicateurs. J'ai développé bboxconverter, un package pour convertir des boîtes de bounding, et la liste continue. Les LLM peuvent vous aider à apprendre de nouvelles technologies et frameworks rapidement ; c'est incroyable.

Un nouveau paradigme : Software 3.0 💡

Je me suis approfondi dans les LLM et j'ai commencé à construire des agents et des squelettes autour d'eux. J'ai reproduit le célèbre article RestGPT. L'idée est excellente : donner aux LLM la capacité d'appeler certaines API REST avec une spécification OpenAPI, telles que Spotify ou TMDB. Ces capacités introduisent un nouveau paradigme de programmation logiciel, que j'aime appeler Software 3.0.

Software 1.0 Software 2.0 Software 3.0
Basé sur des règles Piloté par les données Agence

La même idée a propulsé le protocole MCP, qui permet aux LLM d'appeler des outils et des ressources directement de manière transparente, car par conception, l'outil a besoin d'une description pour être appelé par le LLM, contrairement aux API REST qui ne nécessitent pas nécessairement de spécification OpenAPI.

Les limitations des LLM 🧩

Hallucinations 🌀

Lors de la reproduction du célèbre article RESTGPT, j'ai remarqué certaines limitations graves des LLM. Les auteurs de l'article ont rencontré les mêmes problèmes que moi : les LLM hallucinaient. Ils génèrent du code qui n'est pas implémenté, inventant des arguments et suivant simplement les instructions à la lettre sans utiliser le bon sens. Par exemple, dans le code source original de RestGPT, les auteurs ont demandé dans l'invite de l'appelant.

"de ne pas être malin et d'inventer des étapes qui n'existent pas dans le plan."

J'ai trouvé cette déclaration amusante et très intéressante parce que c'était la première fois que je rencontrais quelqu'un qui instruisait les LLM à ne pas halluciner.

Taille de contexte limitée 📏

Une autre limitation était la taille du contexte ; les LLM performent bien pour trouver l'aiguille dans la botte de foin mais ont du mal à en comprendre le sens. Lorsque vous donnez trop de contexte aux modèles de langage, ils ont tendance à se perdre dans les détails et à perdre de vue l'ensemble, ce qui est ennuyeux et nécessite une direction constante. La façon dont j'aime y penser est similaire à la malédiction de la dimensionnalité. Remplacez le mot "dimension" ou "fonctionnalité" par "contexte", et vous obtenez l'idée.

Plus vous donnez de contexte au LLM, plus il est difficile de trouver la bonne réponse. J'ai créé une phrase agréable pour résumer cette idée :

Fournissez aussi peu de contexte que possible mais autant que nécessaire

Ceci est fortement inspiré par la célèbre citation d'Alain Berset, un politicien suisse 🇨🇭 qui a déclaré pendant le confinement COVID-19 :

"Nous souhaitons agir aussi vite que possible, mais aussi lentement que nécessaire"

Cela représente l'idée de compromis et s'applique à la taille du contexte des LLM !

Recherche d'une meilleure façon : code2prompt 🔨

Par conséquent, j'avais besoin d'un moyen de charger, de filtrer et d'organiser rapidement mon contexte de code en fournissant la moindre quantité possible de contexte avec la meilleure qualité possible. J'ai essayé de copier manuellement des fichiers ou des extraits dans des invites, mais cela est devenu encombrant et sujet aux erreurs. Je savais que l'automatisation du processus fastidieux de forgeage du contexte pour poser de meilleures questions serait utile. Ensuite, un jour, j'ai tapé "code2prompt" sur Google, espérant trouver un outil qui acheminait mon code directement dans des invites.

Et voici ! J'ai découvert un projet basé sur Rust de Mufeed nommé code2prompt, qui comptait environ 200 étoiles sur GitHub. C'était encore basique à l'époque : un simple outil CLI avec une capacité de filtration limitée et des modèles. J'ai vu un énorme potentiel et j'ai sauté directement pour contribuer, en mettant en œuvre la correspondance de modèles globaux, entre autres fonctionnalités, et je suis rapidement devenu le principal contributeur.

Vision & Intégrations 🔮

Aujourd'hui, il existe plusieurs façons de fournir du contexte aux LLM. Générer à partir du contexte plus large, utiliser la génération augmentée de récupération (RAG), compresser le code, ou même utiliser une combinaison de ces méthodes. Le forgeage de contexte est un sujet brûlant qui évoluera rapidement dans les prochains mois. Cependant, mon approche est KISS : Keep It Simple, Stupid. La meilleure façon de fournir du contexte aux LLM est d'utiliser la façon la plus simple et la plus efficace possible. Vous forgez précisément le contexte dont vous avez besoin ; c'est déterministe, contrairement à RAG.

C'est pourquoi j'ai décidé de pousser code2prompt plus loin en tant qu'outil simple pouvant être utilisé dans n'importe quel flux de travail. Je voulais le rendre facile à utiliser, facile à intégrer et facile à étendre. C'est pourquoi j'ai ajouté de nouvelles façons d'interagir avec l'outil.

  • Core : Le cœur de code2prompt est une bibliothèque Rust qui fournit la fonctionnalité de base pour forger le contexte à partir de votre base de code. Il comprend une API simple pour charger, filtrer et organiser votre contexte de code.
  • CLI : L'interface de ligne de commande est la façon la plus simple d'utiliser code2prompt. Vous pouvez forger le contexte à partir de votre base de code et le canaliser directement dans vos invites.
  • API Python : L'API Python est un simple wrapper autour de CLI qui vous permet d'utiliser code2prompt dans vos scripts et agents Python. Vous pouvez forger le contexte à partir de votre base de code et le canaliser directement dans vos invites.
  • MCP : Le serveur MCP code2prompt permet aux LLM d'utiliser code2prompt en tant qu'outil, les rendant ainsi capables de forger le contexte.

La vision est décrite plus en détail dans la page de vision de la documentation.

Intégration avec les agents 👤

Je crois que les futurs agents auront besoin d'un moyen d'ingérer du contexte, et code2prompt est la façon simple et efficace de le faire pour les référentiels textuels comme la base de code, la documentation ou les notes. Un endroit typique pour utiliser code2prompt serait dans une base de code avec des conventions de dénomination significatives. Par exemple, dans l'architecture propre, il existe une séparation claire des préoccupations et des couches. Le contexte pertinent réside généralement dans différents fichiers et dossiers mais partage le même nom. C'est un cas d'utilisation parfait pour code2prompt, où vous pouvez utiliser le modèle global pour saisir les fichiers pertinents.

Basé sur le modèle global : Sélectionnez ou excluez précisément les fichiers avec un minimum de tracas.

En outre, la bibliothèque principale est conçue en tant que gestionnaire de contexte étatique, vous permettant d'ajouter ou de supprimer des fichiers à mesure que votre conversation avec le LLM évolue. Ceci est particulièrement utile pour fournir du contexte pour une tâche ou un objectif spécifique. Vous pouvez facilement ajouter ou supprimer des fichiers du contexte sans relancer le processus.

Contexte étatique : Ajoutez ou supprimez des fichiers à mesure que votre conversation avec le LLM évolue.

Ces capacités font de code2prompt un choix parfait pour les flux de travail basés sur des agents. Le serveur MCP permet une intégration transparente avec des frameworks d'agents IA populaires tels que Aider, Goose, ou Cline. Laissez-les gérer des objectifs complexes pendant que code2prompt fournit le contexte de code parfait.

Pourquoi Code2prompt compte ✊

À mesure que les LLM évoluent et que les fenêtres de contexte s'étendent, il peut sembler que simplement forcer des référentiels entiers dans des invites suffit. Cependant, les coûts de jetons et la cohérence des invites restent des obstacles importants pour les petites entreprises et les développeurs. En se concentrant sur le code qui compte, code2prompt maintient votre utilisation de LLM efficace, rentable et moins encline à l'hallucination.

En bref :

  • Réduire les hallucinations en fournissant la bonne quantité de contexte
  • Réduire les coûts de jetons en curant manuellement le contexte approprié nécessaire
  • Améliorer les performances de LLM en donnant la bonne quantité de contexte
  • Intègre la pile agence en tant que fournisseur de contexte pour les référentiels textuels

Vous pouvez rejoindre ! C'est Open Source ! 🌐

Tout nouveau contributeur est le bienvenu ! Venez à bord si vous êtes intéressé par Rust, la création d'outils IA innovants, ou si vous voulez simplement un meilleur flux de travail pour vos invites basées sur le code.

Merci de lire, et j'espère que mon histoire vous a inspiré à découvrir code2prompt. C'est un incroyable voyage, et cela ne fait que commencer !

Olivier D'Ancona

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Vision (`website/src/content/docs/fr/docs/vision.mdx`)


title: La vision de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` a été créé pour aider les développeurs et les agents IA à interagir avec les bases de code de manière plus efficace.

Le problème 🚩

Les modèles de langage à grande échelle (LLM) ont révolutionné la façon dont nous interagissons avec le code. Cependant, ils font encore face à des défis importants en matière de génération de code :

  • Planification et raisonnement : Les LLM manquent de capacité de planification et de raisonnement, qui est cruciale pour des tâches telles que la génération de code, la refactorisation et le débogage. Ils ont souvent du mal à avoir une vue d'ensemble et sont shortsightés.
  • Taille du contexte : Les LLM ont une fenêtre de contexte limitée, ce qui restreint leur capacité à analyser et à comprendre de grandes bases de code.
  • Hallucination : Les LLM peuvent générer du code qui semble correct mais est en réalité incorrect ou absurde. Ce phénomène, appelé hallucination, se produit lorsque le modèle manque de contexte suffisant ou de compréhension de la base de code.

C'est là que code2prompt intervient.

La solution ✅

Nous pensons que la planification et le raisonnement peuvent être atteints par des humains ou des agents IA avec des techniques de scaffolding. Ces agents doivent collecter un contexte de haute qualité de la base de code qui est filtré, structuré et formaté pour la tâche à accomplir.

La règle générale serait :

Ceci est pratiquement difficile à atteindre, surtout pour de grandes bases de code. Cependant, code2prompt est un outil simple qui peut aider les développeurs et les agents IA à ingérer la base de code de manière plus efficace.

Il automatise le processus de parcours d'une base de code, de filtrage de fichiers et de formatage en invites structurées que les LLM peuvent comprendre. Ce faisant, il aide à atténuer les défis de planification, de raisonnement et d'hallucination.

Vous pouvez comprendre comment code2prompt est conçu pour relever ces défis dans la section suivante.

Architecture ⛩️

code2prompt est conçu de manière modulaire, permettant une intégration facile dans divers flux de travail. Il peut être utilisé comme une bibliothèque principale, une interface de ligne de commande (CLI), un kit de développement logiciel (SDK) ou même comme un serveur de protocole de contexte de modèle (MCP).

Principal

code2prompt est un outil d'ingestion de code qui simplifie le processus de création d'invites LLM pour l'analyse de code, la génération et d'autres tâches. Il fonctionne en parcourant les répertoires, en construisant une structure arborescente et en collectant des informations sur chaque fichier. La bibliothèque principale peut être facilement intégrée dans d'autres applications.

CLI

L'interface de ligne de commande (CLI) de code2prompt a été conçue pour que les humains génèrent des invites directement à partir de votre base de code. L'invite générée est automatiquement copiée dans votre presse-papiers et peut également être enregistrée dans un fichier de sortie. De plus, vous pouvez personnaliser la génération d'invites à l'aide de modèles Handlebars. Consultez les invites fournies dans la documentation !

SDK

Le kit de développement logiciel (SDK) de code2prompt offre une liaison Python à la bibliothèque principale. Ceci est parfait pour les agents IA ou les scripts d'automatisation qui souhaitent interagir avec la base de code de manière transparente. Le SDK est hébergé sur Pypi et peut être installé via pip.

MCP

code2prompt est également disponible en tant que serveur de protocole de contexte de modèle (MCP), ce qui vous permet de l'exécuter en tant que service local. Cela permet aux LLM de fournir un outil pour collecter automatiquement un contexte bien structuré de votre base de code.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Welcome (`website/src/content/docs/fr/docs/welcome.mdx`)


title: Documentation Code2Prompt
template: splash
hero:
tagline: Transformez votre code en invites optimisées pour l'IA en secondes
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: Commencer 🚀
link: ../../docs/tutorials/getting_started
- text: Installation 📥
link: ../../docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Démarrage rapide

code2prompt est un outil puissant d'ingestion de code conçu pour générer des invites pour l'analyse de code, la génération et d'autres tâches. Il fonctionne en parcourant les répertoires, en construisant une structure d'arbre et en collectant des informations sur chaque fichier.

Il simplifie le processus de combinaison et de formatage du code, facilitant l'analyse, la documentation ou la refactorisation du code à l'aide de LLMs.

Vous pouvez utiliser code2prompt de les manières suivantes :

Bibliothèque centrale extrêmement rapide pour l'ingestion de code Interface de ligne de commande spécialement conçue pour les humains Kit de développement logiciel pour les agents d'IA et les scripts d'automatisation Serveur de protocole de contexte de modèle pour LLMs sur steroids

Fonctionnalités clés

  • Générer des invites LLM : Convertissez rapidement des bases de code entières en invites structurées LLM.
  • Filtrage par modèle Glob : Incluez ou excluez des fichiers et des répertoires spécifiques à l'aide de modèles Glob.
  • Modèles personnalisables : Adaptez la génération d'invites avec des modèles Handlebars.
  • Comptage des jetons : Analysez l'utilisation des jetons et optimisez pour les LLMs avec des fenêtres de contexte variables.
  • Intégration Git : Incluez les différences Git et les messages de commit dans les invites pour les revues de code.
  • Respecte .gitignore : Ignore automatiquement les fichiers répertoriés dans .gitignore pour rationaliser la génération d'invites.

Pourquoi `code2prompt` ?

  1. Gagner du temps :

    • Automatise le processus de parcours d'une base de code et de formatage des fichiers pour les LLMs.
    • Évite la copie et le collage répétitifs de code.
  2. Améliorer la productivité :

    • Fournit un format structuré et cohérent pour l'analyse de code.
    • Aide à identifier les bogues, à refactoriser le code et à écrire la documentation plus rapidement.
  3. Gérer de grandes bases de code :

    • Conçu pour fonctionner de manière transparente avec de grandes bases de code, en respectant les limites de contexte des LLMs.
  4. Workflows personnalisables :

    • Options flexibles pour filtrer les fichiers, utiliser des modèles et générer des invites ciblées.

Exemples de cas d'utilisation

  • Documentation de code :
    Générez automatiquement de la documentation pour les fonctions publiques, les méthodes et les classes.

  • Détection de bogues :
    Recherchez les bogues et les vulnérabilités potentiels en analysant votre base de code avec les LLMs.

  • Refactorisation :
    Simplifiez et optimisez le code en générant des invites pour améliorer la qualité du code.

  • Apprentissage et exploration :
    Comprenez de nouvelles bases de code en générant des résumés et des ventilations détaillées.

  • Descriptions de commit Git et de PR :
    Générez des messages de commit significatifs et des descriptions de demandes de tirage à partir des différences Git.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Ja Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/ja/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Code2Prompt を開発した理由"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • AI
  • Agent
    excerpt: "code2prompt の裏側: LLM ワークフローのコンテキスト課題に取り組むためのオープンソースの探求"
    authors:
  • ODAncona
    cover:
    alt: "code2prompt が AI エージェントのためのコードコンテキストを合理化するイラスト"
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

はじめに

私は、Large Language Models (LLMs) がコーディングワークフローをどのように変革するか、テストやドキュメント文字列の生成、さらには数分で機能を出荷することに興味を持っています。しかし、これらのモデルをさらに押し進めるにつれて、いくつかの重要な課題が表面化しました。

計画の困難さ 高いトークンコスト 幻覚
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

そこで、私は code2prompt に貢献し始めました。これは、Rust ベースのツールで、LLM に適切なコンテキストを供給するのに役立ちます。

この投稿では、私の旅を共有し、なぜ code2prompt が今日の関連性があり、統合が簡単で、私の頼りになるソリューションになったのかを説明します。

LLM との最初のステップ 👣

私は 2023 年 11 月に OpenAI Playground で text-davinci-003 を使って LLM を実験し始めました。言語モデルは新しい革命をもたらしました。優れた新しいアシスタントが、ほぼコマンドに従って単体テストやドキュメント文字列を生成するように感じました。私はモデルを限界まで押し上げ、小さな会話から倫理的なジレンマ、脱獄、そして複雑なコーディングタスクまで、すべてをテストしました。しかし、より大規模なプロジェクトに取り組むにつれて、モデルには明らかな限界があることにすぐに気付きました。最初は、コンテキストウィンドウに数百行のコードしか収められず、モデルはコードの目的や構造を理解するのに苦労することがよくありました。そのため、コンテキストの重要性が極めて高いことにすぐに気付きました。より簡潔な命令とより良いコンテキストが、結果をより良くするのです。

モデルの進化 🏗️

モデルは印象的な結果を生み出しましたが、より大きなコードベースや複雑なタスクでは苦労することがよくありました。私は、プロンプトを作成することに多くの時間を費やすよりも、実際にコーディングすることに多くの時間を費やしていることに気付きました。同時に、モデルは新しいバージョンのリリースとともに改善を続け、推論能力とコンテキストサイズが向上し、新しい視点や可能性が広がりました。その後、コンテキストウィンドウにほぼ 2000 行のコードを収めることができ、結果が向上しました。数回の反復で機能全体を記述することができ、結果が得られる速度に驚かされました。私は、LLM がコーディングの未来であると確信し、その革命の一部になりたいと考えました。

LLM による最初のプロジェクト 🚀

私は、ロボット競技用の ROS パスファインディングモジュールを作成し、クリーンアーキテクチャの Flutter クロスプラットフォームアプリの機能を生成し、Next.js で小さなウェブアプリを作成して経費を管理しました。私は、見慣れないフレームワークでこの小さなアプリを 1 日で構築できたことが、大きな転換点となりました。LLM は単なるツールではなく、乗数であることを実感しました。私は、bboxconverter というバウンディングボックスを変換するパッケージを開発し、他にも多くのプロジェクトを行いました。LLM は、新しいテクノロジーやフレームワークを迅速に学ぶのに役立ちます。

新しいパラダイム: Software 3.0 💡

私は、LLM をさらに深く掘り下げ、エージェントや足場を構築し始めました。私は、RestGPT という有名な論文を再現しました。アイデアは素晴らしいものでした。LLM に OpenAPI 仕様のある REST API を呼び出す能力を与えることです。Spotify や TMDB のような。これらの機能は、Software 3.0 と呼ぶ新しいソフトウェアプログラミングパラダイムを導入します。

Software 1.0 Software 2.0 Software 3.0
ルールベース データ駆動型 エージェント型

同じアイデアが MCP プロトコルを推進しました。このプロトコルにより、LLM はツールやリソースを直接呼び出すことができます。

LLM の限界 🧩

幻覚 🌀

私は、RestGPT の有名な論文を再現しながら、LLM の深刻な限界に気付きました。論文の著者も私と同じ問題に遭遇しました。LLM は 幻覚 を起こしていました。実装されていないコードを生成し、引数をでっち上げ、単に命令に従うだけで、常識を働かせませんでした。

コンテキストサイズの制限 📏

もう 1 つの限界はコンテキストサイズでした。LLM は、針を見つけることは得意ですが、意味を理解するのは苦手です。言語モデルにコンテキストを多く与えすぎると、詳細に迷い込み、全体像を見失いがちになります。

コンテキストを増やすと、LLM が正しい答えを見つけるのが難しくなります。私たちは、コンテキストサイズに関して妥協点を見つける必要があります。

より良い方法の探求: code2prompt 🔨

そこで、私はコードコンテキストを迅速にロード、フィルタリング、整理する方法を必要としました。ファイルを手動でコピーしたり、スニペットをプロンプトに貼り付けたりしていましたが、これは煩雑でエラーが発生しやすい作業でした。そこで、私はコンテキストを自動化するツールを探し始めました。そして、ある日、Google で "code2prompt" を検索したところ、Mufeed による Rust ベースのプロジェクト を見つけました。このプロジェクトは約 200 個のスターを獲得していました。当時は基本的な CLI ツールでしたが、フィルター機能やテンプレートは限られていました。私は大きな可能性を感じ、すぐにコントリビューターになりました。

ビジョンと統合 🔮

今日、LLM にコンテキストを提供する方法はたくさんあります。より大きなコンテキストから生成したり、Retrieval-Augmented Generation (RAG) を使用したり、コードを圧縮したり、これらの手法の組み合わせを使用したりできます。コンテキストの構築はホットトピックであり、今後数ヶ月で急速に進化するでしょう。しかし、私のアプローチは KISS です。Keep It Simple, Stupid です。LLM にコンテキストを提供する最も簡単で効率的な方法は、必要に応じてコンテキストを正確に構築することです。これは RAG とは異なり、決定論的です。

エージェントとの統合 👤

私は、将来のエージェントはコンテキストを摂取する方法を必要とし、 code2prompt はそれを行う簡単で効率的な方法であると信じています。コードベースやドキュメント、メモなどのテキストリポジトリに最適です。 code2prompt を使用するのに最適な場所は、意味のある名前の規約があるコードベースです。たとえば、クリーンアーキテクチャでは、関心の分離とレイヤーが明確に分かれています。関連するコンテキストは通常、異なるファイルやフォルダーにありますが、同じ名前を共有します。

Glob パターン優先: ファイルを選択または除外するのが簡単です。

さらに、コアライブラリはステートフルコンテキストマネージャーとして設計されており、会話が進むにつれてファイルを追加または削除できます。これは、特定のタスクや目標のためのコンテキストを提供する場合に特に便利です。

ステートフルコンテキスト: 会話が進むにつれてファイルを追加または削除できます。

これらの機能により、 code2prompt はエージェントベースのワークフローの最適なツールになります。MCP サーバーを使用すると、Aider や Goose などの人気のある AI エージェントフレームワークとシームレスに統合できます。

Code2prompt が重要な理由 ✊

LLM が進化し、コンテキストウィンドウが拡大するにつれて、リポジトリ全体をプロンプトに強制的に押し込むだけで十分であるように思えるかもしれません。しかし、トークンコスト と プロンプトの一貫性 は依然として、小規模な企業や開発者にとって大きな障害です。重要なコードに焦点を当てることで、 code2prompt は LLM の使用を効率的でコスト効果が高く、幻覚を起こしにくくします。

要するに:

  • 幻覚を減らす ことで、適切な量のコンテキストを提供します。
  • トークン使用コストを減らす ことで、適切なコンテキストを手動でキュレートします。
  • LLM のパフォーマンスを向上させる ことで、適切な量のコンテキストを提供します。
  • テキストリポジトリ用のコンテキストフィーダーとして、エージェントスタックと統合します。

オープンソースです! 🌐

新しいコントリビューターは大歓迎です! Rust や革新的な AI ツールの構築に興味がある場合、またはコードベースのプロンプト用のより優れたワークフローを探している場合は、ぜひ参加してください。

このブログ投稿を最後まで読んでいただき、私のストーリーが code2prompt をチェックするきっかけになれば幸いです。

Olivier D'Ancona

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Vision (`website/src/content/docs/ja/docs/vision.mdx`)


title: Code2Promptのビジョン

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt`は、開発者とAIエージェントがコードベースと効果的に相互作用できるように支援するために作成されました。

問題点 🚩

大規模言語モデル(LLM)は、コードとのインタラクション方法に革命をもたらしました。しかし、コード生成に関しては、まだ大きな課題に直面しています。

  • 計画と推論: LLMには計画と推論能力が欠けており、コード生成、リファクタリング、デバッグなどのタスクに不可欠です。彼らは全体像を把握するのに苦労することが多く、近視眼的です。
  • コンテキストサイズ: LLMには限られたコンテキストウィンドウがあり、大きなコードベースを分析して理解する能力を制限します。
  • 幻覚: LLMは、正しいように見えるが、実際には正しくない、または意味をなさないコードを生成することがあります。この現象は、モデルがコードベースのコンテキストまたは理解を十分に持っていない場合に発生する幻覚と呼ばれます。

この問題を解決するために、code2promptがあります。

解決策 ✅

私たちは、計画と推論は、足場技術を使用することで、人間またはAIエージェントによって達成できると信じています。これらのエージェントは、タスクに適したフィルター処理された構造化されたフォーマットされた高品質のコンテキストを収集する必要があります。

経験則は次のとおりです。

これは、特に大きなコードベースの場合、実際に困難です。しかし、code2promptは、開発者とAIエージェントがコードベースをより効果的に吸収できるように支援するシンプルなツールです。

これにより、コードベースのトラバース、ファイルのフィルタリング、LLMが理解できる構造化されたプロンプトへのフォーマットを自動化します。これにより、計画、推論、幻覚の課題を軽減できます。

次のセクションでは、code2promptがこれらの課題にどのように取り組むように設計されているかを理解できます。

アーキテクチャ ⛩️

code2promptはモジュール式に設計されており、さまざまなワークフローへの簡単な統合を可能にします。コアライブラリ、コマンドラインインターフェイス(CLI)、ソフトウェア開発キット(SDK)、またはモデルコンテキストプロトコル(MCP)サーバーとして使用できます。

コア

code2promptは、コード分析、生成、その他のタスクのためのLLMプロンプトを作成するプロセスを合理化するコード吸収ツールです。ディレクトリをトラバースし、ツリー構造を構築し、各ファイルに関する情報を収集することで動作します。コアライブラリは、他のアプリケーションに簡単に統合できます。

CLI

code2promptコマンドラインインターフェイス(CLI)は、コードベースからプロンプトを直接生成するために人間が使用できるように設計されています。生成されたプロンプトは自動的にクリップボードにコピーされ、出力ファイルに保存することもできます。さらに、Handlebarsテンプレートを使用してプロンプト生成をカスタマイズできます。ドキュメントに提供されているプロンプトを確認してください。

SDK

code2promptソフトウェア開発キット(SDK)は、コアライブラリへのPythonバインディングを提供します。これは、コードベースとシームレスに相互作用したいAIエージェントまたは自動化スクリプトに最適です。SDKはPypiにホストされており、pip経由でインストールできます。

MCP

code2promptは、モデルコンテキストプロトコル(MCP)サーバーとしても利用でき、ローカルサービスとして実行できます。これにより、LLMにコードベースの構造化されたコンテキストを自動的に収集するツールを提供することで、LLMを強化できます。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Welcome (`website/src/content/docs/ja/docs/welcome.mdx`)


title: Code2Prompt Documentation
template: splash
hero:
tagline: コードをAI最適化されたプロンプトに数秒で変換する
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: 始める 🚀
link: /docs/tutorials/getting_started
- text: インストール 📥
link: /docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

クイックスタート

code2promptは、コード分析、生成、その他のタスクのためのプロンプトを生成するように設計された強力なコードインジェストツールです。ディレクトリをトラバースし、ツリー構造を構築し、各ファイルに関する情報を収集することで動作します。

LLMを使用したコードの分析、ドキュメント化、リファクタリングを容易にするために、コードの結合とフォーマットを簡素化します。

以下の方法でcode2promptを使用できます:

コードインジェストのためのコアライブラリ 人間向けに特別に設計されたコマンドラインインターフェース AIエージェントと自動化スクリプトのためのソフトウェア開発キット 強力なLLMのためのモデルコンテキストプロトコルサーバー

主な機能

  • LLMプロンプトの生成: 構造化されたLLMプロンプトにコードベース全体を迅速に変換します。
  • グロブパターンによるフィルタリング: グロブパターンを使用して特定のファイルやディレクトリを含めたり除外したりします。
  • カスタマイズ可能なテンプレート: Handlebarsテンプレートを使用してプロンプト生成を調整します。
  • トークンカウント: トークン使用量を分析し、コンテキストウィンドウが異なるLLMを最適化します。
  • Git統合: コードレビューのためにGitの差分とコミットメッセージをプロンプトに含めます。
  • .gitignoreを尊重: .gitignoreにリストされたファイルを自動的に無視してプロンプト生成を合理化します。

なぜ`code2prompt`?

  1. 時間を節約:

    • コードベースをトラバースし、LLM用のファイルをフォーマットするプロセスを自動化します。
    • コードのコピーと貼り付けを繰り返す必要がなくなります。
  2. 生産性を向上:

    • コード分析のための構造化された一貫したフォーマットを提供します。
    • バグの特定、コードのリファクタリング、ドキュメントの作成を迅速に行うことができます。
  3. 大規模なコードベースの処理:

    • 大規模なコードベースでシームレスに動作するように設計されており、LLMのコンテキスト制限を尊重します。
  4. カスタマイズ可能なワークフロー:

    • ファイルのフィルタリング、テンプレートの使用、ターゲットプロンプトの生成のための柔軟なオプション。

使用例

  • コードドキュメント:
    公開関数、メソッド、クラスのドキュメントを自動生成します。

  • バグ検出:
    コードベースをLLMで分析して潜在的なバグや脆弱性を検出します。

  • リファクタリング:
    コード品質の向上のためのプロンプトを生成してコードを簡素化および最適化します。

  • 学習と探索:
    サマリや詳細な内訳を生成して新しいコードベースを理解します。

  • GitコミットとPRの説明:
    Gitの差分から意味のあるコミットメッセージとプルリクエストの説明を生成します。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ru Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/ru/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "Почему я разработал Code2Prompt"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • open-source
  • code2prompt
  • AI
  • Agent
    excerpt: "История создания code2prompt: мой путь к открытому исходному коду для решения проблем контекста в рабочих процессах LLM"
    authors:
  • ODAncona
    cover:
    alt: "Иллюстрация code2prompt, оптимизирующая контекст кода для агентов ИИ."
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

Введение

Меня всегда увлекало, как большие языковые модели (LLM) преобразуют рабочие процессы кодирования — генерируют тесты, комментарии или даже реализуют целые функции за считанные минуты. Но когда я глубже погрузился в эти модели, выявились несколько критических проблем:

Трудности планирования Высокие затраты на токены Галлюцинации
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

Именно поэтому я начал работать над code2prompt, инструментом на основе Rust, который помогает подавать в LLM именно тот контекст, который необходим.

В этом посте я поделюсь своей историей и объясню, почему я убежден, что code2prompt актуален сегодня и прекрасно интегрируется, и почему он стал моим основным решением для более быстрых и эффективных рабочих процессов кодирования с ИИ.

Первые шаги с LLM 👣

Я начал экспериментировать с LLM в OpenAI Playground с text-davinci-003, когда он приобрел популярность в ноябре 2023 года. Языковые модели открыли новую революцию. Это было похоже на наличие блестящего нового помощника, который мог генерировать单元-тесты и комментарии почти по команде. Я наслаждался тестированием моделей на их пределах — проверкой всего, от небольших разговоров и этических дилемм до jailbreaks и сложных задач кодирования. Однако, когда я взялся за более крупные проекты, я быстро осознал, что модели имеют явные ограничения. Сначала я мог поместить в окно контекста только несколько сотен строк кода, и даже тогда модели часто с трудом понимали назначение или структуру кода. Именно поэтому я быстро осознал, что важность контекста имеет первостепенное значение. Чем более краткими были мои инструкции и лучше контекст, тем лучше результаты.

Эволюция моделей 🏗️

Модели могли производить впечатляющие результаты, но часто испытывали трудности с более крупными кодовыми базами или сложными задачами. Я обнаружил, что трачу больше времени на создание подсказок, чем на фактическое кодирование. В то же время модели продолжали улучшаться с выпуском новых версий. Они увеличивали способности рассуждения и размер контекста, предлагая новые перспективы и возможности. Я мог поместить в окно контекста почти две тысячи строк кода, и результаты улучшились. Я мог написать целые функции за несколько итераций, и меня поразило, как быстро я мог получить результаты. Я был убежден, что LLM — это будущее кодирования, и я хотел быть частью этой революции. Я твердо верю, что ИИ не заменит нас пока. Но будет помогать нам в качестве помощников, где люди по-прежнему являются экспертами и контролируют ситуацию.

Мои первые проекты с LLM 🚀

Я начал писать модуль поиска пути ROS для роботизированного соревнования, генерировать функции для кроссплатформенного приложения Flutter с чистой архитектурой и создал небольшое веб-приложение для отслеживания расходов в Next.js. Тот факт, что я создал это небольшое приложение за один вечер, в фреймворке, с которым я никогда не работал раньше, был поворотным моментом для меня; LLM были не просто инструментами, но и умножителями. Я разработал bboxconverter, пакет для преобразования ограничивающих рамок, и список продолжается. LLM могут помочь вам быстро изучить новые технологии и фреймворки; это потрясающе.

Новый парадигма: Software 3.0 💡

Я глубже погрузился в LLM и начал создавать агентов и скелеты вокруг них. Я повторил известную статью RestGPT. Идея отличная: дать LLM возможность вызывать некоторые REST API с помощью спецификации OpenAPI, такие как Spotify или TMDB. Эти возможности вводят новый парадигму программирования программного обеспечения, который я называю Software 3.0.

Software 1.0 Software 2.0 Software 3.0
На основе правил На основе данных Агентный

Та же идея привела к протоколу MCP, который позволяет LLM вызывать инструменты и ресурсы напрямую бесшовным образом, потому что по дизайну инструмент нуждается в описании, чтобы быть вызванным LLM, в отличие от REST API, который не обязательно требует спецификации OpenAPI.

Ограничения LLM 🧩

Галлюцинации 🌀

При повторении известной статьи RESTGPT я заметил некоторые серьезные ограничения LLM. Авторы статьи столкнулись с теми же проблемами, что и я: LLM галлюцинировали. Они генерируют код, который не реализован, изобретая аргументы и просто следуя инструкциям буквально без использования здравого смысла. Например, в исходном коде RestGPT авторы спросили в подсказке вызывающего.

"не быть слишком умным и не придумывать шаги, которых нет в плане."

Я нашел это заявление забавным и очень интересным, потому что это был первый раз, когда я встретил кого-то, кто инструктирует LLM не галлюцинировать.

Ограниченный размер контекста 📏

Другим ограничением был размер контекста; LLM хорошо справляются с поиском иголки в стоге сена, но с трудом понимают его. Когда вы даете слишком много контекста языковым моделям, они склонны теряться в деталях и теряют из виду общую картину, что раздражает и требует постоянного управления. Способ, которым я люблю думать об этом, похож на проклятие размерности. Замените слово "размерность" или "функция" на "контекст", и вы получите идею.

Чем больше контекста вы даете LLM, тем труднее найти правильный ответ. Я придумал nice предложение, чтобы суммировать эту идею:

Предоставьте как можно меньше контекста, но как можно больше, чем необходимо

Это heavily вдохновлено известным цитатой Alain Berset, швейцарского политика 🇨🇭, который сказал во время карантина COVID-19:

"Мы хотим действовать как можно быстрее, но и как можно медленнее, когда это необходимо"

Это представляет идею компромисса и применяется к размеру контекста LLM!

Поиск лучшего способа: code2prompt 🔨

Следовательно, мне нужен был способ быстро загружать, фильтровать и организовывать контекст моего кода, предоставляя как можно меньше контекста с лучшим качеством. Я попробовал вручную копировать файлы или фрагменты в подсказки, но это стало неудобным и подверженным ошибкам. Я знал, что автоматизация tedious процесса создания контекста для запросов лучших подсказок будет полезна. Затем, однажды, я ввел "code2prompt" в Google, надеясь найти инструмент, который напрямую подключает мой код к подсказкам.

И, voilà, я обнаружил проект на основе Rust Mufeed под названием code2prompt, который имеет около 200 звезд на GitHub. Это было еще просто на тот момент: простой инструмент CLI с базовой ограниченной емкостью фильтрации и шаблонами. Я увидел огромный потенциал и сразу же присоединился к нему, реализовав совпадение шаблонов glob, среди других функций, и вскоре стал основным участником.

Видение и интеграции 🔮

Сегодня существует несколько способов предоставить контекст LLM. Генерация из более крупного контекста, использование генерации на основе извлечения (RAG), сжатие кода, или даже использование комбинации этих методов. Создание контекста — это горячая тема, которая будет быстро развиваться в ближайшие месяцы. Однако, мой подход — KISS: Keep It Simple, Stupid. Лучший способ предоставить контекст LLM — использовать самый простой и эффективный способ. Вы создаете именно тот контекст, который вам нужен; это детерминировано, в отличие от RAG.

Именно поэтому я решил продвинуть code2prompt дальше как простой инструмент, который можно использовать в любом рабочем процессе. Я хотел сделать его легким в использовании, легким в интеграции и легким в расширении. Именно поэтому я добавил новые способы взаимодействия с инструментом.

  • Core: Ядро code2prompt — это библиотека Rust, которая предоставляет базовую функциональность для создания контекста из вашей кодовой базы. Она включает в себя простой API для загрузки, фильтрации и организации контекста вашего кода.
  • CLI: Интерфейс командной строки — это самый простой способ использования code2prompt. Вы можете создать контекст из вашей кодовой базы и напрямую подключить его к вашим подсказкам.
  • Python API: Python API — это простой wrapper вокруг CLI, который позволяет вам использовать code2prompt в ваших Python-скриптах и агентах. Вы можете создать контекст из вашей кодовой базы и напрямую подключить его к вашим подсказкам.
  • MCP: Сервер code2prompt MCP позволяет LLM использовать code2prompt как инструмент, тем самым делая их способными создавать контекст.

Видение описано дальше на странице видения в документации.

Интеграция с агентами 👤

Я считаю, что будущие агенты будут нуждаться в способе потреблять контекст, и code2prompt — это простой и эффективный способ сделать это для текстовых репозиториев, таких как кодовая база, документация или заметки. Типичное место для использования code2prompt будет в кодовой базе с осмысленными соглашениями об именовании. Например, в чистой архитектуре есть четкое разделение проблем и слоев. Соответствующий контекст обычно resides в разных файлах и папках, но имеет одно и то же имя. Это идеальный случай использования code2prompt, где вы можете использовать шаблон glob для захвата соответствующих файлов.

На основе шаблонов glob: Точно выберите или исключите файлы с минимальными усилиями.

Кроме того, основная библиотека разработана как менеджер контекста с состоянием, позволяя вам добавлять или удалять файлы по мере развития вашего разговора с LLM. Это особенно полезно при предоставлении контекста для конкретной задачи или цели. Вы можете легко добавлять или удалять файлы из контекста без повторного запуска процесса.

Состояние контекста: Добавляйте или удаляйте файлы по мере развития вашего разговора с LLM.

Эти возможности делают code2prompt идеальным выбором для рабочих процессов на основе агентов. Сервер MCP позволяет бесшовную интеграцию с популярными фреймворками ИИ-агентов, такими как Aider, Goose, или Cline. Пусть они обрабатывают сложные цели, а code2prompt доставляет идеальный контекст кода.

Почему Code2prompt имеет значение ✊

По мере того, как LLM развиваются и окна контекста расширяются, может показаться, что просто форсирование всех репозиториев в подсказки достаточно. Однако стоимость токенов и согласованность подсказок остаются значительными препятствиями для небольших компаний и разработчиков. Сосредоточившись на коде, который имеет значение, code2prompt делает ваше использование LLM эффективным, экономичным и менее подверженным галлюцинациям.

Вкратце:

  • Уменьшите галлюцинации, предоставляя правильное количество контекста
  • Уменьшите стоимость токенов, тщательно создавая необходимый контекст
  • Улучшите производительность LLM, предоставляя правильное количество контекста
  • Интегрируется со стеком агентов как поставщик контекста для текстовых репозиториев

Вы можете присоединиться! 🌐

Каждый новый участник приветствуется! Присоединяйтесь, если вы заинтересованы в Rust, создании инновационных инструментов ИИ или просто хотите лучший рабочий процесс для ваших кодовых подсказок.

Спасибо за чтение, и я надеюсь, что моя история вдохновила вас проверить code2prompt. Это было невероятное путешествие, и оно только начинается!

Olivier D'Ancona

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Vision (`website/src/content/docs/ru/docs/vision.mdx`)


title: Видение Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` был создан для помощи разработчикам и агентам ИИ более эффективно взаимодействовать с кодовыми базами.

Проблема 🚩

Большие языковые модели (LLM) революционизировали способ взаимодействия с кодом. Однако они все еще сталкиваются с существенными проблемами при генерации кода:

  • Планирование и рассуждение: LLM не хватает способности планировать и рассуждать, что крайне важно для задач, таких как генерация кода, рефакторинг и отладка. Они часто испытывают трудности с пониманием общей картины и имеют ограниченный взгляд.
  • Размер контекста: LLM имеют ограниченное окно контекста, что ограничивает их способность анализировать и понимать большие кодовые базы.
  • Галлюцинация: LLM могут генерировать код, который выглядит правильным, но на самом деле является неверным или бессмысленным. Это явление, известное как галлюцинация, возникает, когда модель не имеет достаточного контекста или понимания кодовой базы.

Именно здесь вступает в действие code2prompt.

Решение ✅

Мы считаем, что планирование и рассуждение могут быть достигнуты человеком или агентами ИИ с помощью методов структурирования. Этим агентам необходимо собрать высококачественный контекст кодовой базы, который отфильтрован, структурирован и отформатирован для конкретной задачи.

Основное правило будет таким:

На практике это сложно достичь, особенно для больших кодовых баз. Однако code2prompt — это простой инструмент, который может помочь разработчикам и агентам ИИ более эффективно усваивать кодовую базу.

Он автоматизирует процесс обхода кодовой базы, фильтрации файлов и форматирования их в структурированные подсказки, которые могут понять LLM. Таким образом, он помогает смягчить проблемы планирования, рассуждения и галлюцинации.

Вы можете понять, как code2prompt предназначен для решения этих проблем, в следующем разделе.

Архитектура ⛩️

code2prompt разработан по модульному принципу, что позволяет легко интегрировать его в различные рабочие процессы. Его можно использовать в качестве основной библиотеки, интерфейса командной строки (CLI), набора средств разработки (SDK) или даже в качестве сервера протокола контекста модели (MCP).

Основная часть

code2prompt — это инструмент усвоения кода, который упрощает процесс создания подсказок LLM для анализа кода, генерации и других задач. Он работает, обходя директории, создавая древовидную структуру и собирая информацию о каждом файле. Основная библиотека может быть легко интегрирована в другие приложения.

CLI

Интерфейс командной строки code2prompt (CLI) был разработан для людей, чтобы генерировать подсказки непосредственно из вашей кодовой базы. Сгенерированная подсказка автоматически копируется в буфер обмена и может быть сохранена в выходной файл. Кроме того, вы можете настроить генерацию подсказок с помощью шаблонов Handlebars. Ознакомьтесь с предоставленными подсказками в документации!

SDK

Набор средств разработки code2prompt (SDK) предлагает привязку Python к основной библиотеке. Это идеально подходит для агентов ИИ или скриптов автоматизации, которые хотят взаимодействовать с кодовой базой беспрепятственно. SDK размещен на Pypi и может быть установлен с помощью pip.

MCP

code2prompt также доступен в качестве сервера протокола контекста модели (MCP), что позволяет запускать его в качестве локальной службы. Это позволяет LLM на стероидах, предоставляя им инструмент для автоматического сбора хорошо структурированного контекста вашей кодовой базы.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Welcome (`website/src/content/docs/ru/docs/welcome.mdx`)


title: Документация Code2Prompt
template: splash
hero:
tagline: Преобразуйте свой код в оптимизированные для ИИ подсказки за секунды
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: Начать работу 🚀
link: /docs/tutorials/getting_started
- text: Установка 📥
link: /docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Быстрый старт

code2prompt - это мощный инструмент для анализа и обработки кода, предназначенный для генерации подсказок для анализа, генерации и других задач. Он работает путем обхода директорий, построения древовидной структуры и сбора информации о каждом файле.

Он упрощает процесс объединения и форматирования кода, делая его легко анализируемым, документируемым или рефакторируемым с помощью LLM.

Вы можете использовать code2prompt следующими способами:

Ядро библиотеки для быстрого анализа кода Интерфейс командной строки, специально разработанный для людей Программный инструментарий для агентов ИИ и скриптов автоматизации Сервер протокола контекста модели для LLM на стероидах ---

Ключевые особенности

  • Генерация подсказок LLM: Быстро преобразуйте целые базы кода в структурированные подсказки LLM.
  • Фильтрация по шаблону Glob: Включайте или исключайте определенные файлы и директории с помощью шаблонов glob.
  • Настройка шаблонов: Адаптируйте генерацию подсказок с помощью шаблонов Handlebars.
  • Подсчет токенов: Анализируйте использование токенов и оптимизируйте для LLM с разными окнами контекста.
  • Интеграция с Git: Включайте разницы Git и сообщения о коммитах в подсказки для обзора кода.
  • Уважение к .gitignore: Автоматически игнорирует файлы, перечисленные в .gitignore, чтобы упростить генерацию подсказок.

Почему `code2prompt`?

  1. Экономьте время:

    • Автоматизирует процесс обхода базы кода и форматирования файлов для LLM.
    • Избегает повторяющегося копирования и вставки кода.
  2. Повышайте производительность:

    • Предоставляет структурированный и последовательный формат для анализа кода.
    • Помогает выявлять ошибки, рефакторировать код и писать документацию быстрее.
  3. Работа с большими базами кода:

    • Разработан для работы с большими базами кода, уважая ограничения контекста LLM.
  4. Настройка рабочих процессов:

    • Гибкие возможности для фильтрации файлов, использования шаблонов и генерации целевых подсказок.

Примеры использования

  • Документация кода:
    Автоматически генерируйте документацию для публичных функций, методов и классов.

  • Обнаружение ошибок:
    Найдите потенциальные ошибки и уязвимости, анализируя вашу базу кода с помощью LLM.

  • Рефакторинг:
    Упростите и оптимизируйте код, генерируя подсказки для улучшения качества кода.

  • Обучение и исследование:
    Поймите новые базы кода, генерируя сводки и подробные разборы.

  • Описания коммитов и PR:
    Генерируйте осмысленные сообщения о коммитах и описания pull-запросов из разниц Git.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Zh Blog 2025.04.11 Why I Wrote Code2prompt (`website/src/content/docs/zh/blog/2025.04.11_why_I_wrote_code2prompt.mdx`)


title: "为什么我开发了Code2Prompt"
date: 2025-04-11
lastUpdated: 2025-04-11
tags:

  • 开源
  • code2prompt
  • AI
  • 智能代理
    excerpt: "code2prompt背后的故事:我为了解决LLM工作流中的上下文挑战而进行的开源探索"
    authors:
  • ODAncona
    cover:
    alt: "code2prompt简化AI智能体代码上下文的示意图"
    image: "/src/assets/logo_dark_v0.0.2.svg"
    featured: false
    draft: false

介绍

我一直对大型语言模型(LLMs)如何改变编码工作流程感到着迷——它们可以生成测试、文档字符串,甚至在几分钟内完成整个功能的编写。但当我进一步推动这些模型时,几个关键的痛点不断出现:

规划困难 高Token成本 幻觉
🧠 ➡️ 🤯 🔥 ➡️ 💸 💬 ➡️ 🌀

这就是为什么我开始为code2prompt做出贡献,这是一个基于Rust的工具,旨在为LLMs提供恰到好处的上下文。

在本文中,我将分享我的经验,并解释为什么我相信code2prompt在今天是相关的,并且可以很好地集成,为什么它成为了我更好、更快地进行AI编码工作流程的首选解决方案。

我与LLMs的初步接触 👣

我于2023年11月开始在OpenAI Playground上使用text-davinci-003尝试LLMs。语言模型开启了一场新的革命。感觉就像拥有一个出色的新助手,可以几乎按照命令生成单元测试和文档字符串。我喜欢将模型推向极限——测试从闲聊和伦理困境到越狱和复杂编码任务的一切。然而,当我承担更大的项目时,我很快意识到模型有明显的局限性。起初,我只能将几百行代码放入上下文窗口,即使如此,模型也经常难以理解代码的目的或结构。这就是为什么我迅速意识到上下文的重要性至关重要。我的指令越简洁,上下文越好,结果就越好。

模型演进 🏗️

模型可以产生令人印象深刻的结果,但往往难以处理较大的代码库或复杂的任务。我发现自己花费更多时间编写提示词,而不是实际编码。同时,模型通过发布新版本不断改进。它们增加了推理能力和上下文大小,提供了新的视角和可能性。我可以将近2000行代码放入上下文窗口,然后结果就改进了。我可以在几个迭代中编写整个功能,并且我对快速获得结果的速度感到惊讶。我相信LLMs是编码的未来,并且我想成为这场革命的一部分。我坚信,AI不会取代我们,但会以人类仍然是专家和控制者的助手形式辅助我们。

我与LLMs的第一个项目 🚀

我开始编写一个ROS路径查找模块,用于机器人竞赛,为一个干净架构的Flutter跨平台应用程序生成功能,并制作了一个小型的Next.js网页应用程序来跟踪我的费用。我在一个晚上使用一个我从未接触过的框架构建了这个小型应用程序,这是一个改变游戏规则的时刻;LLMs不仅仅是工具,而是倍增器。我开发了bboxconverter,一个用于转换边界框的包,还有很多其他项目。LLMs可以帮助您快速学习新技术和框架;这很棒。

一个新的范式:软件3.0 💡

我深入研究了LLMs,并开始围绕它们构建智能体和脚手架。我重现了著名的论文RestGPT。这个想法非常棒:给LLMs调用某些REST API的能力,使用OpenAPI规范,如Spotify或TMDB。这些功能引入了一种新的软件编程范式,我称之为软件3.0。

软件1.0 软件2.0 软件3.0
基于规则 数据驱动 智能代理

同样的想法推动了MCP协议的发展,该协议允许LLMs直接调用工具和资源,而无需设计工具描述即可被LLM调用,不像REST Apis那样不一定需要OpenAPI规范。

LLMs的局限性 🧩

幻觉 🌀

在重现著名的论文RESTGPT时,我注意到了LLMs的一些严重局限性。论文作者遇到了与我相同的问题:LLMs正在幻觉。它们生成未实现的代码,发明参数,简单地逐字遵循指令,而不利用常识。例如,在原始RestGPT代码库中,作者在调用者提示中要求。

“不要耍聪明,不要编造计划中不存在的步骤。”

我觉得这句话很有趣,也非常有趣,因为这是我第一次遇到有人指示LLMs不要幻觉。

上下文大小受限 📏

另一个限制是上下文大小;LLMs在寻找关键信息时表现良好,但难以理解它。当你给语言模型太多上下文时,它们往往会陷入细节,失去对全局的把握,这很令人沮丧,需要不断调整。我认为这与维数诅咒类似。把“维数”或“特征”替换为“上下文”,你就明白了。

你给LLM的上下文越多,就越难找到正确答案。我总结了这个想法的妙语:

提供尽可能少但必要的上下文

这高度受到瑞士政治家Alain Berset的名言启发,他在COVID-19封锁期间说过:

“我们希望尽快行动,但也需要时放慢速度”

这代表了折衷的想法,也适用于LLMs的上下文大小!

寻找更好的方法:code2prompt 🔨

因此,我需要一种方法来快速加载、过滤和组织代码上下文,通过提供尽可能少但高质量的上下文。我尝试手动复制文件或代码片段到提示中,但这变得笨拙且容易出错。我知道自动化构造上下文以提出更好提示的繁琐过程会有帮助。然后,有一天,我在谷歌上输入了“code2prompt”,希望能找到一个可以直接将代码输送到提示的工具。

果然,我发现了一个由Mufeed创建的基于Rust的项目,名为code2prompt,在GitHub上拥有大约200个星标。当时,它仍然很基础:一个简单的CLI工具,具有基本的过滤能力和模板。我看到了巨大的潜力,于是直接跳进去贡献,实现了glob模式匹配等功能,并很快成为主要贡献者。

愿景与集成 🔮

如今,有几种方法可以为LLMs提供上下文。从更大的上下文中生成,使用检索增强生成(RAG),压缩代码,甚至使用这些方法的组合。上下文构造是一个热门话题,在未来几个月内将迅速发展。然而,我的方法是KISS:保持简单,笨蛋。向LLMs提供上下文的最简单有效的方法是使用最简单的方法。你精确构造所需的上下文;它是确定性的,这与RAG相反。

这就是为什么我决定将code2prompt作为一个简单的工具进一步推动,可以在任何工作流中使用。我希望它易于使用、集成和扩展。这就是为什么我添加了与工具交互的新方法。

  • 核心: code2prompt的核心是一个Rust库,提供从代码库中构造上下文的基本功能。它包括一个简单的API来加载、过滤和组织代码上下文。
  • CLI: 命令行界面是使用code2prompt的最简单方式。你可以构造代码库的上下文,并直接将其输送到提示中。
  • Python API: Python API是围绕CLI的简单包装器,允许你在Python脚本和智能体中使用code2prompt。你可以构造代码库的上下文,并直接将其输送到提示中。
  • MCP: code2prompt MCP服务器允许LLMs使用code2prompt作为工具,从而使自己能够构造上下文。

更多信息请参见文档中的愿景页面。

与智能体集成 👤

我相信未来的智能体需要一种方法来摄取上下文,而code2prompt是一种简单有效的方法,适用于基于文本的存储库,如代码库、文档或笔记。一个典型的地方是在具有有意义的命名约定的代码库中使用code2prompt。例如,在干净的架构中,关注点和层之间有清晰的分离。相关的上下文通常驻留在不同的文件和文件夹中,但共享相同的名称。这是code2prompt的完美用例,您可以使用glob模式来获取相关文件。

基于Glob模式:以最小的麻烦精确选择或排除文件。

此外,核心库被设计为有状态的上下文管理器,允许您在与LLM的对话过程中添加或删除文件。当为特定任务或目标提供上下文时,这特别有用。您可以轻松地添加或删除文件,而无需重新运行进程。

有状态上下文:在与LLM的对话过程中添加或删除文件。

这些功能使code2prompt成为基于智能体的工作流的理想选择。MCP服务器允许与流行的AI智能体框架(如[Aider](https://github.com/paul-gauthier/aider)、[Goose](https://block.github.io/goose/)或[Cline](https://github.com/jhillyerd/cline))无缝集成。让它们处理复杂目标的同时,`code2prompt`提供完美的代码上下文。

为什么Code2prompt很重要 ✊

随着LLMs的发展和上下文窗口的扩大,简单地将整个存储库强制输入提示可能看起来足够了。然而,Token成本和提示连贯性仍然是小公司和开发者的重大障碍。专注于最重要的代码,code2prompt使您的LLM使用效率高、成本效益高,并且不容易产生幻觉。

简而言之:

  • 减少幻觉:通过提供适量的上下文
  • 降低Token使用成本:通过手动管理所需的适当上下文
  • 提高LLM性能:通过提供适量的上下文
  • 将智能体堆栈集成作为文本存储库的上下文提供者

加入开源! 🌐

欢迎每一位新贡献者!如果您对Rust、构造创新AI工具感兴趣,或者只是想要一个更好的基于代码提示的工作流,请加入我们。

感谢阅读,我希望我的故事能激励您尝试code2prompt。这是一段令人难以置信的旅程,才刚刚开始!

Olivier D'Ancona

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Vision (`website/src/content/docs/zh/docs/vision.mdx`)


title: Code2Prompt 的愿景

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`code2prompt` 的诞生是为了帮助开发者和 AI 代理更有效地与代码库交互。

问题 🚩

大型语言模型(LLMs)已经革新了我们与代码交互的方式。然而,它们在代码生成方面仍然面临着重大挑战:

  • 规划和推理:LLMs 缺乏规划和推理能力,这对于代码生成、重构和调试等任务至关重要。它们往往难以把握全局,目光短浅。
  • 上下文大小:LLMs 的上下文窗口有限,这限制了它们分析和理解大型代码库的能力。
  • 幻觉:LLMs 可以生成看似正确但实际上错误或无意义的代码。这种现象被称为幻觉,发生于模型缺乏足够的上下文或对代码库的理解时。

这就是 code2prompt 的用武之地。

解决方案 ✅

我们相信,通过脚手架技术,规划和推理可以由人类或 AI 代理实现。这些代理需要收集 高质量的上下文,即针对特定任务过滤、结构化和格式化后的代码库。

经验法则是:

这在实践中很难实现,尤其是对于大型代码库。然而,code2prompt 是一个简单的工具,可以帮助开发者和 AI 代理更有效地消化代码库。

它自动遍历代码库,过滤文件,并将它们格式化为 LLMs 可以理解的结构化提示。这样,它有助于减轻规划、推理和幻觉的挑战。

您可以在以下部分了解 code2prompt 如何设计以应对这些挑战。

架构 ⛩️

code2prompt 以模块化方式设计,便于与各种工作流集成。它可以用作核心库、命令行接口(CLI)、软件开发工具包(SDK)或模型上下文协议(MCP)服务器。

核心

code2prompt 是一个代码消化工具,简化了为代码分析、生成和其他任务创建 LLM 提示的过程。它通过遍历目录、构建树结构和收集每个文件的信息来工作。核心库可以轻松集成到其他应用程序中。

CLI

code2prompt 命令行接口(CLI)旨在让人类直接从代码库生成提示。生成的提示会自动复制到剪贴板,也可以保存到输出文件。此外,您可以使用 Handlebars 模板自定义提示生成。查看文档中提供的提示!

SDK

code2prompt 软件开发工具包(SDK)为核心库提供了 Python 绑定。这对于希望与代码库无缝交互的 AI 代理或自动化脚本来说是完美的。SDK 托管在 Pypi 上,可以通过 pip 安装。

MCP

code2prompt 也可用作模型上下文协议(MCP)服务器,允许您将其作为本地服务运行。这通过为 LLMs 提供一个工具,使其能够自动收集代码库的良好结构化的上下文,从而增强了 LLMs 的能力。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Welcome (`website/src/content/docs/zh/docs/welcome.mdx`)


title: Code2Prompt 文件
template: splash
hero:
tagline: 几秒钟内将代码转化为人工智能优化的提示信息
image:
file: ../../../../assets/logo_dark_v0.0.1.svg
actions:
- text: 开始 🚀
link: /zh/docs/tutorials/getting_started
- text: 安装 📥
link: /zh/docs/how_to/install


import { Card, CardGrid } from "@astrojs/starlight/components";
import { LinkCard } from "@astrojs/starlight/components";

Quick Start





code2prompt 是一款强大的代码摄入工具,旨在为代码分析、生成和其他任务生成提示。它通过遍历目录、构建树结构并收集每个文件的信息来工作。

它简化了组合和格式化代码的过程,使得使用大型语言模型(LLM)轻松分析和文档代码或重构代码变得容易。

您可以使用 code2prompt 以下列方式:

核心库,极速代码摄入 专门为人类设计的命令行界面 面向 AI 代理和自动化脚本的软件开发工具包 面向强化 LLM 的模型上下文协议服务器

  • 生成 LLM 提示: 快速将整个代码库转换为结构化的 LLM 提示。
  • Glob 模式过滤: 使用 glob 模式包含或排除特定文件和目录。
  • 可定制的模板: 使用 Handlebars 模板定制提示生成。
  • Token 计数: 分析 token 使用情况,并针对不同上下文窗口的 LLM 进行优化。
  • Git 集成: 在提示中包含 Git diff 和提交消息,以进行代码审查。
  • 尊重 .gitignore: 自动忽略 .gitignore 中列出的文件,以简化提示生成。

为什么选择 `code2prompt`?

  1. 节省时间:

    • 自动遍历代码库并为 LLM 格式化文件。
    • 避免重复复制粘贴代码。
  2. 提高生产力:

    • 为代码分析提供结构化和一致的格式。
    • 帮助更快地识别错误、重构代码和编写文档。
  3. 处理大型代码库:

    • 设计用于与大型代码库无缝协作,尊重 LLM 的上下文限制。
  4. 可定制的流程:

    • 灵活的选项用于过滤文件、使用模板和生成有针对性的提示。

示例用例

  • 代码文档:
    自动为公共函数、方法和类生成文档。

  • 错误检测:
    通过使用 LLM 分析代码库来查找潜在的错误和漏洞。

  • 重构:
    通过生成代码质量改进提示来简化和优化代码。

  • 学习和探索:
    通过生成摘要和详细分析来理解新的代码库。

  • Git 提交和 PR 描述:
    从 Git diff 中生成有意义的提交消息和拉取请求描述。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs De Docs Explanations Glob Pattern Filter (`website/src/content/docs/de/docs/explanations/glob_pattern_filter.mdx`)


title: Wie der Glob-Musterfilter funktioniert

Code2Prompt verwendet Glob-Muster, um Dateien und Verzeichnisse einzuschließen oder auszuschließen, ähnlich wie Tools wie tree oder grep. Es ermöglicht Ihnen, zwei unabhängige Listen von Glob-Mustern zu übergeben:

  • Include-Liste (--include oder -i) - "Diese Muster erlauben Dateien"
  • Exclude-Liste (--exclude oder -e) - "Diese Muster verbieten Dateien"

Code2prompt muss für jede Datei im Projekt entscheiden, ob sie beibehalten oder verworfen wird. Diese Seite erklärt die Regeln und die dahinter stehenden Design-Entscheidungen.


1. Mengen und Symbole

Während der Erklärung verwenden wir die übliche Mengennotation

Symbol Bedeutung
$A$ Menge der Dateien, die mindestens ein Include-Muster treffen
$B$ Menge der Dateien, die mindestens ein Exclude-Muster treffen
$\Omega$ der gesamte Projektbaum (das Universum)
$C = A \cap B$ Dateien, die beide Listen treffen (die Überschneidung)
$D = \Omega \setminus (A \cup B)$ Dateien, die keine Liste treffen

2. Vier Situationen

Übersicht der vier Situationen

Include-Liste Exclude-Liste Behaltene Dateien
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. Keine Include-Liste, keine Exclude-Liste

    Wenn keine Muster angegeben sind, werden alle Dateien beibehalten (Ω).

  2. Nur Exclude-Liste

    In diesem Fall fungiert Code2Prompt als Blacklist und entfernt Dateien, die den ausgeschlossenen Mustern entsprechen ( Ω \ B = ¬B).

  3. Nur Include-Liste

    Wenn nur eine Include-Liste angegeben ist, fungiert Code2Prompt als Whitelist und behält nur Dateien, die den eingeschlossenen Mustern entsprechen (A).

  4. Include- und Exclude-Listen

    Wenn beide Listen angegeben sind, behält Code2Prompt Dateien, die den Include-Mustern entsprechen, entfernt aber diejenigen, die den Exclude-Mustern entsprechen (A \ B).


3. Mehr über die Überschneidung

Mit beiden Listen vorhanden (A ≠ ∅, B ≠ ∅) haben Sie vier logische Möglichkeiten
für die Überschneidung C und den Rest D.

C gewünscht? D gewünscht? Vernünftig?
Nein Nein Standardverhalten (A \ B)
Ja Nein Gleiches Verhalten wie Fall 3 (A)
Nein Ja überraschend ("verwerfe was ich angefordert habe C, behalte was nicht")
Ja Ja Gleiches Verhalten wie Fall 1 (Ω)

Aus diesem Grund wurde die Option --include-priority entfernt. Denn es wäre das gleiche Ergebnis, als hätten Sie nur eine Include-Liste (Fall 3).

4. Schnelle Referenztabelle

Behalten möchten… Verwenden
alles kein -i, kein -e
alles außer bestimmten Mustern nur -e
nur was den Mustern entspricht nur -i
was -i entspricht, minus was -e entspricht -i und -e

Dieses Design hält das mentale Modell einfach:

  • Die Include-Liste ist eine Whitelist, sobald sie existiert.
  • Die Exclude-Liste ist eine darüber gelegte Blacklist.
  • Die Überschneidung wird standardmäßig verworfen

Website Src Content Docs De Docs Explanations Glob Patterns (`website/src/content/docs/de/docs/explanations/glob_patterns.md`)


title: Glob-Muster

Glob-Muster sind eine einfache, aber leistungsstarke Möglichkeit, Dateinamen und -pfade mithilfe von Platzhalterzeichen abzugleichen. Sie werden häufig in Kommandozeilen-Interfaces und Programmiersprachen verwendet, um Mengen von Dateinamen oder Verzeichnissen anzugeben. Hier ist eine Aufschlüsselung der am häufigsten verwendeten Glob-Muster:

Grundlegende Platzhalter

  • *: Passt auf eine beliebige Anzahl von Zeichen, einschließlich null Zeichen.

    • Beispiel: *.txt passt auf alle Dateien, die mit .txt enden.
  • ?: Passt auf genau ein Zeichen.

    • Beispiel: file?.txt passt auf file1.txt, fileA.txt, aber nicht auf file10.txt.
  • []: Passt auf jedes der eingeschlossenen Zeichen.

    • Beispiel: file[1-3].txt passt auf file1.txt, file2.txt, file3.txt.
  • [!] oder [^]: Passt auf jedes Zeichen, das nicht eingeschlossen ist.

    • Beispiel: file[!1-3].txt passt auf file4.txt, fileA.txt, aber nicht auf file1.txt.

Erweiterte Muster

  • **: Passt auf eine beliebige Anzahl von Verzeichnissen und Unterverzeichnissen rekursiv.

    • Beispiel: **/*.txt passt auf alle .txt-Dateien im aktuellen Verzeichnis und in allen Unterverzeichnissen.
  • {}: Passt auf jedes der durch Kommas getrennten Muster, die eingeschlossen sind.

    • Beispiel: file{1,2,3}.txt passt auf file1.txt, file2.txt, file3.txt.

Beispiele

  1. Alle Textdateien in einem Verzeichnis abgleichen:

    sh
    *.txt
  2. Alle Dateien mit einer einzelnen Ziffer vor der Erweiterung abgleichen:

    sh
    file?.txt
  3. Dateien mit den Erweiterungen .jpg oder .png abgleichen:

    sh
    *.{jpg,png}
  4. Alle .txt-Dateien in einem beliebigen Unterverzeichnis abgleichen:

    sh
    **/*.txt
  5. Dateien, die mit a oder b beginnen und mit .txt enden, abgleichen:

    sh
    {a,b}*.txt

Anwendungsfälle

  • Kommandozeilen-Tools: Glob-Muster werden umfassend in Kommandozeilen-Tools wie ls, cp, mv und rm verwendet, um mehrere Dateien oder Verzeichnisse anzugeben.
  • Programmiersprachen: Sprachen wie Python, JavaScript und Ruby unterstützen Glob-Muster für die Dateimatching über Bibliotheken wie glob in Python.
  • Build-Systeme: Tools wie Makefile verwenden Glob-Muster, um Quelldateien und Abhängigkeiten anzugeben.

Schlussfolgerung

Glob-Muster bieten eine flexible und intuitive Möglichkeit, Dateinamen und -pfade abzugleichen, was sie für Skripting, Automatisierung und Dateiverwaltungsaufgaben unverzichtbar macht. Das Verständnis und die Nutzung dieser Muster können Ihre Produktivität und Effizienz bei der Handhabung von Dateien und Verzeichnissen erheblich steigern.

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Explanations Tokenizers (`website/src/content/docs/de/docs/explanations/tokenizers.md`)


title: Tokenisierung in Code2Prompt

Bei der Arbeit mit Sprachmodellen muss Text in ein Format umgewandelt werden, das das Modell verstehen kann – Tokens, die Sequenzen von Zahlen sind. Diese Transformation wird von einem Tokenizer durchgeführt.


Die angegebene Tokenzahl ist eine Schätzung: Code2Prompt zählt die Dateien nach
der Verarbeitung und optionalen Zeilennummerierung parallel und addiert den
geschätzten Aufwand der Vorlage. Der vollständige Prompt wird nicht erneut
tokenisiert. Fragmentgrenzen und Änderungen durch die Vorlage können das Ergebnis
beeinflussen; die Schätzung ist keine garantierte Obergrenze. Das numerische Feld
token_count behält seinen Namen und berücksichtigt weder die JSON-Hülle noch
Escape-Sequenzen der Serialisierung.

Was ist ein Tokenizer?

Ein Tokenizer konvertiert rohen Text in Tokens, die die Bausteine für die Verarbeitung von Eingaben durch Sprachmodelle sind. Diese Tokens können je nach Design des Tokenizers Wörter, Subwörter oder sogar einzelne Zeichen darstellen.

Für code2prompt verwenden wir den tiktoken-Tokenizer. Er ist effizient, robust und für OpenAI-Modelle optimiert.
Sie können seine Funktionalität im offiziellen Repository erkunden

👉 tiktoken GitHub Repository

Wenn Sie mehr über Tokenizer im Allgemeinen erfahren möchten, lesen Sie den

👉 Mistral Tokenization Guide.

Implementierung in `code2prompt`

Die Tokenisierung wird mit tiktoken-rs implementiert. tiktoken unterstützt diese Kodierungen, die von OpenAI-Modellen verwendet werden:

CLI-Argument Kodierungsname OpenAI-Modelle
cl100k cl100k_base ChatGPT-Modelle, text-embedding-ada-002
p50k p50k_base Code-Modelle, text-davinci-002, text-davinci-003
p50k_edit p50k_edit Für Edit-Modelle wie text-davinci-edit-001, code-davinci-edit-001
r50k r50k_base (oder gpt2) GPT-3-Modelle wie davinci
gpt2 o200k_base GPT-4o-Modelle

Für mehr Kontext zu den verschiedenen Tokenizern siehe das OpenAI Cookbook

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs How To Cli (`website/src/content/docs/de/docs/how_to/cli.mdx`)


title: Code2Prompt Grundlegende Nutzung

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

Willkommen zur `Code2Prompt`-Nutzungsanleitung.

Nutzung

Prompt aus einem Code‑Basisverzeichnis generieren:

sh
code2prompt pfad/zur/codebase

Prompt generieren und in die Zwischenablage kopieren:

sh
code2prompt pfad/zur/codebase -c

Interaktive TUI starten:

sh
code2prompt pfad/zur/codebase --tui

Token‑Map anzeigen:

sh
code2prompt pfad/zur/codebase --token-map

Eigenes Handlebars‑Template verwenden:

sh
code2prompt pfad/zur/codebase -t pfad/zum/template.hbs

Dateien mit Glob‑Mustern filtern:

sh
code2prompt pfad/zur/codebase --include="*.rs,*.toml"

Dateien mit Glob‑Mustern ausschließen:

sh
code2prompt pfad/zur/codebase --exclude="*.txt,*.md"

Dateien/Ordner im Quellbaum anhand von Ausschlussmustern entfernen:

sh
code2prompt pfad/zur/codebase --exclude="*.npy,*.wav"

Token‑Anzahl des generierten Prompts anzeigen:

sh
code2prompt pfad/zur/codebase --token-format=format

Tokenizer für die Token‑Zählung angeben:

sh
code2prompt pfad/zur/codebase --encoding=p50k

Unterstützte Tokenizer: cl100k, p50k, p50k_edit, r50k_bas.

Prompt in eine Ausgabedatei schreiben:

sh
code2prompt pfad/zur/codebase -O ausgabe.txt

Ausgabe als JSON ausgeben:

sh
code2prompt pfad/zur/codebase -F JSON

Die JSON‑Ausgabe hat folgendes Format:

json
{
  "prompt": "<Generierter Prompt>",
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT‑Modelle, text-embedding-ada-002",
  "files": []
}

Git‑Commit‑Nachricht generieren (für gestagte Dateien):

sh
code2prompt pfad/zur/codebase --diff -t templates/write-git-commit.hbs

Pull‑Request mit Branch‑Vergleich generieren (für gestagte Dateien):

sh
code2prompt pfad/zur/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Zeilennummern zu Quellcode‑Blöcken hinzufügen:

sh
code2prompt pfad/zur/codebase --line-numbers

Code‑Block‑Umhüllung in Markdown‑Blöcken deaktivieren:

sh
code2prompt pfad/zur/codebase --no-codeblock

Code2Prompt ist ein hervorragendes Werkzeug, um effizient token‑optimierte Prompts zu erzeugen. Es ist nützlich für verschiedene Anwendungsfälle, z. B.:

  • Code in eine andere Sprache umschreiben.
  • Fehler bzw. Sicherheitslücken finden.
  • Code dokumentieren.
  • Neue Funktionen implementieren.

Website Src Content Docs De Docs How To Config (`website/src/content/docs/de/docs/how_to/config.mdx`)


title: Erstellen einer `.c2pconfig`‑Datei

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

In dieser Anleitung lernen Sie, wie Sie eine `.c2pconfig`‑Datei erstellen und verwenden, um Ihren Prompt‑Generierungs‑Workflow zu automatisieren.

Manuelles Schreiben langer Ausschluss‑Muster, Tokenizer‑Einstellungen oder benutzerdefinierter Variablen bei jedem Aufruf von Code2Prompt kann mühsam werden. Durch das Erstellen einer .c2pconfig‑Konfigurationsdatei können Sie „einmal konfigurieren und vergessen“ die Präferenzen Ihres Projekts. Code2Prompt sucht automatisch nach dieser Datei im aktuellen Arbeitsverzeichnis und wendet Ihre Regeln nahtlos an.

Hier finden Sie eine Schritt‑für‑Schritt‑Anleitung zur Einrichtung Ihrer ersten Konfigurationsdatei.


Initialisieren Ihrer Konfigurationsdatei

Navigieren Sie im Terminal zum Stammverzeichnis Ihres Projekts und erstellen Sie eine Datei namens .c2pconfig.

bash
cd pfad/zu/ihrem/projekt
touch .c2pconfig

Schritt 2: Definieren Sie Ihr Basis‑Verhalten (TOML‑Format)

Öffnen Sie die Datei .c2pconfig in Ihrem bevorzugten Texteditor. Die Datei verwendet die TOML‑Syntax. Fügen Sie die folgende Grundkonfiguration in die Datei ein:

toml
# Standard‑Verhalten
default_output = "clipboard"    # Optionen: stdout, clipboard, file
output_format = "xml"           # Optionen: markdown, json, xml
line_numbers = false            # Fügt Zeilennummern zu Ihren Code‑Blöcken hinzu
encoding = "o200k"              # Passt den Tokenizer an Ihr Ziel‑LLM an

# Globale Filterregeln
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**",
    "**/target/**",
    "tests/fixtures/**",
    "package-lock.json"
]

Schritt 3: Ohne Argumente ausführen

Sobald Ihre .c2pconfig‑Datei im Stammverzeichnis Ihrer Code‑Basis gespeichert ist, müssen Sie keine komplexen Flags mehr übergeben. Führen Sie einfach das Tool aus:

bash
code2prompt .

Code2Prompt liest automatisch Ihre .c2pconfig, filtert Ihre Dateien anhand Ihrer Glob‑Muster, fügt Zeilennummern hinzu und formatiert die Ausgabe gemäß Ihren Einstellungen.


Nächste Schritte

Um fortgeschrittene Workflows, Variablen und Standard‑Konfigurations‑Schlüssel zu erkunden:


Website Src Content Docs De Docs How To Filter Files (`website/src/content/docs/de/docs/how_to/filter_files.md`)


title: Filtern von Dateien in Code2Prompt

Verwendung

Generieren Sie einen Prompt aus einem Codebasis-Verzeichnis:

sh
code2prompt path/to/codebase

Verwenden Sie eine benutzerdefinierte Handlebars-Vorlagendatei:

sh
code2prompt path/to/codebase -t path/to/template.hbs

Filtern Sie Dateien mithilfe von Glob-Mustern:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Schließen Sie Dateien mithilfe von Glob-Mustern aus:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

Schließen Sie Dateien/Ordner aus dem Quellbaum basierend auf Ausschlussmustern aus:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

Zeigen Sie die Tokenanzahl des generierten Prompts an:

sh
code2prompt path/to/codebase --token-format=format

Geben Sie einen Tokenizer für die Tokenanzahl an:

sh
code2prompt path/to/codebase --encoding=p50k

Unterstützte Tokenizer: cl100k, p50k, p50k_edit, r50k_bas.

[!HINWEIS]
Siehe Tokenizer für weitere Details.

Speichern Sie den generierten Prompt in einer Ausgabedatei:

sh
code2prompt path/to/codebase --output=output.txt

Drucken Sie die Ausgabe als JSON:

sh
code2prompt path/to/codebase --json

Die JSON-Ausgabe hat die folgende Struktur:

json
{
  "prompt": "<Generierter Prompt>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT-Modelle, text-embedding-ada-002",
  "files": []
}

Generieren Sie eine Git-Commit-Nachricht (für bereitgestellte Dateien):

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Generieren Sie eine Pull-Anfrage mit Branch-Vergleich (für bereitgestellte Dateien):

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Fügen Sie Zeilennummern zu Quellcodeblöcken hinzu:

sh
code2prompt path/to/codebase --line-numbers

Deaktivieren Sie das Umbrechen von Code innerhalb von Markdown-Codeblöcken:

sh
code2prompt path/to/codebase --no-codeblock
  • Übersetzen Sie den Code in eine andere Sprache.
  • Suchen Sie nach Fehlern/Sicherheitslücken.
  • Dokumentieren Sie den Code.
  • Implementieren Sie neue Funktionen.

Ich habe dies ursprünglich für den persönlichen Gebrauch geschrieben, um das 200K-Kontextfenster von Claude 3.0 zu nutzen, und es hat sich als ziemlich nützlich erwiesen, daher habe ich mich entschieden, es Open-Source zu machen!

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs How To Install (`website/src/content/docs/de/docs/how_to/install.mdx`)


title: Installation von Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Willkommen bei der Installationsanleitung für `Code2Prompt`. Dieses Dokument bietet Schritt-für-Schritt-Anleitungen für die Installation auf verschiedenen Plattformen, einschließlich Windows, macOS und Linux.

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

Voraussetzung

Stellen Sie sicher, dass Rust und Cargo auf Ihrem System installiert sind.

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Dies ist die offizielle Methode, um die neueste stabile Version von Rust und Cargo zu installieren.
Stellen Sie sicher, dass Sie Ihre PATH-Variable nach der Installation von Rust aktualisieren. Starten Sie Ihr Terminal neu oder führen Sie die vom Installer vorgeschlagenen Anweisungen aus.

sh
source $HOME/.cargo/env

Sie können überprüfen, ob alles korrekt installiert ist, indem Sie Folgendes ausführen:

sh
cargo --version
git --version

Command Line Interface (CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 Installieren Sie die neueste (unveröffentlichte) Version von GitHub

Wenn Sie die neuesten Funktionen oder Fixes vor ihrer Veröffentlichung auf crates.io möchten:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

Quellcode-Build

Ideal für Entwickler, die aus dem Quellcode bauen oder zum Projekt beitragen möchten.

  1. 🛠️ Voraussetzungen installieren :

  2. 📥 Repository klonen :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 Binary installieren :

    Um aus dem Quellcode zu bauen und zu installieren:

    sh
    cargo install --path crates/code2prompt

    Um die Binary ohne Installation zu bauen:

    sh
    cargo build --release

    Die Binary ist im target/release-Verzeichnis verfügbar.

  4. 🚀 Ausführen :

    sh
    code2prompt --help

Binary-Releases

Am besten für Benutzer, die die neueste Version ohne Quellcode-Build verwenden möchten.

Laden Sie die neueste Binary für Ihr Betriebssystem von Releases herunter.

⚠️ Binary-Releases können hinter der neuesten GitHub-Version zurückliegen. Für die neuesten Funktionen sollten Sie den Quellcode-Build in Betracht ziehen.

AUR

Speziell für Arch Linux-Benutzer ist code2prompt im AUR verfügbar.

code2prompt ist im AUR verfügbar. Installieren Sie es mit einem AUR-Helfer.

sh
paru/yay -S code2prompt

Nix

Wenn Sie Nix verwenden, können Sie es mit nix-env oder nix profile installieren.

sh
# ohne Flakes:
nix-env -iA nixpkgs.code2prompt
# mit Flakes:
nix profile install nixpkgs#code2prompt

Software Development Kit (SDK) 🐍

Pypi

Sie können die Python-Bindings von Pypi herunterladen

sh
pip install code2prompt_rs

Quellcode-Build

  1. 🛠️ Voraussetzungen installieren :

  2. 📥 Repository klonen :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 Abhängigkeiten installieren :

    uv erstellt .venv, sperrt die Entwicklungsabhängigkeiten und baut die native Erweiterung im editierbaren Modus.

    sh
    uv sync
  4. 🧪 Tests ausführen :

    Führen Sie den Testbefehl des Projekts in der synchronisierten Umgebung aus.

    sh
    uv run pytest

Model Context Protocol (MCP) 🤖

Automatische Installation

Der code2prompt-MCP-Server wird bald in MCP-Registries verfügbar sein.

Manuelle Installation

Der code2prompt-MCP-Server ist noch ein Prototyp und wird bald in das Haupt-Repository integriert.

Um den MCP-Server lokal auszuführen und mit Cline, Goose oder Aider zu verwenden:

  1. 🛠️ Voraussetzungen installieren :

  2. 📥 Repository klonen :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 Abhängigkeiten installieren :

    Der rye-Befehl erstellt eine virtuelle Umgebung und installiert alle Abhängigkeiten im .venv-Verzeichnis.

    sh
    rye sync
  4. 🚀 Server ausführen :

    Der MCP-Server ist jetzt installiert. Sie können ihn mit:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 Mit Agenten integrieren :

    text
    Zum Beispiel können Sie ihn mit `Cline` mit einer ähnlichen Konfiguration integrieren:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs How To Ssh (`website/src/content/docs/de/docs/how_to/ssh.md`)


title: Verwenden Sie Code2prompt CLI mit SSH

Warum funktioniert es nicht?

Wenn Sie versuchen, die code2prompt-CLI auf einem Remote-Server über SSH auszuführen, kann der Befehl den Clipboard nicht finden. Dies liegt daran, dass die code2prompt-CLI den Clipboard verwendet, um die generierte Eingabeaufforderung zu kopieren, und SSH-Sitzungen normalerweise keinen Zugriff auf den lokalen Clipboard haben.

Lösung

Um die code2prompt-CLI mit SSH zu verwenden, können Sie die Ausgabe in eine Datei umleiten, anstatt sie in den Clipboard zu kopieren. Auf diese Weise können Sie immer noch die Eingabeaufforderung generieren und für die spätere Verwendung speichern.

Verwenden Sie die Option --output-file, um die Ausgabedatei anzugeben, in der die generierte Eingabeaufforderung gespeichert wird. Zum Beispiel:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs How To Tui (`website/src/content/docs/de/docs/how_to/tui.mdx`)


title: Verwendung der Code2Prompt Terminal‑Benutzeroberfläche (TUI)

import { Card } from "@astrojs/starlight/components";

`Code2Prompt` bietet eine vollständig interaktive Terminal‑Benutzeroberfläche (TUI). Diese Anleitung führt Sie durch das Starten der TUI und das Beherrschen ihrer fünf Hauptregisterkarten.

TUI starten

Um die interaktive Oberfläche zu öffnen, fügen Sie einfach die Option --tui zu Ihrem Befehl zusammen mit dem Pfad zu Ihrem Projekt hinzu:

sh
code2prompt pfad/zu/ihrem/codebase --tui

1. Registerkarte **Auswahl** (Dateibaum)

Die Registerkarte Auswahl ist dort, wo Sie den genauen Kontext zusammenstellen, den Sie an das LLM senden möchten. Sie zeigt eine hierarchische Ansicht Ihres Projekts und respektiert dabei Ihre .gitignore‑ und .c2pconfig‑Regeln.

  • Navigation: Verwenden Sie ↑ / ↓, um den Cursor zu bewegen, und ← / →, um Verzeichnisse zu erweitern oder zu reduzieren.
  • Auswahl: Drücken Sie die Leertaste, um eine Datei oder ein ganzes Verzeichnis auszuwählen bzw. abzuwählen.
  • Suche: Drücken Sie s oder /, um in den Suchmodus zu wechseln. Sie können Text eingeben oder Platzhalter (*, ?) nutzen, um den Baum sofort zu filtern.
  • Drücken Sie Enter oder Esc, um den Suchmodus zu verlassen und zur normalen Navigation zurückzukehren.

2. Registerkarte **Einstellungen**

Möchten Sie anpassen, wie die Ausgabe formatiert wird, bevor Sie sie generieren? Die Registerkarte Einstellungen bietet visuelle Kontrollkästchen und Dropdown‑Menüs für Ihre aktuelle Sitzung.


3. Registerkarte **Statistiken**

Bevor Sie Geld ausgeben, um ein großes Prompt an ein LLM zu senden, nutzen Sie die Registerkarte Statistiken, um Ihr Token‑Budget zu verstehen.

Verwenden Sie ← / →, um zwischen drei leistungsstarken Ansichten zu wechseln:


4. Registerkarte **Vorlage**

Die Registerkarte Vorlage ist dort, wo die Magie passiert. Sie präsentiert ein mehrspaltiges, anpassbares Layout, das Ihnen hilft, die perfekte Handlebars‑Vorlage zu erstellen.

Wenn Sie sich in der Registerkarte Vorlage befinden, können Sie mit Tastenkombinationen sofort zwischen drei Unterpanels wechseln:


5. Registerkarte **Ausgabe**

Nachdem Sie Ihre Dateien ausgewählt, die Einstellungen angepasst und die Vorlage gewählt haben, drücken Sie Enter, um die endgültige Ausgabe zu erzeugen.

Die Registerkarte Ausgabe zeigt das Prompt exakt so, wie es an das LLM gesendet wird.

  • Scrollen: Verwenden Sie ↑ / ↓, PgUp oder PgDn, um den generierten Text zu prüfen.
  • Kopieren: Drücken Sie c, um das gesamte Prompt sofort in Ihre System‑Zwischenablage zu kopieren.
  • Speichern: Drücken Sie s, um das Prompt direkt in einer lokalen Markdown‑Datei zu speichern (z. B. prompt_20260613_204753.md).

Falls Ihnen ein Datei fehlt, drücken Sie einfach 1, um zurück zur Registerkarte Auswahl zu springen, markieren Sie die Datei und drücken Sie Enter, um die Ausgabe in Echtzeit neu zu generieren.


Website Src Content Docs De Docs References Command Line Options (`website/src/content/docs/de/docs/references/command_line_options.md`)


title: Code2Prompt-Befehlszeilenoptionen

Befehlszeilenoptionen

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs References Default Template (`website/src/content/docs/de/docs/references/default_template.md`)


title: Standardvorlage für Code2Prompt

Standardvorlage

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Tutorials Configuration (`website/src/content/docs/de/docs/tutorials/configuration.mdx`)


title: Konfiguration von Code2Prompt 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

Manuelles Schreiben langer Ausschluss‑Muster oder spezifischer Tokenizer‑Einstellungen bei jedem Aufruf kann mühsam werden. Dieses Tutorial zeigt Ihnen **wie Sie eine `.c2pconfig`‑Konfigurationsdatei** nutzen, um „einmal konfigurieren und vergessen“ die Projekt‑Einstellungen.

Voraussetzungen

Stellen Sie sicher, dass code2prompt installiert ist. Wenn Sie es noch nicht installiert haben, lesen Sie die Installations‑Anleitung. Kenntnisse der TOML‑Syntax sind hilfreich, aber nicht zwingend erforderlich.


Was ist `.c2pconfig`?

Die Datei .c2pconfig ist eine Konfigurationsdatei im TOML‑Format. Beim Ausführen von code2prompt sucht das Tool automatisch nach dieser Datei im aktuellen Arbeitsverzeichnis.

Sie können damit definieren:

  • Filterregeln: Persistente Include‑/Exclude‑Muster.
  • Ausgabeformate: Standardmäßig JSON, Markdown oder XML.
  • Vorlagen‑Kontext: Vordefinierte Variablen für Ihre Handlebars‑Vorlagen.

Schnellstart

Erstellen Sie eine Datei namens .c2pconfig im Stammverzeichnis Ihres Projekts, um Ihr Basis‑Verhalten festzulegen.

toml
# Beispiel‑`.c2pconfig`
default_output = "stdout" # Optionen: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MeinTollesProjekt"
author = "Entwickler"

Referenz der Konfiguration

Die folgende Tabelle beschreibt die verfügbaren Schlüssel in der Konfigurationsdatei.

Schlüssel Typ Beschreibung
path String Standard‑Pfad zum Code‑Basis (meist .).
include_patterns Array Glob‑Muster für Dateien, die einbezogen werden sollen.
exclude_patterns Array Glob‑Muster für Dateien, die ausgeschlossen werden sollen.
line_numbers Boolean Wenn true, werden Zeilennummern zu Code‑Blöcken hinzugefügt.
absolute_path Boolean Absolute Pfade anstelle von relativen Pfaden verwenden.
full_directory_tree Boolean Vollständigen Baum auch für ausgeschlossene Dateien erzeugen.
output_format String markdown, json oder xml.
sort_method String name_asc, name_desc, date_asc, date_desc.
encoding String Tokenizer: cl100k, p50k, o200k.
diff_enabled Boolean Git‑Diff (HEAD vs Index) einbinden.
token_map_enabled Boolean Hierarchische Token‑Nutzungs‑Karte anzeigen.

Implementierungs‑Leitfaden

Folgen Sie diesen Schritten, um eine Konfigurationsdatei in Ihren Workflow zu integrieren.

  1. Initialisieren der Konfiguration
    Navigieren Sie zum Projekt‑Root und erstellen Sie die Datei:

    bash
    touch .c2pconfig
  2. Globale Filter festlegen
    Schließen Sie schwere Verzeichnisse wie node_modules oder Build‑Artefakte aus, um den Kontext für das LLM sauber zu halten.

    toml
    exclude_patterns = [
      "**/node_modules/**",
      "package-lock.json",
      "dist/**"
    ]
  3. Tokenizer für Ihr Modell setzen
    Stimmen Sie den Tokenizer mit Ihrem Ziel‑LLM ab. Verwenden Sie o200k für GPT‑4o, oder cl100k für Claude und GPT‑4.

    toml
    encoding = "o200k"
  4. Benutzerdefinierte Variablen einbinden
    Nutzen Sie den Abschnitt [user_variables], um Daten an Ihre Handlebars‑Vorlagen zu übergeben.

    toml
    [user_variables]
    project_goal = "Refaktorierung des Authentifizierungs‑Moduls für bessere Sicherheit."
  5. Ausführen ohne weitere Flags
    Führen Sie das Tool einfach aus. Es respektiert nun alle vordefinierten Regeln ohne zusätzliche CLI‑Optionen.

    bash
    code2prompt .

Verständnis der Priorität

Es ist wichtig zu verstehen, wie code2prompt entscheidet, welche Konfigurationen verwendet werden, wenn mehrere Quellen im Konflikt stehen.


Beispiel: Die „Review‑Bereit“-Konfiguration

Verwenden Sie diese Konfiguration, wenn Ihr Hauptziel die Generierung von Prompts für Code‑Reviews ist.

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

Nächste Schritte


Website Src Content Docs De Docs Tutorials Getting Started (`website/src/content/docs/de/docs/tutorials/getting_started.mdx`)


title: Erste Schritte mit Code2Prompt

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

Willkommen bei Code2Prompt! Dieses Tutorial bietet eine umfassende Einführung in die Verwendung von Code2Prompt zur Generierung von KI-bereiten Prompts aus Ihren Codebasen. Wir werden seine Kernfunktionalität erkunden und seine Verwendung in verschiedenen Integrationsmethoden demonstrieren: Command Line Interface (CLI), Software Development Kit (SDK) und Model Context Protocol (MCP).

Was ist Code2Prompt?

Code2Prompt ist ein vielseitiges Tool, das entwickelt wurde, um die Lücke zwischen Ihrer Codebasis und großen Sprachmodellen (LLMs) zu schließen. Es extrahiert intelligent relevante Code-Snippets, wendet leistungsstarke Filterung an und formatiert die Informationen in strukturierte Prompts, die für die LLM-Verarbeitung optimiert sind. Dies vereinfacht Aufgaben wie Code-Dokumentation, Fehlererkennung, Refaktorisierung und mehr.

Code2Prompt bietet verschiedene Integrationspunkte:

Eine Core-Rust-Bibliothek, die die Grundlage für Code-Ingestion und Prompt-Bearbeitung bietet. Eine benutzerfreundliche Kommandozeilen-Schnittstelle für schnelle Prompt-Generierung. Ideal für interaktive Verwendung und einmalige Aufgaben. Ein leistungsstarkes Software Development Kit (SDK) für nahtlose Integration in Ihre Python-Projekte. Perfekt für die Automatisierung von Prompt-Generierung innerhalb größerer Workflows. Ein Model Context Protocol (MCP)-Server für die erweiterte Integration mit LLM-Agenten. Ermöglicht anspruchsvolle, Echtzeit-Interaktionen mit Ihrer Codebasis.

📥 Installation

Für detaillierte Installationsanweisungen für alle Methoden (CLI, SDK, MCP) lesen Sie bitte die umfassende Installationsanleitung.

🏁 Generierung von Prompts: Ein CLI-Beispiel

Beginnen wir mit einem einfachen Beispiel mit der CLI. Erstellen Sie ein Beispielprojekt:

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Generieren Sie nun einen Prompt:

bash
code2prompt my_project

Dies kopiert einen Prompt in Ihre Zwischenablage. Sie können dies anpassen:

  • Filterung: code2prompt my_project --include="*.rs" --exclude="tests/*" (enthält nur .rs-Dateien, schließt tests-Verzeichnis aus)
  • Ausgabedatei: code2prompt my_project --output-file=my_prompt.txt
  • JSON-Ausgabe: code2prompt my_project -O json (strukturierte JSON-Ausgabe)
  • Benutzerdefinierte Vorlagen: code2prompt my_project -t my_template.hbs (benötigt die Erstellung von my_template.hbs)

Siehe die Tutorials Lernen Sie Kontextfilterung und Lernen Sie Handlebar-Vorlagen, um mehr über die erweiterten Verwendungen zu erfahren.

🐍 SDK-Integration (Python)

Für die programmgesteuerte Kontrolle verwenden Sie das Python-SDK:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

Dies erfordert die Installation des SDK (pip install code2prompt_rs). Lesen Sie die SDK-Dokumentation für weitere Details.

🤖 MCP-Server-Integration (Erweitert)

Für die erweiterte Integration mit LLM-Agenten führen Sie den code2prompt-MCP-Server aus (siehe Installationsanleitung für Details). Dies ermöglicht Agenten, den Code-Kontext dynamisch anzufordern. Dies ist eine erweiterte Funktion, und weitere Dokumentationen sind auf der Projekt-Website verfügbar.

Erkunden Sie die erweiterten Tutorials und Dokumentationen, um die Fähigkeiten von Code2Prompt zu beherrschen und es in Ihre Workflows zu integrieren.

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Tutorials Learn Filters (`website/src/content/docs/de/docs/tutorials/learn_filters.mdx`)


title: Lernen Sie Kontextfilterung mit Code2Prompt

import { Card } from "@astrojs/starlight/components";

Dieses Tutorial zeigt, wie Sie das **Glob-Muster-Tool** in der `code2prompt`-CLI verwenden, um Dateien basierend auf Einschluss- und Ausschlussmustern zu filtern und zu verwalten.

Glob-Muster funktionieren ähnlich wie Tools wie tree oder grep und bieten leistungsstarke Filterfunktionen. Weitere Informationen finden Sie in der detaillierten Erklärung.


Voraussetzungen

Stellen Sie sicher, dass Sie code2prompt installiert haben. Wenn Sie es noch nicht installiert haben, lesen Sie die Installationsanleitung.


Verständnis von Einschluss- und Ausschlussmustern

Glob-Muster ermöglichen es Ihnen, Regeln für die Filterung von Dateien und Verzeichnissen anzugeben.

  • Einschlussmuster (--include): Geben Sie Dateien und Verzeichnisse an, die Sie einschließen möchten.
  • Ausschlussmuster (--exclude): Geben Sie Dateien und Verzeichnisse an, die Sie ausschließen möchten.
  • Priorität (--include-priority): Löst Konflikte zwischen Einschluss- und Ausschlussmustern.

Einrichtung der Umgebung

Um mit Glob-Mustern zu üben, erstellen wir eine Beispieldatenstruktur mit einigen Dateien.

Bash-Script zum Erstellen der Teststruktur

Führen Sie dieses Skript aus, um eine temporäre Verzeichnisstruktur zu erstellen:

bash
#!/bin/bash

# Erstelle Basisverzeichnis
mkdir -p test_dir/{lowercase,uppercase,.secret}

# Erstelle Dateien in der Struktur
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

Um die Struktur später zu bereinigen, führen Sie aus:

bash
rm -rf test_dir

Dies erstellt die folgende Verzeichnisstruktur:

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.py - BAR.py - BAZ.py - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

Beispiele: Filtern von Dateien mit Einschluss- und Ausschlussmustern

Fall 1: Kein Einschluss, kein Ausschluss

Befehl:

bash
code2prompt test_dir

Ergebnis

Alle Dateien sind eingeschlossen:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

Fall 2: Ausschluss bestimmter Dateitypen

.txt-Dateien ausschließen:

bash
code2prompt test_dir --exclude="*.txt"

Ergebnis

Ausschlossen:

  • Alle .txt-Dateien

Eingeschlossen:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

Fall 3: Einschluss bestimmter Dateitypen

Nur Python-Dateien einschließen:

bash
code2prompt test_dir --include="*.py"

Ergebnis

Eingeschlossen:

  • Alle .py-Dateien

Ausschlossen:

  • .secret/secret.txt

Fall 4: Einschluss und Ausschluss mit Priorität

.py-Dateien einschließen, aber Dateien im uppercase-Verzeichnis ausschließen:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

Ergebnis

Eingeschlossen:

  • Alle lowercase/1-Dateien mit .py-Erweiterung

Ausschlossen:

  • Alle uppercase-Dateien
  • .secret/secret.txt

Zusammenfassung

Das Glob-Muster-Tool in code2prompt ermöglicht es Ihnen, Dateien und Verzeichnisse effektiv zu filtern, indem Sie:

  • --include verwenden, um Dateien anzugeben, die eingeschlossen werden sollen
  • --exclude verwenden, um Dateien anzugeben, die ausgeschlossen werden sollen
  • --include-priority verwenden, um Konflikte zwischen Mustern zu lösen

Um zu üben, erstellen Sie die Beispieldatenstruktur, probieren Sie die Befehle aus und sehen Sie, wie das Tool Dateien dynamisch filtert.

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Tutorials Learn Templates (`website/src/content/docs/de/docs/tutorials/learn_templates.mdx`)


title: Lernen Sie Handlebar-Vorlagen mit Code2Prompt kennen

import { Card } from "@astrojs/starlight/components";

Dieses Tutorial zeigt, wie Sie benutzerdefinierte Handlebars-Vorlagen für die Prompt-Generierung im `code2prompt`-CLI verwenden und erstellen.

Voraussetzungen

Stellen Sie sicher, dass Sie code2prompt installiert haben. Wenn Sie es noch nicht installiert haben, lesen Sie die Installationsanleitung.


Was sind Handlebars-Vorlagen?

Handlebars ist eine beliebte Template-Engine, die es ermöglicht, dynamische Vorlagen mit Platzhaltern zu erstellen.
In code2prompt werden Handlebars-Vorlagen verwendet, um die generierten Prompts basierend auf der Codebasis-Struktur und benutzerdefinierten Variablen zu formatieren.

Wie werden Handlebars-Vorlagen verwendet?

Sie können diese Vorlagen verwenden, indem Sie die -t- oder --template-Flagge gefolgt vom Pfad zur Vorlagendatei übergeben. Zum Beispiel:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

Vorlage-Syntax

Handlebars-Vorlagen verwenden eine einfache Syntax für Platzhalter und Ausdrücke. Sie platzieren Variablen in doppelten geschweiften Klammern {{variable_name}}, um sie in den generierten Prompt aufzunehmen.
Code2prompt bietet eine Reihe von Standardvariablen, die Sie in Ihren Vorlagen verwenden können:

  • absolute_code_path: Der absolute Pfad zur Codebasis.
  • source_tree: Der Quellbaum der Codebasis, der alle Dateien und Verzeichnisse enthält.
  • files: Eine Liste von Dateien in der Codebasis, einschließlich ihrer Pfade und Inhalte.
  • git_diff: Der Git-Diff der Codebasis, wenn zutreffend.
  • code: Der Codeinhalt der aktuell verarbeiteten Datei.
  • path: Der Pfad der aktuell verarbeiteten Datei.

Sie können auch Handlebars-Helfer verwenden, um bedingte Logik, Schleifen und andere Operationen innerhalb Ihrer Vorlagen auszuführen. Zum Beispiel:

handlebars
{{#if files}}
  {{#each files}}
    Datei:
    {{this.path}}
    Inhalt:
    {{this.content}}
  {{/each}}
{{else}}
  Keine Dateien gefunden.
{{/if}}

Vorhandene Vorlagen

code2prompt wird mit einer Reihe von integrierten Vorlagen für gängige Anwendungsfälle geliefert. Sie finden sie im templates-Verzeichnis.

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

Verwenden Sie diese Vorlage, um Prompts für die Dokumentation des Codes zu generieren. Sie fügt Dokumentationskommentare zu allen öffentlichen Funktionen, Methoden, Klassen und Modulen in der Codebasis hinzu.

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

Verwenden Sie diese Vorlage, um Prompts für die Suche nach potenziellen Sicherheitslücken in der Codebasis zu generieren. Sie sucht nach gängigen Sicherheitsproblemen und bietet Empfehlungen, wie diese behoben oder gemildert werden können.

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

Verwenden Sie diese Vorlage, um Prompts für die Bereinigung und Verbesserung der Codequalität zu generieren. Sie sucht nach Möglichkeiten, die Lesbarkeit, Einhaltung von Best Practices, Effizienz, Fehlerbehandlung und mehr zu verbessern.

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

Verwenden Sie diese Vorlage, um Prompts für die Behebung von Fehlern in der Codebasis zu generieren. Sie hilft bei der Diagnose von Problemen, bietet Vorschläge für die Behebung und aktualisiert den Code mit den vorgeschlagenen Änderungen.

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

Verwenden Sie diese Vorlage, um eine GitHub-Pull-Request-Beschreibung in Markdown zu erstellen, indem Sie den Git-Diff und den Git-Log von zwei Branches vergleichen.

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

Verwenden Sie diese Vorlage, um eine hochwertige README-Datei für das Projekt zu erstellen, die für die Hosting auf GitHub geeignet ist. Sie analysiert die Codebasis, um ihren Zweck und ihre Funktionalität zu verstehen, und generiert den README-Inhalt im Markdown-Format.

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

Verwenden Sie diese Vorlage, um Git-Commits aus den gestagten Dateien in Ihrem Git-Verzeichnis zu generieren. Sie analysiert die Codebasis, um ihren Zweck und ihre Funktionalität zu verstehen, und generiert den Git-Commit-Nachrichtentext im Markdown-Format.

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

Verwenden Sie diese Vorlage, um Prompts für die Verbesserung der Leistung der Codebasis zu generieren. Sie sucht nach Optimierungsmöglichkeiten, bietet spezifische Vorschläge und aktualisiert den Code mit den Änderungen.

Benutzerdefinierte Variablen

code2prompt unterstützt die Verwendung von benutzerdefinierten Variablen in den Handlebars-Vorlagen. Alle Variablen in der Vorlage, die nicht Teil des Standardkontexts (absolute_code_path, source_tree, files) sind, werden als benutzerdefinierte Variablen behandelt.

Während der Prompt-Generierung fordert code2prompt den Benutzer auf, Werte für diese benutzerdefinierten Variablen einzugeben. Dies ermöglicht eine weitere Anpassung der generierten Prompts basierend auf der Benutzereingabe.

Zum Beispiel, wenn Ihre Vorlage {{challenge_name}} und {{challenge_description}} enthält, werden Sie aufgefordert, Werte für diese Variablen einzugeben, wenn Sie code2prompt ausführen.

Diese Funktion ermöglicht die Erstellung von wiederverwendbaren Vorlagen, die an verschiedene Szenarien basierend auf der Benutzereingabe angepasst werden können.

Diese Seite wurde für Ihre Bequemlichkeit automatisch übersetzt. Bitte greifen Sie für den Originalinhalt auf die englische Version zurück.


Website Src Content Docs De Docs Tutorials Tui (`website/src/content/docs/de/docs/tutorials/tui.mdx`)


title: Verwendung der Terminal‑UI (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2Prompt` verfügt über eine vollständig interaktive Terminal‑Benutzeroberfläche (TUI). Dieses Tutorial führt Sie durch das Starten der TUI und das Beherrschen ihrer fünf Kern‑Registerkarten.

TUI starten

Um die interaktive Oberfläche zu öffnen, fügen Sie einfach die Flagge --tui zu Ihrem Befehl zusammen mit dem Pfad zu Ihrem Projekt hinzu:

sh
code2prompt pfad/zu/ihrem/codebase --tui

1. Registerkarte **Auswahl** (Dateibaum)

Die Registerkarte Auswahl ist dort, wo Sie den genauen Kontext zusammenstellen, den Sie an das LLM senden möchten. Sie zeigt eine hierarchische Ansicht Ihres Projekts und respektiert dabei Ihre .gitignore‑ und .c2pconfig‑Regeln.

  • Navigation: ↑ / ↓ zum Bewegen des Cursors, ← / → zum Erweitern bzw. Reduzieren von Verzeichnissen.
  • Auswahl: Leertaste, um eine Datei oder ein ganzes Verzeichnis auszuwählen bzw. abzuwählen.
  • Suche: s oder /, um in den Suchmodus zu wechseln. Sie können Text eingeben oder Platzhalter (*, ?) nutzen, um den Baum sofort zu filtern.
  • Enter oder Esc, um den Suchmodus zu verlassen und zur normalen Navigation zurückzukehren.

2. Registerkarte **Einstellungen**

Möchten Sie anpassen, wie die Ausgabe formatiert wird, bevor Sie sie generieren? Die Registerkarte Einstellungen bietet visuelle Kontrollkästchen und Dropdown‑Menüs für Ihre aktuelle Sitzung.


3. Registerkarte **Statistiken**

Bevor Sie Geld ausgeben, um ein großes Prompt an ein LLM zu senden, nutzen Sie die Registerkarte Statistiken, um Ihr Token‑Budget zu verstehen.

Verwenden Sie ← / →, um zwischen drei leistungsstarken Ansichten zu wechseln:


4. Registerkarte **Vorlage**

Die Registerkarte Vorlage ist dort, wo die Magie passiert. Sie präsentiert ein mehrspaltiges, anpassbares Layout, das Ihnen hilft, die perfekte Handlebars‑Vorlage zu erstellen.

Wenn Sie sich in der Registerkarte Vorlage befinden, können Sie mit Tastenkombinationen sofort zwischen drei Unter‑Panels wechseln:


5. Registerkarte **Ausgabe**

Nachdem Sie Ihre Dateien ausgewählt, die Einstellungen angepasst und die Vorlage gewählt haben, drücken Sie Enter, um die endgültige Ausgabe zu erzeugen.

Die Registerkarte Ausgabe zeigt das Prompt exakt so, wie es an das LLM gesendet wird.

  • Scrollen: ↑ / ↓, PgUp oder PgDn, um den generierten Text zu prüfen.
  • Kopieren: c, um das gesamte Prompt sofort in Ihre System‑Zwischenablage zu kopieren.
  • Speichern: s, um das Prompt direkt in einer lokalen Markdown‑Datei zu speichern (z. B. prompt_20260613_204753.md).

Falls Ihnen eine Datei fehlt, drücken Sie einfach 1, um zurück zur Registerkarte Auswahl zu springen, markieren Sie die Datei und drücken Sie Enter, um die Ausgabe in Echtzeit neu zu generieren.


Website Src Content Docs Es Docs Explanations Glob Pattern Filter (`website/src/content/docs/es/docs/explanations/glob_pattern_filter.mdx`)


title: Cómo funciona el filtro de patrones Glob

Code2Prompt utiliza patrones glob para incluir o excluir archivos y directorios, funcionando de manera similar a herramientas como tree o grep. Te permite pasar dos listas independientes de patrones glob:

  • lista de inclusión (--include o -i) - "estos patrones permiten archivos"
  • lista de exclusión (--exclude o -e) - "estos patrones prohíben archivos"

Code2prompt debe decidir, para cada archivo en el proyecto, si se conserva o se descarta. Esta página explica las reglas y las decisiones de diseño que las respaldan.


1. Conjuntos y Símbolos

A lo largo de la explicación usamos la notación de conjuntos habitual

Símbolo Significado
$A$ conjunto de archivos que coinciden con al menos un patrón de inclusión
$B$ conjunto de archivos que coinciden con al menos un patrón de exclusión
$\Omega$ todo el árbol del proyecto (el universo)
$C = A \cap B$ archivos que coinciden con ambas listas (la superposición)
$D = \Omega \setminus (A \cup B)$ archivos que no coinciden con ninguna lista

2. Cuatro Situaciones

Resumen de las cuatro situaciones

Lista de inclusión Lista de exclusión Archivos conservados
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. Sin lista de inclusión, sin lista de exclusión

    Si no se especifican patrones, se conservan todos los archivos (Ω).

  2. Solo lista de exclusión

    En este caso, Code2Prompt actúa como una lista negra, eliminando archivos que coinciden con los patrones excluidos ( Ω \ B = ¬B).

  3. Solo lista de inclusión

    Si solo se especifica una lista de inclusión, Code2Prompt actúa como una lista blanca, conservando solo archivos que coinciden con los patrones incluidos (A).

  4. Listas de inclusión y exclusión

    Si se especifican ambas listas, Code2Prompt conserva archivos que coinciden con los patrones de inclusión, pero elimina aquellos que coinciden con los patrones de exclusión (A \ B).


3. Más sobre la superposición

Con ambas listas presentes (A ≠ ∅, B ≠ ∅) tienes cuatro posibilidades lógicas
para la superposición C y el resto D.

¿Quieres C? ¿Quieres D? ¿Razonable?
No No Comportamiento predeterminado (A \ B)
Sí No Mismo comportamiento que el caso 3 (A)
No Sí sorprendente ("descartar lo que pedí C, conservar lo que no")
Sí Sí Mismo comportamiento que el caso 1 (Ω)

Por esta razón se eliminó la opción --include-priority. Porque sería el mismo resultado que si solo tuvieras una lista de inclusión (caso 3).

4. Tabla de referencia rápida

Quieres conservar… Usa
todo sin -i, sin -e
todo excepto algunos patrones solo -e
solo lo que coincide con los patrones solo -i
lo que coincide con -i, menos lo que coincide con -e -i y -e

Este diseño mantiene el modelo mental simple:

  • La lista de inclusión es una lista blanca tan pronto como existe.
  • La lista de exclusión es una lista negra superpuesta encima.
  • La superposición se descarta por defecto

Website Src Content Docs Es Docs Explanations Glob Patterns (`website/src/content/docs/es/docs/explanations/glob_patterns.md`)


title: Entendiendo patrones Glob

Los patrones Glob son una forma sencilla pero poderosa de coincidir nombres de archivos y rutas utilizando caracteres comodín. Se utilizan comúnmente en interfaces de línea de comandos y lenguajes de programación para especificar conjuntos de nombres de archivos o directorios. A continuación, se presenta un desglose de los patrones Glob más comúnmente utilizados:

Comodines básicos

  • *: Coincide con cualquier número de caracteres, incluidos cero caracteres.

    • Ejemplo: *.txt coincide con todos los archivos que terminan con .txt.
  • ?: Coincide exactamente con un carácter.

    • Ejemplo: file?.txt coincide con file1.txt, fileA.txt, pero no con file10.txt.
  • []: Coincide con cualquiera de los caracteres incluidos.

    • Ejemplo: file[1-3].txt coincide con file1.txt, file2.txt, file3.txt.
  • [!] o [^]: Coincide con cualquier carácter no incluido.

    • Ejemplo: file[!1-3].txt coincide con file4.txt, fileA.txt, pero no con file1.txt.

Patrones avanzados

  • **: Coincide con cualquier número de directorios y subdirectorios de forma recursiva.

    • Ejemplo: **/*.txt coincide con todos los archivos .txt en el directorio actual y todos los subdirectorios.
  • {}: Coincide con cualquiera de los patrones separados por comas incluidos.

    • Ejemplo: file{1,2,3}.txt coincide con file1.txt, file2.txt, file3.txt.

Ejemplos

  1. Coincidir con todos los archivos de texto en un directorio:

    sh
    *.txt
  2. Coincidir con todos los archivos con un solo dígito antes de la extensión:

    sh
    file?.txt
  3. Coincidir con archivos con extensiones .jpg o .png:

    sh
    *.{jpg,png}
  4. Coincidir con todos los archivos .txt en cualquier subdirectorio:

    sh
    **/*.txt
  5. Coincidir con archivos que comienzan con a o b y terminan con .txt:

    sh
    {a,b}*.txt

Casos de uso

  • Herramientas de línea de comandos: Los patrones Glob se utilizan ampliamente en herramientas de línea de comandos como ls, cp, mv y rm para especificar varios archivos o directorios.
  • Lenguajes de programación: Lenguajes como Python, JavaScript y Ruby admiten patrones Glob para la coincidencia de archivos a través de bibliotecas como glob en Python.
  • Sistemas de compilación: Herramientas como Makefile utilizan patrones Glob para especificar archivos fuente y dependencias.

Conclusión

Los patrones Glob proporcionan una forma flexible e intuitiva de coincidir nombres de archivos y rutas, lo que los hace invaluables para tareas de scripting, automatización y administración de archivos. Comprender y utilizar estos patrones puede mejorar significativamente su productividad y eficiencia en el manejo de archivos y directorios.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Explanations Tokenizers (`website/src/content/docs/es/docs/explanations/tokenizers.md`)


title: Tokenización en Code2Prompt

Cuando se trabaja con modelos de lenguaje, el texto debe transformarse en un formato que el modelo pueda entender: tokens, que son secuencias de números. Esta transformación se realiza mediante un tokenizador.


El recuento indicado es una estimación: Code2Prompt cuenta los archivos en
paralelo después del procesamiento y la numeración de líneas opcional, y añade el
coste estimado de la plantilla. El prompt completo no se vuelve a tokenizar. Los
límites entre fragmentos y las transformaciones de la plantilla pueden cambiar el
resultado; la estimación no es un límite superior garantizado. El campo numérico
token_count conserva su nombre y excluye la envoltura JSON y los escapes de
serialización.

¿Qué es un Tokenizador?

Un tokenizador convierte texto sin procesar en tokens, que son los bloques de construcción para cómo los modelos de lenguaje procesan la entrada. Estos tokens pueden representar palabras, subpalabras o incluso caracteres individuales, dependiendo del diseño del tokenizador.

Para code2prompt, utilizamos el tokenizador tiktoken. Es eficiente, robusto y optimizado para modelos de OpenAI.
Puedes explorar su funcionalidad en el repositorio oficial

👉 Repositorio de GitHub de tiktoken

Si deseas aprender más sobre tokenizadores en general, consulta

👉 Guía de Tokenización de Mistral.

Implementación en `code2prompt`

La tokenización se implementa utilizando tiktoken-rs. tiktoken admite estos codificaciones utilizadas por los modelos de OpenAI:

Argumento de CLI Nombre de codificación Modelos de OpenAI
cl100k cl100k_base Modelos de ChatGPT, text-embedding-ada-002
p50k p50k_base Modelos de código, text-davinci-002, text-davinci-003
p50k_edit p50k_edit Utilizar para modelos de edición como text-davinci-edit-001, code-davinci-edit-001
r50k r50k_base (o gpt2) Modelos de GPT-3 como davinci
gpt2 o200k_base Modelos de GPT-4o

Para obtener más contexto sobre los diferentes tokenizadores, consulta OpenAI Cookbook

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs How To Cli (`website/src/content/docs/es/docs/how_to/cli.mdx`)


title: Uso básico de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

Bienvenido a la guía de uso de `Code2Prompt`.

Uso

Generar un prompt desde un código base:

sh
code2prompt ruta/a/código-base

Generar un prompt y copiarlo al portapapeles:

sh
code2prompt ruta/a/código-base -c

Iniciar la TUI interactiva:

sh
code2prompt ruta/a/código-base --tui

Mostrar el mapa de tokens

sh
code2prompt ruta/a/código-base --token-map

Usar un archivo de plantilla Handlebars personalizado:

sh
code2prompt ruta/a/código-base -t ruta/a/plantilla.hbs

Filtrar archivos usando patrones glob:

sh
code2prompt ruta/a/código-base --include="*.rs,*.toml"

Excluir archivos usando patrones glob:

sh
code2prompt ruta/a/código-base --exclude="*.txt,*.md"

Excluir archivos/carpetas del árbol de origen según patrones de exclusión:

sh
code2prompt ruta/a/código-base --exclude="*.npy,*.wav"

Mostrar el recuento de tokens del prompt generado:

sh
code2prompt ruta/a/código-base --token-format=format

Especificar un tokenizador para el recuento de tokens:

sh
code2prompt ruta/a/código-base --encoding=p50k

Tokenizadores compatibles: cl100k, p50k, p50k_edit, r50k_bas.

Guardar el prompt generado en un archivo de salida:

sh
code2prompt ruta/a/código-base -O output.txt

Imprimir salida como JSON:

sh
code2prompt ruta/a/código-base -F JSON

La salida JSON tendrá la siguiente estructura:

json
{
  "prompt": "<Prompt generado>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT models, text-embedding-ada-002",
  "files": []
}

Generar un mensaje de commit de Git (para archivos preparados):

sh
code2prompt ruta/a/código-base --diff -t templates/write-git-commit.hbs

Generar una Pull Request con comparación de ramas (para archivos preparados):

sh
code2prompt ruta/a/código-base --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Agregar números de línea a los bloques de código fuente:

sh
code2prompt ruta/a/código-base --line-numbers

Desactivar el encapsulado de código dentro de bloques de código markdown:

sh
code2prompt ruta/a/código-base --no-codeblock

Code2prompt es una excelente manera de generar prompts de forma eficiente en tokens. Puede ser práctico para una variedad de casos de uso, tales como:

  • Reescribir el código en otro lenguaje.
  • Encontrar errores/vulnerabilidades de seguridad.
  • Documentar el código.
  • Implementar nuevas funcionalidades.

Website Src Content Docs Es Docs How To Config (`website/src/content/docs/es/docs/how_to/config.mdx`)


title: Crear un archivo `.c2pconfig`

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

En esta guía, aprenderá cómo crear y usar un archivo `.c2pconfig` para automatizar su flujo de trabajo de generación de prompts.

Escribir manualmente patrones de exclusión largos, configuraciones de tokenizador o variables personalizadas cada vez que ejecuta Code2Prompt puede volverse tedioso. Al crear un archivo de configuración .c2pconfig, puede "configurar y olvidar" las preferencias de su proyecto. Code2Prompt buscará automáticamente este archivo en su directorio de trabajo actual y aplicará sus reglas sin problemas.

Aquí hay una guía paso a paso para configurar su primer archivo de configuración.


Inicializar su archivo de configuración

Navegue al directorio raíz de su proyecto usando su terminal y cree un archivo llamado .c2pconfig.

bash
cd ruta/a/su/proyecto
touch .c2pconfig

Paso 2: Definir su comportamiento base (formato TOML)

Abra el archivo .c2pconfig en su editor de texto preferido. El archivo usa sintaxis TOML. Pegue la siguiente configuración base en el archivo:

toml
# Configuración de comportamiento predeterminado
default_output = "clipboard"    # Opciones: stdout, clipboard, file
output_format = "xml"           # Opciones: markdown, json, xml
line_numbers = false            # Agrega números de línea a sus bloques de código
encoding = "o200k"              # Coincide con el tokenizador de su LLM objetivo

# Reglas de filtrado globales
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**", 
    "**/target/**", 
    "tests/fixtures/**",
    "package-lock.json"
]

Paso 3: Ejecutar sin argumentos

Una vez que su archivo .c2pconfig esté guardado en la raíz de su código base, ya no necesita pasar banderas complejas. Simplemente ejecute la herramienta:

bash
code2prompt .

Code2Prompt leerá automáticamente su .c2pconfig, filtrará sus archivos usando sus patrones glob, agregará números de línea y formateará la salida según sus elecciones.


Próximos pasos

Para profundizar en la configuración de flujos de trabajo avanzados, variables y claves de configuración predeterminadas:


Website Src Content Docs Es Docs How To Filter Files (`website/src/content/docs/es/docs/how_to/filter_files.md`)


title: Filtrado de Archivos en Code2Prompt

Uso

Generar un prompt desde un directorio de base de código:

sh
code2prompt path/to/codebase

Utilizar un archivo de plantilla Handlebars personalizado:

sh
code2prompt path/to/codebase -t path/to/template.hbs

Filtrar archivos utilizando patrones glob:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Excluir archivos utilizando patrones glob:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

Excluir archivos/carpeta del árbol de origen según patrones de exclusión:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

Mostrar el recuento de tokens del prompt generado:

sh
code2prompt path/to/codebase --token-format=format

Especificar un tokenizador para el recuento de tokens:

sh
code2prompt path/to/codebase --encoding=p50k

Tokenizadores compatibles: cl100k, p50k, p50k_edit, r50k_bas.

[!NOTE]
Consulte Tokenizadores para obtener más detalles.

Guardar el prompt generado en un archivo de salida:

sh
code2prompt path/to/codebase --output=output.txt

Imprimir la salida como JSON:

sh
code2prompt path/to/codebase --json

La salida JSON tendrá la siguiente estructura:

json
{
  "prompt": "<Prompt generado>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "Modelos ChatGPT, text-embedding-ada-002",
  "files": []
}

Generar un mensaje de commit de Git (para archivos en staging):

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Generar una solicitud de Pull Request con comparación de ramas (para archivos en staging):

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Agregar números de línea a bloques de código fuente:

sh
code2prompt path/to/codebase --line-numbers

Deshabilitar el ajuste de código dentro de bloques de código markdown:

sh
code2prompt path/to/codebase --no-codeblock
  • Reescribir el código en otro lenguaje.
  • Encontrar errores/vulnerabilidades de seguridad.
  • Documentar el código.
  • Implementar nuevas características.

Inicialmente escribí esto para uso personal para aprovechar la ventana de contexto de 200K de Claude 3.0 y resultó ser bastante útil, así que decidí open-sourcearlo.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs How To Install (`website/src/content/docs/es/docs/how_to/install.mdx`)


title: Instalación de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Bienvenido a la guía de instalación de `Code2Prompt`. Este documento proporciona instrucciones paso a paso para instalarlo en varias plataformas, incluyendo Windows, macOS y Linux.

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

Requisitos previos

Asegúrese de que Rust y cargo estén instalados en su sistema.

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Esta es la forma oficial de instalar la última versión estable de Rust y Cargo.
Asegúrese de refrescar su variable PATH después de instalar Rust. Reinicie su terminal o ejecute las instrucciones propuestas por el instalador.

sh
source $HOME/.cargo/env

Puede verificar que todo esté instalado correctamente ejecutando:

sh
cargo --version
git --version

Interfaz de Línea de Comando (CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 Instalar la última versión (no publicada) desde GitHub

Si desea las últimas características o correcciones antes de que se publiquen en crates.io:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

Compilación desde código fuente

Ideal para desarrolladores que desean compilar desde código fuente o contribuir al proyecto.

  1. 🛠️ Instalar requisitos previos :

  2. 📥 Clonar el repositorio :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 Instalar el binario :

    Para compilar e instalar desde código fuente:

    sh
    cargo install --path crates/code2prompt

    Para compilar el binario sin instalarlo:

    sh
    cargo build --release

    El binario estará disponible en el directorio target/release.

  4. 🚀 Ejecutarlo :

    sh
    code2prompt --help

Lanzamientos binarios

Mejor para usuarios que desean utilizar la última versión sin compilar desde código fuente.

Descargue el último binario para su sistema operativo desde Lanzamientos.

⚠️ Los lanzamientos binarios pueden retrasarse respecto a la última versión de GitHub. Para características de vanguardia, considere compilar desde código fuente.

AUR

Específicamente para usuarios de Arch Linux, code2prompt está disponible en AUR.

code2prompt está disponible en AUR. Instálelo mediante cualquier ayudante de AUR.

sh
paru/yay -S code2prompt

Nix

Si está utilizando Nix, puede instalarlo utilizando nix-env o nix profile.

sh
# sin flakes:
nix-env -iA nixpkgs.code2prompt
# con flakes:
nix profile install nixpkgs#code2prompt

Kit de Desarrollo de Software (SDK) 🐍

Pypi

Puede descargar los enlaces de Python desde Pypi

sh
pip install code2prompt_rs

Compilación desde código fuente

  1. 🛠️ Instalar requisitos previos :

  2. 📥 Clonar el repositorio :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 Instalar dependencias :

    uv crea .venv, bloquea las dependencias de desarrollo y compila la extensión nativa en modo editable.

    sh
    uv sync
  4. 🧪 Ejecutar las pruebas :

    Ejecute el comando de pruebas del proyecto en el entorno sincronizado.

    sh
    uv run pytest

Protocolo de Contexto de Modelo (MCP) 🤖

Instalación automatizada

El servidor MCP de code2prompt estará disponible pronto en registros de MCP.

Instalación manual

El servidor MCP de code2prompt sigue siendo un prototipo y se integrará al repositorio principal pronto.

Para ejecutar el servidor MCP, localmente para usarlo con Cline, Goose o Aider:

  1. 🛠️ Instalar requisitos previos :

  2. 📥 Clonar el repositorio :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 Instalar dependencias :

    El comando rye creará un entorno virtual e instalará todas las dependencias en la carpeta .venv.

    sh
    rye sync
  4. 🚀 Ejecutar el servidor :

    El servidor MCP ahora está instalado. Puede ejecutarlo utilizando:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 Integrar con Agentes :

    text
    Por ejemplo, puede integrarlo con `Cline`, utilizando una configuración similar:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

Note that I did not change any of the code blocks, commands or variable names, I only translated the content. Also, I did not modify the frontmatter and metadata at the top of the file.

Please let me know if you need any further assistance.

Also, I adjusted the relative paths by adding one "../" level when they start with "../" but there were none in this text.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs How To Ssh (`website/src/content/docs/es/docs/how_to/ssh.md`)


title: Uso de Code2prompt CLI con SSH

¿Por qué no funciona?

Cuando intentas ejecutar el CLI de code2prompt en un servidor remoto a través de SSH, el comando no puede encontrar el portapapeles. Esto se debe a que el CLI de code2prompt utiliza el portapapeles para copiar el mensaje generado, y las sesiones de SSH normalmente no tienen acceso al portapapeles local.

Solución

Para usar el CLI de code2prompt con SSH, puedes redirigir la salida a un archivo en lugar de copiarla al portapapeles. De esta manera, aún puedes generar el mensaje y guardarlo para su uso posterior.

Utiliza la opción --output-file para especificar el archivo de salida donde se guardará el mensaje generado. Por ejemplo:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs How To Tui (`website/src/content/docs/es/docs/how_to/tui.mdx`)


title: Usar la interfaz de usuario de terminal (TUI) de Code2prompt

import { Card } from "@astrojs/starlight/components";


Website Src Content Docs Es Docs References Command Line Options (`website/src/content/docs/es/docs/references/command_line_options.md`)


title: Opciones de línea de comandos de Code2Prompt

Opciones de línea de comandos

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs References Default Template (`website/src/content/docs/es/docs/references/default_template.md`)


title: Plantilla Predeterminada para Code2Prompt

Plantilla Predeterminada

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Tutorials Configuration (`website/src/content/docs/es/docs/tutorials/configuration.mdx`)


title: Configuración de Code2Prompt 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

Escribir manualmente patrones de exclusión largos o configuraciones de tokenizador específicas cada vez puede ser tedioso. Por lo tanto, este tutorial le muestra **cómo usar un archivo de configuración `.c2pconfig`** para "configurar y olvidar" la configuración de su proyecto.

Requisitos previos

Asegúrese de tener code2prompt instalado. Si aún no lo ha instalado, consulte la Guía de instalación. La familiaridad con la sintaxis TOML es útil pero no obligatoria.


¿Qué es .c2pconfig?

El archivo .c2pconfig es un archivo de configuración escrito en formato TOML. Cuando ejecuta code2prompt, busca automáticamente este archivo en su directorio de trabajo actual.

Le permite definir:

  • Reglas de filtrado: Patrones persistentes de inclusión/exclusión.
  • Formatos de salida: Predeterminado a JSON, Markdown o XML.
  • Contexto de plantilla: Predefinir variables para sus plantillas Handlebars.

Inicio rápido

Cree un archivo llamado .c2pconfig en la raíz de su proyecto para definir su comportamiento base.

toml
# Ejemplo de .c2pconfig
default_output = "stdout" # Opciones: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MiProyectoGenial"
author = "Desarrollador"

Referencia de configuración

La siguiente tabla describe las claves disponibles en el archivo de configuración.

Clave Tipo Descripción
path String Ruta predeterminada al código base (generalmente .).
include_patterns Array Patrones glob de archivos a incluir.
exclude_patterns Array Patrones glob de archivos a excluir.
line_numbers Boolean Si es true, agrega números de línea a los bloques de código.
absolute_path Boolean Usar rutas absolutas en lugar de rutas relativas.
full_directory_tree Boolean Generar el árbol completo incluso para archivos excluidos.
output_format String markdown, json o xml.
sort_method String name_asc, name_desc, date_asc, date_desc.
encoding String Tokenizador: cl100k, p50k, o200k.
diff_enabled Boolean Incluir diff de git (HEAD vs Index).
token_map_enabled Boolean Mostrar un mapa jerárquico de uso de tokens.

Guía de implementación

Siga estos pasos para integrar un archivo de configuración en su flujo de trabajo.

  1. Inicializar su configuración
    Navegue a la raíz de su proyecto y cree el archivo de configuración:
    bash touch .c2pconfig

  2. Definir su fuente de verdad
    Excluya directorios pesados como node_modules o artefactos de compilación para mantener limpio el contexto del LLM.
    toml exclude_patterns = [ "**/node_modules/**", "package-lock.json", "dist/**" ]

  3. Establecer la codificación de su modelo
    Haga coincidir el tokenizador con su LLM objetivo. Use o200k para GPT-4o, o cl100k para Claude y GPT-4.
    toml encoding = "o200k"

  4. Inyectar contexto personalizado
    Use la sección [user_variables] para pasar datos a sus plantillas Handlebars.
    toml [user_variables] project_goal = "Refactorizar el módulo de autenticación para una mejor seguridad."

  5. Ejecutar sin argumentos
    Simplemente ejecute la herramienta. Ahora respetará todas sus reglas predefinidas sin banderas CLI adicionales.
    bash code2prompt .


Comprender la precedencia

Es importante comprender cómo code2prompt decide qué configuraciones usar cuando múltiples fuentes entran en conflicto.


Ejemplo: La configuración "Lista para revisión"

Use esta configuración si su objetivo principal es generar prompts para revisiones de código.

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

Próximos pasos


Website Src Content Docs Es Docs Tutorials Getting Started (`website/src/content/docs/es/docs/tutorials/getting_started.mdx`)


title: Getting Started with Code2Prompt

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

Bienvenido a Code2Prompt. Este tutorial proporciona una introducción integral al uso de Code2Prompt para generar indicaciones listas para IA a partir de sus bases de código. Exploraremos su funcionalidad central y demostraremos su uso en diferentes métodos de integración: Interfaz de Línea de Comando (CLI), Kit de Desarrollo de Software (SDK) y Protocolo de Contexto de Modelo (MCP).

¿Qué es Code2Prompt?

Code2Prompt es una herramienta versátil diseñada para cerrar la brecha entre su base de código y Modelos de Lenguaje grandes (LLM). Extrae inteligentemente fragmentos de código relevantes, aplica un filtrado potente y formatea la información en indicaciones estructuradas optimizadas para el consumo de LLM. Esto simplifica tareas como documentación de código, detección de errores, refactoring y más.

Code2Prompt ofrece diferentes puntos de integración:

Una biblioteca de núcleo de Rust que proporciona la base para la ingestión de código y las indicaciones Una interfaz de línea de comandos fácil de usar para la generación rápida de indicaciones. Ideal para uso interactivo y tareas puntuales. Un kit de desarrollo de software (SDK) potente para una integración perfecta en sus proyectos de Python. Perfecto para automatizar la generación de indicaciones dentro de flujos de trabajo más grandes. Un servidor de Protocolo de Contexto de Modelo (MCP) para integración avanzada con agentes de LLM. Permite interacciones sofisticadas y en tiempo real con su base de código.

📥 Instalación

Para obtener instrucciones de instalación detalladas para todos los métodos (CLI, SDK, MCP), consulte la Guía de Instalación completa.

🏁 Generación de Indicaciones: Un ejemplo de CLI

Comencemos con un ejemplo sencillo utilizando la CLI. Cree un proyecto de muestra:

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Ahora, genere una indicación:

bash
code2prompt my_project

Esto copia una indicación en su portapapeles. Puede personalizar esto:

  • Filtrado: code2prompt my_project --include="*.rs" --exclude="tests/*" (incluye solo archivos .rs, excluye el directorio tests)
  • Archivo de Salida: code2prompt my_project --output-file=my_prompt.txt
  • Salida JSON: code2prompt my_project -O json (salida JSON estructurada)
  • Plantillas personalizadas: code2prompt my_project -t my_template.hbs (requiere crear my_template.hbs)

Consulte los tutoriales Aprender filtrado de contexto y Aprender plantillas de Handlebar para obtener más información sobre usos avanzados.

🐍 Integración con SDK (Python)

Para obtener control programático, utilice el SDK de Python:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

Esto requiere instalar el SDK (pip install code2prompt_rs). Consulte la documentación del SDK para obtener más detalles.

🤖 Integración con el servidor MCP (Avanzado)

Para una integración avanzada con agentes de LLM, ejecute el servidor MCP de code2prompt (consulte la guía de instalación para obtener detalles). Esto permite a los agentes solicitar contexto de código dinámicamente. Esta es una característica avanzada y se proporciona más documentación en el sitio web del proyecto.

Explore los tutoriales y la documentación avanzados para dominar las capacidades de Code2Prompt e integrarlo en sus flujos de trabajo.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Tutorials Learn Filters (`website/src/content/docs/es/docs/tutorials/learn_filters.mdx`)


title: Aprender filtrado de contexto con Code2Prompt

import { Card } from "@astrojs/starlight/components";

Este tutorial demuestra cómo utilizar la herramienta de patrones glob en `code2prompt` CLI para filtrar y gestionar archivos según patrones de inclusión y exclusión.

Los patrones glob funcionan de manera similar a herramientas como tree o grep,
proporcionando capacidades de filtrado potentes. Consulta la explicación detallada para obtener más información.


Requisitos previos

Asegúrate de tener code2prompt instalado. Si aún no lo has instalado, consulta la Guía de instalación.


Entendiendo patrones de inclusión y exclusión

Los patrones glob te permiten especificar reglas para filtrar archivos y directorios.

  • Patrones de inclusión (--include): Especifica los archivos y directorios que deseas incluir.
  • Patrones de exclusión (--exclude): Especifica los archivos y directorios que deseas excluir.
  • Prioridad (--include-priority): Resuelve conflictos entre patrones de inclusión y exclusión.

Configuración del entorno

Para practicar con patrones glob, creemos una estructura de carpetas de muestra con algunos archivos.

Script Bash para generar la estructura de prueba

Ejecuta este script para configurar una estructura de directorio temporal:

bash
#!/bin/bash

# Crea el directorio base
mkdir -p test_dir/{lowercase,uppercase,.secret}

# Crea archivos en la estructura
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

Para limpiar la estructura más tarde, ejecuta:

bash
rm -rf test_dir

Creará la siguiente estructura de directorio:

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.py - BAR.py - BAZ.py - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

Ejemplos: filtrar archivos con patrones de inclusión y exclusión

Caso 1: Sin inclusión, sin exclusión

Comando:

bash
code2prompt test_dir

Resultado

Se incluyen todos los archivos:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

Caso 2: Excluir tipos de archivo específicos

Excluir archivos .txt:

bash
code2prompt test_dir --exclude="*.txt"

Resultado

Excluidos:

  • Todos los archivos .txt

Incluidos:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

Caso 3: Incluir tipos de archivo específicos

Incluir solo archivos Python:

bash
code2prompt test_dir --include="*.py"

Resultado

Incluidos:

  • Todos los archivos .py

Excluidos:

  • .secret/secret.txt

Caso 4: Incluir y excluir con prioridad

Incluir archivos .py pero excluir archivos en la carpeta uppercase:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

Resultado

Incluidos:

  • Todos los archivos lowercase/1 con extensión .py

Excluidos:

  • Todos los archivos uppercase
  • .secret/secret.txt

Resumen

La herramienta de patrones glob en code2prompt te permite filtrar archivos y directorios de manera efectiva utilizando:

  • --include para especificar archivos a incluir
  • --exclude para archivos a excluir
  • --include-priority para resolver conflictos entre patrones

Para practicar, configura el directorio de muestra, prueba los comandos y observa cómo la herramienta filtra archivos dinámicamente.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Tutorials Learn Templates (`website/src/content/docs/es/docs/tutorials/learn_templates.mdx`)


title: Aprenda plantillas de Handlebar con Code2Prompt

import { Card } from "@astrojs/starlight/components";

Este tutorial demuestra cómo usar y crear plantillas personalizadas de Handlebars para la generación de prompts en el CLI de `code2prompt`.

Requisitos previos

Asegúrese de tener instalado code2prompt. Si aún no lo ha instalado, consulte la Guía de instalación.


¿Qué son las plantillas de Handlebars?

Handlebars es un motor de plantillas popular que le permite crear plantillas dinámicas utilizando marcadores de posición.
En code2prompt, las plantillas de Handlebars se utilizan para dar formato a los prompts generados según la estructura del código base y las variables definidas por el usuario.

Cómo usar plantillas de Handlebars

Puede utilizar estas plantillas pasando la bandera -t o --template seguida de la ruta al archivo de plantilla. Por ejemplo:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

Sintaxis de plantilla

Las plantillas de Handlebars utilizan una sintaxis simple para marcadores de posición y expresiones. Colocará variables entre llaves dobles {{nombre_de_variable}} para incluirlas en el prompt generado.
Code2prompt proporciona un conjunto de variables predeterminadas que puede utilizar en sus plantillas:

  • absolute_code_path: La ruta absoluta al código base.
  • source_tree: El árbol de origen del código base, que incluye todos los archivos y directorios.
  • files: Una lista de archivos en el código base, incluidas sus rutas y contenidos.
  • git_diff: El diff de git del código base, si corresponde.
  • code: El contenido del código del archivo que se está procesando.
  • path: La ruta del archivo que se está procesando.

También puede utilizar ayudantes de Handlebars para realizar lógica condicional, bucles y otras operaciones dentro de sus plantillas. Por ejemplo:

handlebars
{{#if files}}
  {{#each files}}
    Archivo:
    {{this.path}}
    Contenido:
    {{this.content}}
  {{/each}}
{{else}}
  No se encontraron archivos.
{{/if}}

Plantillas existentes

code2prompt viene con un conjunto de plantillas integradas para casos de uso comunes. Puede encontrarlas en el directorio templates.

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

Utilice esta plantilla para generar prompts para documentar el código. Agregará comentarios de documentación a todas las funciones públicas, métodos, clases y módulos en el código base.

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

Utilice esta plantilla para generar prompts para encontrar vulnerabilidades de seguridad potenciales en el código base. Buscará problemas de seguridad comunes y proporcionará recomendaciones sobre cómo solucionarlos o mitigarlos.

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

Utilice esta plantilla para generar prompts para limpiar y mejorar la calidad del código. Buscará oportunidades para mejorar la legibilidad, la adherencia a las mejores prácticas, la eficiencia, el manejo de errores y más.

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

Utilice esta plantilla para generar prompts para solucionar errores en el código base. Ayudará a diagnosticar problemas, proporcionará sugerencias de solución y actualizará el código con las correcciones propuestas.

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

Utilice esta plantilla para crear una descripción de solicitud de extracción de GitHub en markdown comparando el diff de git y el registro de git de dos ramas.

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

Utilice esta plantilla para generar un archivo README de alta calidad para el proyecto, adecuado para alojar en GitHub. Analizará el código base para comprender su propósito y funcionalidad, y generará el contenido del README en formato Markdown.

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

Utilice esta plantilla para generar confirmaciones de git a partir de los archivos preparados en su directorio de git. Analizará el código base para comprender su propósito y funcionalidad, y generará el contenido del mensaje de confirmación de git en formato Markdown.

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

Utilice esta plantilla para generar prompts para mejorar el rendimiento del código base. Buscará oportunidades de optimización, proporcionará sugerencias específicas y actualizará el código con los cambios.

Variables definidas por el usuario

code2prompt admite el uso de variables definidas por el usuario en las plantillas de Handlebars. Cualquier variable en la plantilla que no sea parte del contexto predeterminado (absolute_code_path, source_tree, files) se tratará como una variable definida por el usuario.

Durante la generación de prompts, code2prompt solicitará al usuario que ingrese valores para estas variables definidas por el usuario. Esto permite una mayor personalización de los prompts generados según la entrada del usuario.

Por ejemplo, si su plantilla incluye {{challenge_name}} y {{challenge_description}}, se le pedirá que ingrese valores para estas variables al ejecutar code2prompt.

Esta función permite crear plantillas reutilizables que se pueden adaptar a diferentes escenarios según la información proporcionada por el usuario.

Esta página ha sido traducida automáticamente para su conveniencia. Consulte la versión en inglés para ver el contenido original.


Website Src Content Docs Es Docs Tutorials Tui (`website/src/content/docs/es/docs/tutorials/tui.mdx`)


title: Uso de la interfaz de terminal (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2prompt` cuenta con una interfaz de usuario de terminal (TUI) completamente interactiva. Esta guía le guía a través del lanzamiento de la TUI y el dominio de sus cinco pestañas principales.

Lanzar la TUI

Para abrir la interfaz interactiva, simplemente agregue la bandera --tui a su comando junto con la ruta de su proyecto:

bash
code2prompt ruta/a/su/código-base --tui

1. Pestaña de Selección (Árbol de archivos)

La pestaña de Selección es donde organiza el contexto exacto que desea enviar al LLM. Muestra una vista jerárquica de su proyecto, respetando sus reglas .gitignore y .c2pconfig.

  • Navegación: Use ↑ / ↓ para mover el cursor, y ← / → para expandir o contraer directorios.
  • Selección: Presione Espacio para seleccionar o deseleccionar un archivo o un directorio completo.
  • Modo de búsqueda: Presione s o / para ingresar al modo de búsqueda.
  • Puede escribir texto o usar comodines (*, ?) para filtrar instantáneamente el árbol.
  • Presione Enter o Esc para salir del modo de búsqueda y volver a la navegación normal.

2. Pestaña de Configuración

¿Necesita ajustar cómo se formatea la salida antes de generar? La pestaña de Configuración le ofrece casillas de verificación visuales y menús desplegables para su sesión activa.


3. Pestaña de Estadísticas

Antes de gastar dinero enviando un prompt masivo a un LLM, use la pestaña de Estadísticas para comprender su presupuesto de tokens.

Use ← / → para cambiar entre tres vistas potentes:


4. Pestaña de Plantilla

La pestaña de Plantilla es donde ocurre la magia. Presenta un diseño de varias columnas adaptable para ayudarle a crear la plantilla Handlebars perfecta.

Cuando está en la pestaña de Plantilla, puede cambiar instantáneamente su enfoque entre tres subpaneles usando atajos de teclado:


5. Pestaña de Salida

Una vez que haya seleccionado sus archivos, ajustado su configuración y elegido su plantilla, presione Enter para generar la salida final.

La pestaña de Salida muestra el prompt final exactamente como se enviará al LLM.

  • Desplazar: Use ↑ / ↓, PgUp o PgDn para revisar el texto generado.
  • Copiar: Presione c para copiar instantáneamente todo el prompt a su portapapeles del sistema.
  • Guardar: Presione s para guardar el prompt directamente en un archivo Markdown local (por ejemplo, prompt_20260613_204753.md).

Si se da cuenta de que olvidó un archivo, simplemente presione 1 para volver a la pestaña de Selección, marque el archivo y presione Enter para regenerar la salida en tiempo real.


Website Src Content Docs Fr Docs Explanations Glob Pattern Filter (`website/src/content/docs/fr/docs/explanations/glob_pattern_filter.mdx`)


title: Comment fonctionne le filtre de modèle Glob

Code2Prompt utilise des modèles glob pour inclure ou exclure des fichiers et répertoires, fonctionnant de manière similaire à des outils comme tree ou grep. Il vous permet de passer deux listes indépendantes de modèles glob :

  • liste d'inclusion (--include ou -i) - "ces modèles autorisent les fichiers"
  • liste d'exclusion (--exclude ou -e) - "ces modèles interdisent les fichiers"

Code2prompt doit décider, pour chaque fichier du projet, s'il est conservé ou écarté. Cette page explique les règles et les choix de conception qui les sous-tendent.


1. Ensembles et Symboles

Tout au long de l'explication, nous utilisons la notation d'ensemble habituelle

Symbole Signification
$A$ ensemble des fichiers qui correspondent à au moins un modèle d'inclusion
$B$ ensemble des fichiers qui correspondent à au moins un modèle d'exclusion
$\Omega$ l'arbre de projet entier (l'univers)
$C = A \cap B$ fichiers qui correspondent aux deux listes (le chevauchement)
$D = \Omega \setminus (A \cup B)$ fichiers qui ne correspondent à aucune liste

2. Quatre Situations

Aperçu des quatre situations

Liste d'inclusion Liste d'exclusion Fichiers conservés
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. Pas de liste d'inclusion, pas de liste d'exclusion

    Si aucun modèle n'est spécifié, tous les fichiers sont conservés (Ω).

  2. Liste d'exclusion seulement

    Dans ce cas, Code2Prompt agit comme une liste noire, supprimant les fichiers qui correspondent aux modèles exclus ( Ω \ B = ¬B).

  3. Liste d'inclusion seulement

    Si seule une liste d'inclusion est spécifiée, Code2Prompt agit comme une liste blanche, ne conservant que les fichiers qui correspondent aux modèles inclus (A).

  4. Listes d'inclusion et d'exclusion

    Si les deux listes sont spécifiées, Code2Prompt conserve les fichiers qui correspondent aux modèles d'inclusion, mais supprime ceux qui correspondent aux modèles d'exclusion (A \ B).


3. Plus sur le chevauchement

Avec les deux listes présentes (A ≠ ∅, B ≠ ∅), vous avez quatre possibilités logiques
pour le chevauchement C et le reste D.

Vouloir C ? Vouloir D ? Raisonnable ?
Non Non Comportement par défaut (A \ B)
Oui Non Même comportement que le cas 3 (A)
Non Oui surprenant ("écarter ce que j'ai demandé C, garder ce que je n'ai pas")
Oui Oui Même comportement que le cas 1 (Ω)

C'est pour cette raison que l'option --include-priority a été supprimée. Parce que ce serait le même résultat que si vous n'aviez qu'une liste d'inclusion (cas 3).

4. Table de référence rapide

Vous voulez garder… Utilisez
tout pas de -i, pas de -e
tout sauf certains modèles -e seulement
seulement ce qui correspond aux modèles -i seulement
ce qui correspond à -i, moins ce qui correspond à -e -i et -e

Cette conception maintient le modèle mental simple :

  • La liste d'inclusion est une liste blanche dès qu'elle existe.
  • La liste d'exclusion est une liste noire superposée par-dessus.
  • Le chevauchement est écarté par défaut

Website Src Content Docs Fr Docs Explanations Glob Patterns (`website/src/content/docs/fr/docs/explanations/glob_patterns.md`)


title: Comprendre les modèles Glob

Les modèles Glob sont un moyen simple mais puissant de faire correspondre les noms de fichiers et les chemins d'accès à l'aide de caractères génériques. Ils sont couramment utilisés dans les interfaces de ligne de commande et les langages de programmation pour spécifier des ensembles de noms de fichiers ou de répertoires. Voici une analyse des modèles Glob les plus couramment utilisés :

Générateurs de base

  • * : Correspond à tout nombre de caractères, y compris zéro caractère.

    • Exemple : *.txt correspond à tous les fichiers se terminant par .txt.
  • ? : Correspond exactement à un caractère.

    • Exemple : file?.txt correspond à file1.txt, fileA.txt, mais pas à file10.txt.
  • [] : Correspond à l'un des caractères enfermés.

    • Exemple : file[1-3].txt correspond à file1.txt, file2.txt, file3.txt.
  • [!] ou [^] : Correspond à tout caractère non enfermé.

    • Exemple : file[!1-3].txt correspond à file4.txt, fileA.txt, mais pas à file1.txt.

Modèles avancés

  • ** : Correspond à tout nombre de répertoires et sous-répertoires de manière récursive.

    • Exemple : **/*.txt correspond à tous les fichiers .txt dans le répertoire actuel et tous les sous-répertoires.
  • {} : Correspond à l'un des modèles séparés par des virgules enfermés.

    • Exemple : file{1,2,3}.txt correspond à file1.txt, file2.txt, file3.txt.

Exemples

  1. Faire correspondre tous les fichiers texte dans un répertoire :

    sh
    *.txt
  2. Faire correspondre tous les fichiers avec un seul chiffre avant l'extension :

    sh
    file?.txt
  3. Faire correspondre les fichiers avec les extensions .jpg ou .png :

    sh
    *.{jpg,png}
  4. Faire correspondre tous les fichiers .txt dans n'importe quel sous-répertoire :

    sh
    **/*.txt
  5. Faire correspondre les fichiers qui commencent par a ou b et se terminent par .txt :

    sh
    {a,b}*.txt

Cas d'utilisation

  • Outils de ligne de commande : Les modèles Glob sont largement utilisés dans les outils de ligne de commande tels que ls, cp, mv et rm pour spécifier plusieurs fichiers ou répertoires.
  • Langages de programmation : Les langages tels que Python, JavaScript et Ruby prennent en charge les modèles Glob pour la correspondance de fichiers via des bibliothèques telles que glob en Python.
  • Systèmes de build : Des outils tels que Makefile utilisent des modèles Glob pour spécifier les fichiers source et les dépendances.

Conclusion

Les modèles Glob fournissent un moyen flexible et intuitif de faire correspondre les noms de fichiers et les chemins d'accès, les rendant indispensables pour les tâches de script, d'automatisation et de gestion de fichiers. Comprendre et utiliser ces modèles peut considérablement améliorer votre productivité et votre efficacité dans la gestion des fichiers et des répertoires.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Explanations Tokenizers (`website/src/content/docs/fr/docs/explanations/tokenizers.md`)


title: Tokenisation dans Code2Prompt

Lorsque l'on travaille avec des modèles de langage, le texte doit être transformé en un format que le modèle peut comprendre — tokens, qui sont des séquences de nombres. Cette transformation est gérée par un tokeniseur.


Le nombre de tokens annoncé est une estimation : Code2Prompt compte les fichiers
en parallèle après traitement et numérotation éventuelle, puis ajoute le coût estimé
du template. Le prompt complet n'est pas recompté. Les frontières entre fragments et
les transformations du template peuvent modifier le résultat ; l'estimation n'est
pas une borne supérieure garantie. Le champ numérique token_count garde son nom
et exclut l'enveloppe JSON ainsi que les échappements de sérialisation.

Qu'est-ce qu'un Tokeniseur ?

Un tokeniseur convertit le texte brut en tokens, qui sont les blocs de construction pour la façon dont les modèles de langage traitent l'entrée. Ces tokens peuvent représenter des mots, des sous-mots ou même des caractères individuels, selon la conception du tokeniseur.

Pour code2prompt, nous utilisons le tokeniseur tiktoken. Il est efficace, robuste et optimisé pour les modèles OpenAI.
Vous pouvez explorer sa fonctionnalité dans le référentiel officiel

👉 Référentiel GitHub de tiktoken

Si vous souhaitez en savoir plus sur les tokeniseurs en général, consultez le

👉 Guide de tokenisation Mistral.

Implémentation dans `code2prompt`

La tokenisation est implémentée à l'aide de tiktoken-rs. tiktoken prend en charge ces encodages utilisés par les modèles OpenAI :

Argument CLI Nom de l'encodage Modèles OpenAI
cl100k cl100k_base Modèles ChatGPT, text-embedding-ada-002
p50k p50k_base Modèles de code, text-davinci-002, text-davinci-003
p50k_edit p50k_edit Utiliser pour les modèles d'édition comme text-davinci-edit-001, code-davinci-edit-001
r50k r50k_base (ou gpt2) Modèles GPT-3 comme davinci
gpt2 o200k_base Modèles GPT-4o

Pour plus de contexte sur les différents tokeniseurs, consultez le OpenAI Cookbook

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs How To Cli (`website/src/content/docs/fr/docs/how_to/cli.mdx`)


title: Utilisation de base de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

Bienvenue dans le guide d'utilisation de `Code2Prompt`.

Utilisation

Générer un prompt à partir d'une base de code :

sh
code2prompt chemin/vers/base-de-code

Générer un prompt et le copier dans le presse-papiers :

sh
code2prompt chemin/vers/base-de-code -c

Lancer le TUI interactif :

sh
code2prompt chemin/vers/base-de-code --tui

Afficher la carte des tokens

sh
code2prompt chemin/vers/base-de-code --token-map

Utiliser un fichier de template Handlebars personnalisé :

sh
code2prompt chemin/vers/base-de-code -t chemin/vers/template.hbs

Filtrer les fichiers en utilisant des motifs glob :

sh
code2prompt chemin/vers/base-de-code --include="*.rs,*.toml"

Exclure des fichiers en utilisant des motifs glob :

sh
code2prompt chemin/vers/base-de-code --exclude="*.txt,*.md"

Exclure des fichiers/dossiers de l'arborescence source en fonction des motifs d'exclusion :

sh
code2prompt chemin/vers/base-de-code --exclude="*.npy,*.wav"

Afficher le nombre de tokens du prompt généré :

sh
code2prompt chemin/vers/base-de-code --token-format=format

Spécifier un tokenizer pour le comptage des tokens :

sh
code2prompt chemin/vers/base-de-code --encoding=p50k

Tokenizers supportés : cl100k, p50k, p50k_edit, r50k_bas.

Sauvegarder le prompt généré dans un fichier de sortie :

sh
code2prompt chemin/vers/base-de-code -O output.txt

Afficher la sortie au format JSON :

sh
code2prompt chemin/vers/base-de-code -F JSON

La sortie JSON aura la structure suivante :

json
{
  "prompt": "<Prompt généré>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT models, text-embedding-ada-002",
  "files": []
}

Générer un message de commit Git (pour les fichiers en staging) :

sh
code2prompt chemin/vers/base-de-code --diff -t templates/write-git-commit.hbs

Générer une Pull Request avec comparaison de branches (pour les fichiers en staging) :

sh
code2prompt chemin/vers/base-de-code --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Ajouter des numéros de ligne aux blocs de code source :

sh
code2prompt chemin/vers/base-de-code --line-numbers

Désactiver l'encapsulation du code dans des blocs de code markdown :

sh
code2prompt chemin/vers/base-de-code --no-codeblock

Code2prompt est un excellent moyen de générer des prompts de manière efficace en termes de tokens. Il peut être pratique pour une variété de cas d'utilisation, tels que :

  • Réécrire le code dans un autre langage.
  • Trouver des bugs/vulnérabilités de sécurité.
  • Documenter le code.
  • Implémenter de nouvelles fonctionnalités.

Website Src Content Docs Fr Docs How To Config (`website/src/content/docs/fr/docs/how_to/config.mdx`)


title: Créer un fichier `.c2pconfig`

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

Dans ce guide, vous apprendrez à créer et utiliser un fichier `.c2pconfig` pour automatiser votre flux de travail de génération de prompts.

Taper manuellement de longs motifs d'exclusion, des paramètres de tokenizer ou des variables personnalisées à chaque fois que vous exécutez Code2Prompt peut devenir fastidieux. En créant un fichier de configuration .c2pconfig, vous pouvez "configurer et oublier" vos préférences de projet. Code2Prompt recherchera automatiquement ce fichier dans votre répertoire de travail actuel et appliquera vos règles de manière transparente.

Voici un guide étape par étape pour configurer votre premier fichier de configuration.


Initialiser votre fichier de configuration

Naviguez vers le répertoire racine de votre projet en utilisant votre terminal et créez un fichier nommé .c2pconfig.

bash
cd chemin/vers/votre/projet
touch .c2pconfig

Étape 2 : Définir votre comportement de base (format TOML)

Ouvrez le fichier .c2pconfig dans votre éditeur de texte préféré. Le fichier utilise la syntaxe TOML. Collez la configuration de base suivante dans le fichier :

toml
# Configuration du comportement par défaut
default_output = "clipboard"    # Options : stdout, clipboard, file
output_format = "xml"           # Options : markdown, json, xml
line_numbers = false            # Ajoute des numéros de ligne à vos blocs de code
encoding = "o200k"              # Correspond au tokenizer de votre LLM cible

# Règles de filtrage globales
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**", 
    "**/target/**", 
    "tests/fixtures/**",
    "package-lock.json"
]

Étape 3 : Exécuter sans arguments

Une fois que votre fichier .c2pconfig est enregistré à la racine de votre base de code, vous n'avez plus besoin de passer des flags complexes. Exécutez simplement l'outil :

bash
code2prompt .

Code2Prompt lira automatiquement votre .c2pconfig, filtrera vos fichiers en utilisant vos motifs glob, ajoutera des numéros de ligne et formatera la sortie en fonction de vos choix.


Prochaines étapes

Pour approfondir la configuration de flux de travail avancés, de variables et de clés de configuration par défaut :


Website Src Content Docs Fr Docs How To Filter Files (`website/src/content/docs/fr/docs/how_to/filter_files.md`)


title: Filtrage de fichiers dans Code2Prompt

Utilisation

Générez une invite à partir d'un répertoire de base de code :

sh
code2prompt path/to/codebase

Utilisez un fichier de modèle Handlebars personnalisé :

sh
code2prompt path/to/codebase -t path/to/template.hbs

Filtrez les fichiers à l'aide de modèles glob :

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Excluez les fichiers à l'aide de modèles glob :

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

Excluez les fichiers/dossiers de l'arborescence source en fonction des modèles d'exclusion :

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

Affichez le nombre de jetons de l'invite générée :

sh
code2prompt path/to/codebase --token-format=format

Spécifiez un tokenizeur pour le décompte des jetons :

sh
code2prompt path/to/codebase --encoding=p50k

Tokenizeurs pris en charge : cl100k, p50k, p50k_edit, r50k_bas.

[!NOTE]
Voir Tokenizeurs pour plus de détails.

Enregistrez l'invite générée dans un fichier de sortie :

sh
code2prompt path/to/codebase --output=output.txt

Imprimez la sortie au format JSON :

sh
code2prompt path/to/codebase --json

La sortie JSON aura la structure suivante :

json
{
  "prompt": "<Invite générée>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "Modèles ChatGPT, text-embedding-ada-002",
  "files": []
}

Générez un message de commit Git (pour les fichiers en scène) :

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Générez une demande de tirage avec comparaison de branche (pour les fichiers en scène) :

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Ajoutez des numéros de ligne aux blocs de code source :

sh
code2prompt path/to/codebase --line-numbers

Désactivez l'emballage de code à l'intérieur des blocs de code markdown :

sh
code2prompt path/to/codebase --no-codeblock
  • Réécrivez le code dans un autre langage.
  • Recherchez des bogues/vulnérabilités de sécurité.
  • Documentez le code.
  • Implémentez de nouvelles fonctionnalités.

J'ai initialement écrit cela pour une utilisation personnelle afin de profiter de la fenêtre de contexte de 200K de Claude 3.0 et cela s'est avéré assez utile, alors j'ai décidé de le rendre open-source !

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs How To Install (`website/src/content/docs/fr/docs/how_to/install.mdx`)


title: Installation de Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Bienvenue dans le guide d'installation de `Code2Prompt`. Ce document fournit des instructions étape par étape pour l'installer sur différentes plateformes, notamment Windows, macOS et Linux.

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

Prérequis

Assurez-vous que Rust et cargo sont installés sur votre système.

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

C'est la façon officielle d'installer la dernière version stable de Rust et Cargo. Assurez-vous de rafraîchir votre variable PATH après avoir installé Rust. Redémarrez votre terminal ou exécutez les instructions proposées par l'installateur.

sh
source $HOME/.cargo/env

Vous pouvez vérifier que tout est installé correctement en exécutant :

sh
cargo --version
git --version

Interface de ligne de commande (CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 Installer la dernière version (non publiée) depuis GitHub

Si vous voulez les dernières fonctionnalités ou corrections avant leur publication sur crates.io :

sh
cargo install --git https://github.com/mufeedvh/code2prompt

Construction à partir du code source

Idéal pour les développeurs qui veulent construire à partir du code source ou contribuer au projet.

  1. 🛠️ Installer les prérequis :

  2. 📥 Cloner le référentiel :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 Installer l'exécutable :

    Pour construire et installer à partir du code source :

    sh
    cargo install --path crates/code2prompt

    Pour construire l'exécutable sans l'installer :

    sh
    cargo build --release

    L'exécutable sera disponible dans le répertoire target/release.

  4. 🚀 L'exécuter :

    sh
    code2prompt --help

Publications binaires

Le meilleur choix pour les utilisateurs qui veulent utiliser la dernière version sans construire à partir du code source.

Téléchargez la dernière version binaire pour votre système d'exploitation à partir de Releases.

⚠️ Les publications binaires peuvent être à la traîne par rapport à la dernière version GitHub. Pour des fonctionnalités de pointe, envisagez de construire à partir du code source.

AUR

Spécifiquement pour les utilisateurs d'Arch Linux, code2prompt est disponible dans l'AUR.

code2prompt est disponible dans l'AUR. Installez-le via n'importe quel assistant AUR.

sh
paru/yay -S code2prompt

Nix

Si vous utilisez Nix, vous pouvez l'installer en utilisant soit nix-env, soit nix profile.

sh
# sans flakes :
nix-env -iA nixpkgs.code2prompt
# avec flakes :
nix profile install nixpkgs#code2prompt

Kit de développement logiciel (SDK) 🐍

Pypi

Vous pouvez télécharger les liaisons Python à partir de Pypi

sh
pip install code2prompt_rs

Construction à partir du code source

  1. 🛠️ Installer les prérequis :

  2. 📥 Cloner le référentiel :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 Installer les dépendances :

    uv crée .venv, verrouille les dépendances de développement et compile l'extension native en mode éditable.

    sh
    uv sync
  4. 🧪 Exécuter les tests :

    Exécutez la commande de test du projet dans l'environnement synchronisé.

    sh
    uv run pytest

Protocole de contexte de modèle (MCP) 🤖

Installation automatisée

Le serveur MCP code2prompt sera bientôt disponible dans les registres MCP.

Installation manuelle

Le serveur MCP code2prompt est encore un prototype et sera intégré au référentiel principal bientôt.

Pour exécuter le serveur MCP, localement pour l'utiliser avec Cline, Goose ou Aider :

  1. 🛠️ Installer les prérequis :

  2. 📥 Cloner le référentiel :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 Installer les dépendances :

    La commande rye créera un environnement virtuel et installera toutes les dépendances dans le dossier .venv.

    sh
    rye sync
  4. 🚀 Exécuter le serveur :

    Le serveur MCP est maintenant installé. Vous pouvez l'exécuter en utilisant :

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 Intégrer avec les agents :

    text
    Par exemple, vous pouvez l'intégrer avec `Cline`, en utilisant une configuration similaire :
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs How To Ssh (`website/src/content/docs/fr/docs/how_to/ssh.md`)


title: Utiliser Code2prompt CLI avec SSH

Pourquoi ça ne fonctionne pas ?

Lorsque vous essayez d'exécuter la CLI code2prompt sur un serveur distant via SSH, la commande est incapable de trouver le presse-papiers. En effet, la CLI code2prompt utilise le presse-papiers pour copier l'invite générée, et les sessions SSH n'ont généralement pas accès au presse-papiers local.

Solution

Pour utiliser la CLI code2prompt avec SSH, vous pouvez rediriger la sortie vers un fichier au lieu de la copier dans le presse-papiers. De cette façon, vous pouvez toujours générer l'invite et la sauvegarder pour une utilisation ultérieure.

Utilisez l'option --output-file pour spécifier le fichier de sortie où l'invite générée sera enregistrée. Par exemple :

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs How To Tui (`website/src/content/docs/fr/docs/how_to/tui.mdx`)


title: Utiliser l'interface utilisateur en terminal (TUI) de Code2prompt

import { Card } from "@astrojs/starlight/components";


Website Src Content Docs Fr Docs References Command Line Options (`website/src/content/docs/fr/docs/references/command_line_options.md`)


title: Options de ligne de commande Code2Prompt

Options de ligne de commande

Please let me know if you want me to translate anything else.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs References Default Template (`website/src/content/docs/fr/docs/references/default_template.md`)


title: Modèle par défaut pour Code2Prompt

Modèle par défaut

(Note: I translated the content as per your request, and as there was no actual content to translate apart from the title, description and heading, I left it as is. If there's more content to translate, please provide it.)

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Tutorials Configuration (`website/src/content/docs/fr/docs/tutorials/configuration.mdx`)


title: Configuration de Code2Prompt 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

Taper manuellement de longs motifs d'exclusion ou des paramètres de tokenizer spécifiques à chaque fois peut être fastidieux. Par conséquent, ce tutoriel vous montre **comment utiliser un fichier de configuration `.c2pconfig`** pour "configurer et oublier" vos paramètres de projet.

Prérequis

Assurez-vous d'avoir code2prompt installé. Si vous ne l'avez pas encore installé, consultez le Guide d'installation. Une connaissance de la syntaxe TOML est utile mais non requise.


Qu'est-ce que .c2pconfig ?

Le fichier .c2pconfig est un fichier de configuration écrit au format TOML. Lorsque vous exécutez code2prompt, il recherche automatiquement ce fichier dans votre répertoire de travail actuel.

Il vous permet de définir :

  • Règles de filtrage : Motifs d'inclusion/exclusion persistants.
  • Formats de sortie : Par défaut JSON, Markdown ou XML.
  • Contexte de template : Prédéfinir des variables pour vos templates Handlebars.

Démarrage rapide

Créez un fichier nommé .c2pconfig à la racine de votre projet pour définir votre comportement de base.

toml
# Exemple de .c2pconfig
default_output = "stdout" # Options : stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MonProjetGénial"
author = "Développeur"

Référence de configuration

Le tableau suivant décrit les clés disponibles dans le fichier de configuration.

Clé Type Description
path String Chemin par défaut vers la base de code (généralement .).
include_patterns Array Motifs glob des fichiers à inclure.
exclude_patterns Array Motifs glob des fichiers à exclure.
line_numbers Boolean Si true, ajoute des numéros de ligne aux blocs de code.
absolute_path Boolean Utiliser des chemins absolus au lieu de chemins relatifs.
full_directory_tree Boolean Générer l'arborescence complète même pour les fichiers exclus.
output_format String markdown, json ou xml.
sort_method String name_asc, name_desc, date_asc, date_desc.
encoding String Tokenizer : cl100k, p50k, o200k.
diff_enabled Boolean Inclure le diff git (HEAD vs Index).
token_map_enabled Boolean Afficher une carte hiérarchique d'utilisation des tokens.

Guide d'implémentation

Suivez ces étapes pour intégrer un fichier de configuration dans votre flux de travail.

  1. Initialiser votre configuration
    Naviguez vers la racine de votre projet et créez le fichier de configuration :
    bash touch .c2pconfig

  2. Définir votre source de vérité
    Excluez les répertoires lourds comme node_modules ou les artefacts de build pour garder le contexte du LLM propre.
    toml exclude_patterns = [ "**/node_modules/**", "package-lock.json", "dist/**" ]

  3. Définir l'encodage de votre modèle
    Faites correspondre le tokenizer à votre LLM cible. Utilisez o200k pour GPT-4o, ou cl100k pour Claude et GPT-4.
    toml encoding = "o200k"

  4. Injecter du contexte personnalisé
    Utilisez la section [user_variables] pour transmettre des données dans vos templates Handlebars.
    toml [user_variables] project_goal = "Refactoriser le module d'authentification pour une meilleure sécurité."

  5. Exécuter sans arguments
    Exécutez simplement l'outil. Il respectera maintenant toutes vos règles prédéfinies sans flags CLI supplémentaires.
    bash code2prompt .


Comprendre la priorité

Il est important de comprendre comment code2prompt décide quels paramètres utiliser lorsque plusieurs sources entrent en conflit.


Exemple : La configuration "Prêt pour la revue"

Utilisez cette configuration si votre objectif principal est de générer des prompts pour les revues de code.

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

Prochaines étapes


Website Src Content Docs Fr Docs Tutorials Getting Started (`website/src/content/docs/fr/docs/tutorials/getting_started.mdx`)


title: Getting Started with Code2Prompt

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

Bienvenue dans Code2Prompt ! Ce tutoriel fournit une introduction complète à l'utilisation de Code2Prompt pour générer des invites prêtes à être utilisées par l'IA à partir de vos bases de code. Nous explorerons sa fonctionnalité principale et démontrerons son utilisation à travers différentes méthodes d'intégration : Interface de Ligne de Commande (CLI), Kit de Développement de Logiciels (SDK) et Protocole de Contexte de Modèle (MCP).

Qu'est-ce que Code2Prompt ?

Code2Prompt est un outil polyvalent conçu pour combler le fossé entre votre base de code et les Modèles de Langage à Grande Échelle (LLM). Il extrait intelligemment des extraits de code pertinents, applique un filtrage puissant et formate les informations en invites structurées optimisées pour la consommation LLM. Cela simplifie des tâches telles que la documentation de code, la détection de bogues, la refactorisation, etc.

Code2Prompt offre différents points d'intégration :

Une bibliothèque Rust de base qui fournit les fondations pour l'ingestion de code et la génération d'invites. Une interface de ligne de commande conviviale pour une génération rapide d'invites. Idéale pour une utilisation interactive et des tâches ponctuelles. Un Kit de Développement de Logiciels (SDK) puissant pour une intégration transparente dans vos projets Python. Parfait pour automatiser la génération d'invites dans des workflows plus larges. Un serveur de Protocole de Contexte de Modèle (MCP) pour une intégration avancée avec les agents LLM. Permet des interactions sophistiquées en temps réel avec votre base de code.

📥 Installation

Pour des instructions d'installation détaillées pour toutes les méthodes (CLI, SDK, MCP), veuillez vous référer au Guide d'Installation.

🏁 Génération d'Invites : Un Exemple de CLI

Commençons par un exemple simple en utilisant la CLI. Créez un projet échantillon :

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Maintenant, générez une invite :

bash
code2prompt my_project

Cela copie une invite dans votre presse-papiers. Vous pouvez personnaliser cela :

  • Filtrage : code2prompt my_project --include="*.rs" --exclude="tests/*" (inclut uniquement les fichiers .rs, exclut le répertoire tests)
  • Fichier de sortie : code2prompt my_project --output-file=my_prompt.txt
  • Sortie JSON : code2prompt my_project -O json (sortie JSON structurée)
  • Modèles personnalisés : code2prompt my_project -t my_template.hbs (nécessite la création de my_template.hbs)

Voir les tutoriels Apprendre le filtrage de contexte et Apprendre les modèles Handlebar pour en savoir plus sur les utilisations avancées.

🐍 Intégration SDK (Python)

Pour un contrôle programmatique, utilisez le SDK Python :

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

Cela nécessite l'installation du SDK (pip install code2prompt_rs). Référez-vous à la documentation du SDK pour plus de détails.

🤖 Intégration du Serveur MCP (Avancé)

Pour une intégration avancée avec les agents LLM, exécutez le serveur MCP code2prompt (voir le guide d'installation pour les détails). Cela permet aux agents de demander du contexte de code de manière dynamique. Il s'agit d'une fonctionnalité avancée, et une documentation supplémentaire est disponible sur le site Web du projet.

Explorez les tutoriels avancés et la documentation pour maîtriser les capacités de Code2Prompt et l'intégrer dans vos workflows.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Tutorials Learn Filters (`website/src/content/docs/fr/docs/tutorials/learn_filters.mdx`)


title: Apprendre le filtrage de contexte avec Code2Prompt

import { Card } from "@astrojs/starlight/components";

Ce tutoriel démontre comment utiliser l'outil de modèle de glob dans l'interface de ligne de commande `code2prompt` pour filtrer et gérer des fichiers en fonction de modèles d'inclusion et d'exclusion.

Les modèles de glob fonctionnent de manière similaire à des outils comme tree ou grep, offrant des capacités de filtrage puissantes. Consultez l'explication détaillée pour plus d'informations.


Prérequis

Assurez-vous d'avoir installé code2prompt. Si vous ne l'avez pas encore installé, reportez-vous au Guide d'installation.


Comprendre les modèles d'inclusion et d'exclusion

Les modèles de glob vous permettent de spécifier des règles pour filtrer des fichiers et des répertoires.

  • Modèles d'inclusion (--include) : Spécifiez les fichiers et répertoires que vous souhaitez inclure.
  • Modèles d'exclusion (--exclude) : Spécifiez les fichiers et répertoires que vous souhaitez exclure.
  • Priorité (--include-priority) : Résout les conflits entre les modèles d'inclusion et d'exclusion.

Configuration de l'environnement

Pour pratiquer avec les modèles de glob, créons une structure de dossier échantillon avec quelques fichiers.

Script Bash pour générer la structure de test

Exécutez ce script pour configurer une structure de répertoire temporaire :

bash
#!/bin/bash

# Créer le répertoire de base
mkdir -p test_dir/{lowercase,uppercase,.secret}

# Créer des fichiers dans la structure
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

Pour nettoyer la structure plus tard, exécutez :

bash
rm -rf test_dir

Cela créera la structure de répertoire suivante :

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.py - BAR.py - BAZ.py - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

Exemples : Filtrage de fichiers avec des modèles d'inclusion et d'exclusion

Cas 1 : Aucun modèle d'inclusion, aucun modèle d'exclusion

Commande :

bash
code2prompt test_dir

Résultat

Tous les fichiers sont inclus :

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

Cas 2 : Exclure des types de fichiers spécifiques

Exclure les fichiers .txt :

bash
code2prompt test_dir --exclude="*.txt"

Résultat

Exclus :

  • Tous les fichiers .txt

Inclus :

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

Cas 3 : Inclure des types de fichiers spécifiques

Inclure uniquement les fichiers Python :

bash
code2prompt test_dir --include="*.py"

Résultat

Inclus :

  • Tous les fichiers .py

Exclus :

  • .secret/secret.txt

Cas 4 : Inclure et exclure avec priorité

Inclure les fichiers .py mais exclure les fichiers dans le dossier uppercase :

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

Résultat

Inclus :

  • Tous les fichiers lowercase/1 ayant l'extension .py

Exclus :

  • Tous les fichiers uppercase
  • .secret/secret.txt

Résumé

L'outil de modèle de glob dans code2prompt vous permet de filtrer efficacement des fichiers et des répertoires à l'aide de :

  • --include pour spécifier les fichiers à inclure
  • --exclude pour les fichiers à exclure
  • --include-priority pour résoudre les conflits entre les modèles

Pour pratiquer, configurez le répertoire échantillon, essayez les commandes et voyez comment l'outil filtre les fichiers de manière dynamique.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Tutorials Learn Templates (`website/src/content/docs/fr/docs/tutorials/learn_templates.mdx`)


title: Apprendre les modèles Handlebar avec Code2Prompt

import { Card } from "@astrojs/starlight/components";

Ce tutoriel démontre comment utiliser et créer des modèles Handlebars personnalisés pour la génération d'invites dans l'outil de ligne de commande `code2prompt`.

Prérequis

Assurez-vous d'avoir code2prompt installé. Si vous ne l'avez pas encore installé, reportez-vous au Guide d'installation.


Qu'est-ce que les modèles Handlebars ?

Handlebars est un moteur de templating populaire qui permet de créer des modèles dynamiques à l'aide de placeholders.
Dans code2prompt, les modèles Handlebars sont utilisés pour formater les invites générées en fonction de la structure du codebase et des variables définies par l'utilisateur.

Comment utiliser les modèles Handlebars ?

Vous pouvez utiliser ces modèles en passant le drapeau -t ou --template suivi du chemin vers le fichier de modèle. Par exemple :

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

Syntaxe des modèles

Les modèles Handlebars utilisent une syntaxe simple pour les placeholders et les expressions. Vous placerez les variables entre des doubles accolades {{variable_name}} pour les inclure dans l'invite générée.
Code2prompt fournit un ensemble de variables par défaut que vous pouvez utiliser dans vos modèles :

  • absolute_code_path : Le chemin absolu vers le codebase.
  • source_tree : L'arbre de source du codebase, qui comprend tous les fichiers et répertoires.
  • files : Une liste de fichiers dans le codebase, y compris leurs chemins et contenus.
  • git_diff : Le diff Git du codebase, si applicable.
  • code : Le contenu du code du fichier en cours de traitement.
  • path : Le chemin du fichier en cours de traitement.

Vous pouvez également utiliser des helpers Handlebars pour effectuer des logiques conditionnelles, des boucles et d'autres opérations dans vos modèles. Par exemple :

handlebars
{{#if files}}
  {{#each files}}
    Fichier :
    {{this.path}}
    Contenu :
    {{this.content}}
  {{/each}}
{{else}}
  Aucun fichier trouvé.
{{/if}}

Modèles existants

code2prompt est livré avec un ensemble de modèles intégrés pour les cas d'utilisation courants. Vous pouvez les trouver dans le répertoire templates.

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

Utilisez ce modèle pour générer des invites pour documenter le code. Il ajoutera des commentaires de documentation à toutes les fonctions publiques, méthodes, classes et modules du codebase.

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

Utilisez ce modèle pour générer des invites pour trouver des vulnérabilités de sécurité potentielles dans le codebase. Il recherchera des problèmes de sécurité courants et fournira des recommandations sur la façon de les corriger ou de les atténuer.

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

Utilisez ce modèle pour générer des invites pour nettoyer et améliorer la qualité du code. Il recherchera des opportunités pour améliorer la lisibilité, la conformité aux meilleures pratiques, l'efficacité, la gestion des erreurs, etc.

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

Utilisez ce modèle pour générer des invites pour corriger les bogues dans le codebase. Il aidera à diagnostiquer les problèmes, à fournir des suggestions de correction et à mettre à jour le code avec les corrections proposées.

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

Utilisez ce modèle pour créer une description de pull request GitHub en markdown en comparant le diff Git et le log Git de deux branches.

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

Utilisez ce modèle pour générer un fichier README de haute qualité pour le projet, adapté à l'hébergement sur GitHub. Il analysera le codebase pour comprendre son objectif et sa fonctionnalité, et générera le contenu du README en format Markdown.

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

Utilisez ce modèle pour générer des commits Git à partir des fichiers en scène dans votre répertoire Git. Il analysera le codebase pour comprendre son objectif et sa fonctionnalité, et générera le contenu du message de commit en format Markdown.

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

Utilisez ce modèle pour générer des invites pour améliorer les performances du codebase. Il recherchera des opportunités d'optimisation, fournira des suggestions spécifiques et mettra à jour le code avec les modifications.

Variables définies par l'utilisateur

code2prompt prend en charge l'utilisation de variables définies par l'utilisateur dans les modèles Handlebars. Toutes les variables du modèle qui ne font pas partie du contexte par défaut (absolute_code_path, source_tree, files) seront traitées comme des variables définies par l'utilisateur.

Lors de la génération d'invites, code2prompt invitera l'utilisateur à saisir des valeurs pour ces variables définies par l'utilisateur. Cela permet une personnalisation supplémentaire des invites générées en fonction des entrées utilisateur.

Par exemple, si votre modèle inclut {{challenge_name}} et {{challenge_description}}, vous serez invité à saisir des valeurs pour ces variables lors de l'exécution de code2prompt.

Cette fonctionnalité permet de créer des modèles réutilisables qui peuvent être adaptés à différents scénarios en fonction des informations fournies par l'utilisateur.

Cette page a été traduite automatiquement pour votre commodité. Veuillez vous référer à la version anglaise pour le contenu original.


Website Src Content Docs Fr Docs Tutorials Tui (`website/src/content/docs/fr/docs/tutorials/tui.mdx`)


title: Utilisation de l'interface en terminal (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2prompt` dispose d'une interface utilisateur en terminal (TUI) entièrement interactive. Ce guide vous accompagne dans le lancement du TUI et la maîtrise de ses cinq onglets principaux.

Lancer le TUI

Pour ouvrir l'interface interactive, ajoutez simplement le flag --tui à votre commande avec le chemin de votre projet :

bash
code2prompt chemin/vers/votre/base-de-code --tui

1. Onglet Sélection (Arborescence de fichiers)

L'onglet Sélection est l'endroit où vous organisez le contexte exact que vous souhaitez envoyer au LLM. Il affiche une vue hiérarchique de votre projet, respectant vos règles .gitignore et .c2pconfig.

  • Navigation : Utilisez ↑ / ↓ pour déplacer le curseur, et ← / → pour développer ou réduire les répertoires.
  • Sélection : Appuyez sur Espace pour sélectionner ou désélectionner un fichier ou un répertoire entier.
  • Mode recherche : Appuyez sur s ou / pour entrer en mode recherche.
  • Vous pouvez taper du texte ou utiliser des caractères génériques (*, ?) pour filtrer instantanément l'arborescence.
  • Appuyez sur Entrée ou Échap pour quitter le mode recherche et revenir à la navigation normale.

2. Onglet Paramètres

Besoin d'ajuster la façon dont la sortie est formatée avant la génération ? L'onglet Paramètres vous offre des cases à cocher visuelles et des menus déroulants pour votre session active.


3. Onglet Statistiques

Avant de dépenser de l'argent en envoyant un prompt massif à un LLM, utilisez l'onglet Statistiques pour comprendre votre budget de tokens.

Utilisez ← / → pour basculer entre trois vues puissantes :


4. Onglet Template

L'onglet Template est l'endroit où la magie opère. Il dispose d'une mise en page multi-colonnes responsive pour vous aider à créer le template Handlebars parfait.

Lorsque vous êtes dans l'onglet Template, vous pouvez instantanément déplacer votre focus entre trois sous-panneaux à l'aide de raccourcis clavier :


5. Onglet Sortie

Une fois que vous avez sélectionné vos fichiers, ajusté vos paramètres et choisi votre template, appuyez sur Entrée pour générer la sortie finale.

L'onglet Sortie affiche le prompt final exactement tel qu'il sera envoyé au LLM.

  • Défiler : Utilisez ↑ / ↓, PgUp ou PgDn pour parcourir le texte généré.
  • Copier : Appuyez sur c pour copier instantanément l'intégralité du prompt dans votre presse-papiers système.
  • Sauvegarder : Appuyez sur s pour enregistrer le prompt directement dans un fichier Markdown local (par exemple, prompt_20260613_204753.md).

Si vous réalisez que vous avez manqué un fichier, appuyez simplement sur 1 pour revenir à l'onglet Sélection, cochez le fichier et appuyez sur Entrée pour régénérer la sortie en temps réel.


Website Src Content Docs Ja Docs Explanations Glob Pattern Filter (`website/src/content/docs/ja/docs/explanations/glob_pattern_filter.mdx`)


title: Globパターンフィルターの動作原理

Code2Prompt は glob パターンを使用してファイルとディレクトリを含めたり除外したりし、tree や grep などのツールと同様に動作します。2 つの独立したリストの glob パターンを渡すことができます:

  • インクルードリスト (--include または -i) - "これらのパターンはファイルを許可する"
  • エクスクルードリスト (--exclude または -e) - "これらのパターンはファイルを禁止する"

Code2prompt は、プロジェクト内のすべてのファイルについて、それを保持するか破棄するかを決定する必要があります。このページでは、ルールとその背後にある設計選択について説明します。


1. 集合と記号

説明全体を通して、通常の集合記法を使用します

記号 意味
$A$ 少なくとも 1 つのインクルードパターンに一致するファイルの集合
$B$ 少なくとも 1 つのエクスクルードパターンに一致するファイルの集合
$\Omega$ プロジェクトツリー全体(宇宙)
$C = A \cap B$ 両方のリストに一致するファイル(重複)
$D = \Omega \setminus (A \cup B)$ どちらのリストにも一致しないファイル

2. 4 つの状況

4 つの状況の概要

インクルードリスト エクスクルードリスト 保持されるファイル
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. インクルードリストなし、エクスクルードリストなし

    パターンが指定されていない場合、すべてのファイルが保持されます(Ω)。

  2. エクスクルードリストのみ

    この場合、Code2Prompt はブラックリストとして機能し、除外されたパターンに一致するファイルを削除します( Ω \ B = ¬B)。

  3. インクルードリストのみ

    インクルードリストのみが指定されている場合、Code2Prompt はホワイトリストとして機能し、含まれるパターンに一致するファイルのみを保持します(A)。

  4. インクルードおよびエクスクルードリスト

    両方のリストが指定されている場合、Code2Prompt はインクルードパターンに一致するファイルを保持しますが、エクスクルードパターンに一致するものは削除します(A \ B)。


3. 重複についてさらに詳しく

両方のリストが存在する場合(A ≠ ∅、B ≠ ∅)、重複Cと残りDについて
4 つの論理的可能性があります。

Cが欲しい? Dが欲しい? 合理的?
いいえ いいえ デフォルトの動作(A \ B)
はい いいえ ケース 3 と同じ動作(A)
いいえ はい 驚き("要求したCを破棄し、要求しなかったものを保持する")
はい はい ケース 1 と同じ動作(Ω)

このため、--include-priorityオプションが削除されました。なぜなら、インクルードリストのみを持つ場合(ケース 3)と同じ結果になるからです。

4. クイックリファレンステーブル

保持したいもの… 使用する
すべて -iなし、-eなし
いくつかのパターン以外のすべて -eのみ
パターンに一致するもののみ -iのみ
-iに一致するもの、マイナス-eに一致するもの -iおよび-e

この設計はメンタルモデルをシンプルに保ちます:

  • インクルードリストは存在するとすぐにホワイトリストになります。
  • エクスクルードリストはその上に重ねられたブラックリストです。
  • 重複はデフォルトで破棄されます

Website Src Content Docs Ja Docs Explanations Glob Patterns (`website/src/content/docs/ja/docs/explanations/glob_patterns.md`)


title: グロブパターンの理解

グロブパターンは、ワイルドカード文字を使用してファイル名とパスを一致させるシンプルで強力な方法です。これらは、コマンドラインインターフェイスやプログラミング言語で、ファイル名やディレクトリのセットを指定するために一般的に使用されます。以下は、最も一般的に使用されるグロブパターンの内訳です。

基本的なワイルドカード

  • *: 任意の数の文字(0文字を含む)に一致します。

    • 例: *.txtは、.txtで終わるすべてのファイルに一致します。
  • ?: ちょうど1つの文字に一致します。

    • 例: file?.txtは、file1.txtやfileA.txtには一致しますが、file10.txtには一致しません。
  • []: 括弧内に含まれる任意の1つの文字に一致します。

    • 例: file[1-3].txtは、file1.txt、file2.txt、file3.txtに一致します。
  • [!]または[^]: 括弧内に含まれない任意の文字に一致します。

    • 例: file[!1-3].txtは、file4.txtやfileA.txtには一致しますが、file1.txtには一致しません。

高度なパターン

  • **: 任意の数のディレクトリとサブディレクトリに再帰的に一致します。

    • 例: **/*.txtは、現在のディレクトリとすべてのサブディレクトリ内の.txtファイルをすべて一致させます。
  • {}: カンマで区切られたパターンのいずれかに一致します。

    • 例: file{1,2,3}.txtは、file1.txt、file2.txt、file3.txtに一致します。

例

  1. ディレクトリ内のすべてのテキストファイルを一致させる:

    sh
    *.txt
  2. 拡張子前に1桁の数字が付くファイルをすべて一致させる:

    sh
    file?.txt
  3. .jpgまたは.pngの拡張子を持つファイルを一致させる:

    sh
    *.{jpg,png}
  4. サブディレクトリ内のすべての.txtファイルを一致させる:

    sh
    **/*.txt
  5. aまたはbで始まり、.txtで終わるファイルを一致させる:

    sh
    {a,b}*.txt

使用例

  • コマンドラインツール: グロブパターンは、ls、cp、mv、rmなどのコマンドラインツールで、複数のファイルまたはディレクトリを指定するために広く使用されています。
  • プログラミング言語: Python、JavaScript、Rubyなどの言語は、Pythonのglobライブラリなど、グロブパターンをファイルの一致に使用するためのライブラリをサポートしています。
  • ビルドシステム: Makefileなどのツールは、ソースファイルと依存関係を指定するためにグロブパターンを使用しています。

結論

グロブパターンは、ファイル名とパスを一致させるための柔軟で直感的な方法を提供し、スクリプト作成、自動化、ファイル管理タスクに不可欠なものとなっています。これらのパターンを理解して活用することで、ファイルとディレクトリの処理における生産性と効率を大幅に向上させることができます。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Explanations Tokenizers (`website/src/content/docs/ja/docs/explanations/tokenizers.md`)


title: Code2Promptにおけるトークン化

言語モデルを扱う場合、テキストをモデルが理解できる形式—トークン(数列)に変換する必要があります。この変換は、トークナイザーによって処理されます。


表示されるトークン数は推定値です。Code2Promptは処理と任意の行番号追加を
行った後、各ファイルのトークンを並列に数え、テンプレートの推定コストを加算します。
完成したプロンプト全体を再度トークン化することはありません。断片の境界や
テンプレートによる変換で実際の数は変わるため、推定値が上限になる保証はありません。
数値フィールド名token_countは変わらず、JSONの外側の構造とシリアライズ時の
エスケープは計算に含まれません。

トークナイザーとは?

トークナイザーは、生のテキストをトークンに変換します。これは、言語モデルが入力を処理するための基本的な構成要素です。これらのトークンは、トークナイザーの設計に応じて、単語、サブワード、または個々の文字を表すことができます。

code2promptでは、tiktokenトークナイザーを使用します。これは、効率的で堅牢であり、OpenAIモデルに最適化されています。
その機能は、公式リポジトリで確認できます。

👉 tiktoken GitHub リポジトリ

トークナイザー全般について詳しく知りたい場合は、以下を参照してください。

👉 Mistral トークン化ガイド.

`code2prompt`での実装

トークン化は、tiktoken-rsを使用して実装されます。tiktokenは、OpenAIモデルで使用される以下のエンコーディングをサポートしています。

CLI引数 エンコーディング名 OpenAIモデル
cl100k cl100k_base ChatGPTモデル、text-embedding-ada-002
p50k p50k_base コードモデル、text-davinci-002、text-davinci-003
p50k_edit p50k_edit text-davinci-edit-001、code-davinci-edit-001などの編集モデル
r50k r50k_base(またはgpt2) davinciなどのGPT-3モデル
gpt2 o200k_base GPT-4oモデル

トークナイザーの詳細については、OpenAI Cookbookを参照してください。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs How To Cli (`website/src/content/docs/ja/docs/how_to/cli.mdx`)


title: Code2Prompt 基本的な使い方

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

`Code2Prompt` の使用方法へようこそ。

使用方法

コードベースからプロンプトを生成する:

sh
code2prompt path/to/codebase

プロンプトを生成し、クリップボードにコピーする:

sh
code2prompt path/to/codebase -c

インタラクティブな TUI を起動する:

sh
code2prompt path/to/codebase --tui

トークンマップを表示する:

sh
code2prompt path/to/codebase --token-map

カスタム Handlebars テンプレートを使用する:

sh
code2prompt path/to/codebase -t path/to/template.hbs

Glob パターンでファイルをフィルタリングする:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Glob パターンでファイルを除外する:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

除外パターンに基づいてソースツリーからファイル/フォルダを除外する:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

生成されたプロンプトのトークン数を表示する:

sh
code2prompt path/to/codebase --token-format=format

トークン数計算に使用するトークナイザーを指定する:

sh
code2prompt path/to/codebase --encoding=p50k

サポートされているトークナイザー: cl100k, p50k, p50k_edit, r50k_bas.

生成されたプロンプトを出力ファイルに保存する:

sh
code2prompt path/to/codebase -O output.txt

出力を JSON 形式で表示する:

sh
code2prompt path/to/codebase -F JSON

JSON の出力例:

json
{
  "prompt": "<生成されたプロンプト>",
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT モデル, text-embedding-ada-002",
  "files": []
}

ステージされたファイル用に Git コミットメッセージを生成する:

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

ステージされたファイル用にブランチ比較のプルリクエストを生成する:

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

コードブロックに行番号を付与する:

sh
code2prompt path/to/codebase --line-numbers

Markdown のコードブロック内でコードのラップを無効にする:

sh
code2prompt path/to/codebase --no-codeblock

Code2Prompt はトークン効率の良いプロンプトを生成する優れたツールです。以下のような様々なユースケースに活用できます:

  • コードを別の言語に変換する
  • バグやセキュリティ脆弱性を検出する
  • コードをドキュメント化する
  • 新機能を実装する

Website Src Content Docs Ja Docs How To Config (`website/src/content/docs/ja/docs/how_to/config.mdx`)


title: .c2pconfig ファイルの作成

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

このガイドでは、`.c2pconfig` ファイルを作成・使用して、プロンプト生成ワークフローを自動化する方法を学びます。

手動で長い除外パターンやトークナイザー設定、カスタム変数を書き込むのは面倒です。.c2pconfig 設定ファイルを作成すれば、プロジェクトの設定を「一度設定して忘れる」ことができます。Code2Prompt は作業ディレクトリでこのファイルを自動的に探し、設定をシームレスに適用します。

以下に、最初の設定ファイルを作成する手順を示します。


1. 設定ファイルの初期化

ターミナルでプロジェクトのルートディレクトリに移動し、.c2pconfig という名前のファイルを作成します。

bash
cd path/to/your/project
touch .c2pconfig

2. 基本設定を TOML 形式で記述

エディタで .c2pconfig を開き、以下の内容を貼り付けます(TOML 形式です)。

toml
# デフォルトの動作設定
default_output = "clipboard"    # オプション: stdout, clipboard, file
output_format = "xml"           # オプション: markdown, json, xml
line_numbers = false            # コードブロックに行番号を付与するか
encoding = "o200k"              # 使用するトークナイザーを LLM に合わせる

# グローバルなフィルタリングルール
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**",
    "**/target/**",
    "tests/fixtures/**",
    "package-lock.json"
]

3. 引数なしで実行

.c2pconfig をプロジェクトのルートに保存したら、フラグを付けずに実行できます。

bash
code2prompt .

Code2Prompt は自動的に .c2pconfig を読み込み、指定したグロブパターンでファイルをフィルタリングし、行番号を付与し、設定に従って出力形式を整えます。


次のステップ

高度なワークフローや変数、デフォルト設定キーをさらに深く掘り下げるには、以下のチュートリアルをご覧ください:


Website Src Content Docs Ja Docs How To Filter Files (`website/src/content/docs/ja/docs/how_to/filter_files.md`)


title: Code2Promptでのファイルフィルタリング

使用方法

コードベースディレクトリからプロンプトを生成する:

sh
code2prompt path/to/codebase

カスタムHandlebarsテンプレートファイルを使用する:

sh
code2prompt path/to/codebase -t path/to/template.hbs

グロブパターンを使用してファイルをフィルタリングする:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

グロブパターンを使用してファイルを除外する:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

ソースツリーから除外パターンに基づいてファイル/フォルダを除外する:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

生成されたプロンプトのトークン数を表示する:

sh
code2prompt path/to/codebase --token-format=format

トークン数にトークナイザを指定する:

sh
code2prompt path/to/codebase --encoding=p50k

サポートされているトークナイザ: cl100k, p50k, p50k_edit, r50k_bas.

[!注意]
詳細はトークナイザを参照してください。

生成されたプロンプトを出力ファイルに保存する:

sh
code2prompt path/to/codebase --output=output.txt

出力をJSONとして印刷する:

sh
code2prompt path/to/codebase --json

JSON出力の構造は以下の通りである:

json
{
  "prompt": "<生成されたプロンプト>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPTモデル、text-embedding-ada-002",
  "files": []
}

Gitコミットメッセージ(ステージングされたファイルに対して)を生成する:

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Pull Requestをブランチ比較(ステージングされたファイルに対して)で生成する:

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

ソースコードブロックに行番号を追加する:

sh
code2prompt path/to/codebase --line-numbers

Markdownコードブロック内のコードのラッピングを無効にする:

sh
code2prompt path/to/codebase --no-codeblock
  • コードを別の言語に書き直す。
  • バグ/セキュリティ脆弱性を発見する。
  • コードを文書化する。
  • 新しい機能を実装する。

最初にこれは、Claude 3.0の200Kコンテキストウィンドウを利用するために個人使用で書いたものであり、かなり役に立ったのでオープンソース化することにした!

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs How To Install (`website/src/content/docs/ja/docs/how_to/install.mdx`)


title: Code2Prompt のインストール

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Code2Prompt のインストールガイドへようこそ。このドキュメントでは、Windows、macOS、Linuxを含む様々なプラットフォームへのCode2Promptのインストール手順をステップごとに説明します。

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

前提条件

システムにRustとcargoがインストールされていることを確認してください。

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

これは、RustとCargoの最新安定版をインストールする公式の方法です。Rustをインストールした後、PATH変数を更新してください。ターミナルを再起動するか、インストーラーが提案するコマンドを実行します。

sh
source $HOME/.cargo/env

すべてが正しくインストールされていることを確認するには、次のコマンドを実行します。

sh
cargo --version
git --version

コマンドラインインターフェイス(CLI)👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 GitHubから最新の(未公開の)バージョンをインストールする

crates.ioで公開される前に最新の機能や修正を使用したい場合:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

ソースビルド

開発者がソースからビルドしたり、プロジェクトに貢献したい場合に最適です。

  1. 🛠️ 前提条件をインストールする :

  2. 📥 リポジトリをクローンする :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 バイナリをインストールする :

    ソースからビルドしてインストールするには:

    sh
    cargo install --path crates/code2prompt

    バイナリをインストールせずにビルドするには:

    sh
    cargo build --release

    バイナリはtarget/releaseディレクトリで利用できます。

  4. 🚀 実行する :

    sh
    code2prompt --help

バイナリリリース

ソースからビルドせずに最新バージョンを使用したいユーザーに最適です。

リリースからお使いのOSの最新バイナリをダウンロードしてください。

⚠️ バイナリリリースは、最新のGitHubバージョンよりも遅れる場合があります。最先端の機能を使用するには、ソースからビルドすることを検討してください。

AUR

特にArch Linuxユーザー向けに、code2promptはAURで利用可能です。

code2promptはAURで利用できます。AURヘルパーを使用してインストールしてください。

sh
paru/yay -S code2prompt

Nix

Nixを使用している場合、nix-envまたはnixプロファイルのいずれかを使用してインストールできます。

sh
# without flakes:
nix-env -iA nixpkgs.code2prompt
# with flakes:
nix profile install nixpkgs#code2prompt

ソフトウェア開発キット(SDK)🐍

Pypi

PypiからPythonバインディングをダウンロードできます

sh
pip install code2prompt_rs

ソースビルド

  1. 🛠️ 前提条件をインストールする :

  2. 📥 リポジトリをクローンする :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 依存関係をインストールする :

    uvは.venvを作成し、開発用依存関係をロックして、ネイティブ拡張を編集可能モードでビルドします。

    sh
    uv sync
  4. 🧪 テストを実行する :

    同期済みの環境でプロジェクトのテストコマンドを実行します。

    sh
    uv run pytest

Model Context Protocol(MCP)🤖

自動インストール

code2promptMCPサーバーは、近日中にMCPレジストリで利用できるようになります。

手動インストール

code2promptMCPサーバーはまだプロトタイプであり、近日中にメインのリポジトリに統合されます。

Cline,GooseまたはAiderで使用するために、ローカルでMCPサーバーを実行するには:

  1. 🛠️ 前提条件をインストールする :

  2. 📥 リポジトリをクローンする :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 依存関係をインストールする :

    ryeコマンドは、仮想環境を作成し、.venvフォルダ内のすべての依存関係をインストールします。

    sh
    rye sync
  4. 🚀 サーバーを実行する :

    MCPサーバーはインストールされました。次のコマンドを使用して実行できます:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 エージェントとの統合 :

    text
    例えば、次のような構成を使用して、`Cline`と統合できます:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs How To Ssh (`website/src/content/docs/ja/docs/how_to/ssh.md`)


title: Code2prompt CLIをSSHで使用する

なぜ動作しないのか?

SSH経由でリモートサーバー上でcode2prompt CLIを実行しようとすると、コマンドはクリップボードを見つけることができません。これは、code2prompt CLIが生成されたプロンプトをコピーするためにクリップボードを使用するためであり、SSHセッションは通常、ローカルクリップボードにアクセスできないためです。

解決策

code2prompt CLIをSSHで使用するには、クリップボードにコピーする代わりに、出力先をファイルにリダイレクトすることができます。これにより、プロンプトを生成し、後で使用するために保存することができます。

--output-fileオプションを使用して、生成されたプロンプトが保存される出力ファイルを指定します。例えば:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs How To Tui (`website/src/content/docs/ja/docs/how_to/tui.mdx`)


title: Code2Prompt ターミナル UI (TUI) の使用

import { Card } from "@astrojs/starlight/components";

`Code2Prompt` のインタラクティブなターミナル UI (TUI) を使用する方法をご紹介します。

TUI の起動

以下のように --tui フラグを付けてコマンドを実行すると、TUI が起動します。

sh
code2prompt path/to/codebase --tui

1. 選択タブ (ファイルツリー)

このタブでは、LLM に送信する正確なコンテキストを選択できます。.gitignore と .c2pconfig のルールが適用された階層ビューが表示されます。

  • ナビゲーション: ↑ / ↓ でカーソルを移動、← / → でディレクトリを展開/縮小
  • 選択: Space でファイルまたはディレクトリ全体を選択/解除
  • 検索: s または / で検索モードに入り、テキストやワイルドカード (*, ?) を入力して即座にフィルタリング
  • 終了: Enter または Esc で検索モードを抜け、通常のナビゲーションに戻ります

2. 設定タブ

出力形式やトークナイザーなど、生成前に調整したい設定を視覚的に変更できます。

3. 統計タブ

トークン使用量を確認し、LLM に送信する前にコストを把握できます。

← / → で 3 つのビューを切り替えます。

4. テンプレートタブ

ここで Handlebars テンプレートを作成・編集できます。複数列レイアウトで直感的にテンプレートを構築できます。

5. 出力タブ

最終的なプロンプトが表示されます。c でクリップボードにコピー、s でローカルの Markdown ファイルに保存できます。


Website Src Content Docs Ja Docs References Command Line Options (`website/src/content/docs/ja/docs/references/command_line_options.md`)


title: Code2Prompt コマンドラインオプション

コマンドラインオプション

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs References Default Template (`website/src/content/docs/ja/docs/references/default_template.md`)


title: Code2Prompt のデフォルト テンプレート

デフォルト テンプレート

text
./
    ├── ja/
    │   ├── ブログ/
    │   └── ドキュメント/
    ├── fr/
    │   ├── blog/
    │   └── docs/
    ├── de/
    │   ├── blog/
    │   └── docs/
    ├── es/
    │   ├── blog/
    │   └── docs/

becomes

text
./
    ├── ja/
    │   ├── ブログ/
    │   └── ドキュメント/
    ├── fr/
    │   ├── ../../blog/
    │   └── ../../docs/
    ├── de/
    │   ├── ../../blog/
    │   └── ../../docs/
    ├── es/
    │   ├── ../../blog/
    │   └── ../../docs/

so the code blocks ,commands and variable names remain the same
thus

Here is the complete response


title: Code2Prompt のデフォルト テンプレート

デフォルト テンプレート

text
./
    ├── ja/
    │   ├── ブログ/
    │   └── ドキュメント/
    ├── fr/
    │   ├── ../../blog/
    │   └── ../../docs/
    ├── de/
    │   ├── ../../blog/
    │   └── ../../docs/
    ├── es/
    │   ├── ../../blog/
    │   └── ../../docs/

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Tutorials Configuration (`website/src/content/docs/ja/docs/tutorials/configuration.mdx`)


title: Code2Prompt の設定 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

手動で長い除外パターンやトークナイザー設定を書くのは面倒です。このチュートリアルでは、**`.c2pconfig` 設定ファイル** を使用して「一度設定して忘れる」方式でプロジェクト設定を管理する方法を紹介します。

前提条件

code2prompt がインストールされていることを確認してください。未インストールの場合は、インストールガイド を参照してください。TOML の基本構文は知っておくと便利ですが必須ではありません。

`.c2pconfig` とは?

.c2pconfig は TOML 形式の設定ファイルです。code2prompt は実行時に自動的にこのファイルを探し、設定を適用します。

  • フィルタリング: 永続的な include / exclude パターン
  • 出力形式: デフォルトで JSON、Markdown、XML のいずれかを選択
  • テンプレートコンテキスト: Handlebars テンプレートに渡す変数を事前定義

クイックスタート

プロジェクトのルートに .c2pconfig を作成し、基本設定を書き込みます。

toml
# デフォルト設定
default_output = "stdout"   # オプション: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MyAwesomeProject"
author = "Developer"

設定項目リファレンス

キー 型 説明
path String デフォルトのコードベースパス(通常 .)
include_patterns Array 取り込むファイルの glob パターン
exclude_patterns Array 除外するファイルの glob パターン
line_numbers Boolean true の場合、コードブロックに行番号を付与
absolute_path Boolean 絶対パスを使用するか
full_directory_tree Boolean 除外ファイルでもディレクトリツリーを完全に生成
output_format String markdown, json, xml のいずれか
sort_method String name_asc, name_desc, date_asc, date_desc
encoding String 使用するトークナイザー (cl100k, p50k, o200k)
diff_enabled Boolean Git diff (HEAD vs Index) を含める
token_map_enabled Boolean トークン使用マップを表示

実装手順

1. **設定ファイルの作成** ```bash touch .c2pconfig ```
  1. グローバルフィルタの設定
    node_modules やビルド成果物を除外して、LLM にクリーンなコンテキストを提供します。

    toml
    exclude_patterns = [
      "**/node_modules/**",
      "package-lock.json",
      "dist/**"
    ]
  2. トークナイザーの選択
    使用する LLM に合わせてトークナイザーを設定します。GPT‑4o なら o200k、Claude や GPT‑4 なら cl100k。

    toml
    encoding = "o200k"
  3. ユーザー変数の追加
    Handlebars テンプレートで使用するカスタム変数を [user_variables] に定義します。

    toml
    [user_variables]
    project_goal = "セキュリティ向上のための認証モジュールのリファクタリング"
  4. フラグなしで実行
    すべての設定が .c2pconfig に保存されたら、シンプルに実行します。

    bash
    code2prompt .

優先順位の理解

CLI 引数 > .c2pconfig > デフォルト設定 の順に優先されます。CLI で一時的にオーバーライドしたい場合に便利です。

「レビュー向け」設定例

コードレビュー用に最適化された設定例です。

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

次のステップ


Website Src Content Docs Ja Docs Tutorials Getting Started (`website/src/content/docs/ja/docs/tutorials/getting_started.mdx`)


title: Code2Prompt の使い方を始める

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

Code2Promptへようこそ! このチュートリアルでは、Code2Promptを使用してコードベースからAI対応のプロンプトを生成する方法を総合的に紹介します。コア機能を探求し、コマンドラインインターフェイス(CLI)、ソフトウェア開発キット(SDK)、モデルコンテキストプロトコル(MCP)などの異なる統合方法での使用法を示します。

Code2Promptとは?

Code2Promptは、コードベースと大規模言語モデル(LLM)間のギャップを埋めるように設計された汎用ツールです。関連するコードスニペットをインテリジェントに抽出し、強力なフィルタリングを適用し、LLM消費用に最適化された構造化されたプロンプトにフォーマットします。これにより、コードドキュメント、バグ検出、リファクタリングなどのタスクが簡素化されます。

Code2Promptは異なる統合ポイントを提供します:

コード摂取とプロンプトの基礎を提供するコアRustライブラリです。 クイックプロンプト生成のためのユーザーフレンドリーなコマンドラインインターフェイス。インタラクティブな使用とワンオフタスクに最適です。 Pythonプロジェクトへのシームレスな統合のための強力なソフトウェア開発キット(SDK)。より大きなワークフロー内でのプロンプト生成の自動化に最適です。 LLMエージェントとの高度な統合のためのモデルコンテキストプロトコル(MCP)サーバー。コードベースとの高度なリアルタイムインタラクションを可能にします。

📥 インストール

すべての方法(CLI、SDK、MCP)の詳細なインストール手順については、総合的なインストールガイドを参照してください。

🏁 プロンプトの生成:CLIの例

CLIを使用した簡単な例から始めましょう。サンプルプロジェクトを作成します。

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

ここで、プロンプトを生成します。

bash
code2prompt my_project

これにより、プロンプトがクリップボードにコピーされます。これをカスタマイズできます。

  • フィルタリング: code2prompt my_project --include="*.rs" --exclude="tests/*"(.rsファイルのみを含め、testsディレクトリを除外)
  • 出力ファイル: code2prompt my_project --output-file=my_prompt.txt
  • JSON出力: code2prompt my_project -O json(構造化されたJSON出力)
  • カスタムテンプレート: code2prompt my_project -t my_template.hbs(my_template.hbsを作成する必要があります)

詳細な使用法については、コンテキストフィルタリングの学習とハンドルバーテンプレートの学習のチュートリアルを参照してください。

🐍 SDK統合(Python)

プログラム制御を使用するには、Python SDKを使用します。

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

これには、SDK(pip install code2prompt_rs)のインストールが必要です。詳細については、SDKのドキュメントを参照してください。

🤖 MCPサーバー統合(高度な)

LLMエージェントとの高度な統合については、code2prompt MCPサーバーを実行します(詳細はインストールガイドを参照)。これにより、エージェントがコードコンテキストを動的に要求できます。これは高度な機能であり、プロジェクトのWebサイトでさらにドキュメントが提供されています。

Code2Promptの機能をマスターし、ワークフローに統合するには、高度なチュートリアルとドキュメントを参照してください。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Tutorials Learn Filters (`website/src/content/docs/ja/docs/tutorials/learn_filters.mdx`)


title: Learn Context Filtering with Code2Prompt

import { Card } from "@astrojs/starlight/components";

このチュートリアルでは、`code2prompt` CLIの**globパターン ツール**を使用して、ファイルやディレクトリをフィルタリングし、管理する方法を説明します。

Globパターンは、treeやgrepなどのツールと同様に、強力なフィルタリング機能を提供します。詳細な説明は、こちらをご覧ください。


前提条件

code2promptがインストールされていることを確認してください。まだインストールしていない場合は、インストールガイドを参照してください。


インクルードおよびエクスクルードパターンの理解

Globパターンは、ファイルやディレクトリのフィルタリングルールを指定できます。

  • インクルードパターン (--include): 含めたいファイルやディレクトリを指定します。
  • エクスクルードパターン (--exclude): 除外したいファイルやディレクトリを指定します。
  • 優先度 (--include-priority): インクルードパターンとエクスクルードパターンの競合を解決します。

環境の設定

Globパターンを使って練習するために、サンプルフォルダー構造とファイルを作成しましょう。

テスト構造を生成するBashスクリプト

以下のスクリプトを実行して、一時的なディレクトリ構造を設定します。

bash
#!/bin/bash

# ベースディレクトリを作成
mkdir -p test_dir/{lowercase,uppercase,.secret}

# 構造内のファイルを作成
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

後で構造をクリーンアップするには、次のコマンドを実行します。

bash
rm -rf test_dir

以下のディレクトリ構造が作成されます。

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.PY - BAR.PY - BAZ.PY - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

例: インクルードおよびエクスクルードパターンを使用したファイルのフィルタリング

ケース1: インクルードなし、エクスクルードなし

コマンド:

bash
code2prompt test_dir

結果

すべてのファイルが含まれます:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

ケース2: 特定のファイルタイプをエクスクルードする

.txtファイルをエクスクルードします:

bash
code2prompt test_dir --exclude="*.txt"

結果

エクスクルード:

  • すべての.txtファイル

インクルード:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

ケース3: 特定のファイルタイプをインクルードする

Pythonファイルのみを含めます:

bash
code2prompt test_dir --include="*.py"

結果

インクルード:

  • すべての.pyファイル

エクスクルード:

  • .secret/secret.txt

ケース4: インクルードとエクスクルードを優先度で制御する

.pyファイルを含めますが、uppercaseフォルダ内のファイルをエクスクルードします:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

結果

インクルード:

  • lowercase内のすべての.py拡張子のファイル

エクスクルード:

  • すべてのuppercaseファイル
  • .secret/secret.txt

まとめ

code2promptのglobパターン ツールを使用すると、以下のようにファイルやディレクトリを効果的にフィルタリングできます。

  • --includeでインクルードするファイルを指定
  • --excludeでエクスクルードするファイルを指定
  • --include-priorityでパターン間の競合を解決

練習として、サンプルディレクトリを設定し、コマンドを実行して、ツールがファイルを動的にフィルタリングする様子を確認してください。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Tutorials Learn Templates (`website/src/content/docs/ja/docs/tutorials/learn_templates.mdx`)


title: Code2PromptでHandlebarテンプレートを学ぶ

import { Card } from "@astrojs/starlight/components";

このチュートリアルでは、Code2Prompt CLIのためのカスタムHandlebarsテンプレートの作成と使用方法を説明します。

前提条件

code2promptがインストールされていることを確認してください。まだインストールしていない場合は、インストールガイドを参照してください。


Handlebarsテンプレートとは

Handlebarsは、プレースホルダを使用した動的テンプレートを作成できる人気のテンプレートエンジンです。
code2promptでは、Handlebarsテンプレートは、コードベースの構造とユーザー定義の変数に基づいて生成されたプロンプトをフォーマットするために使用されます。

Handlebarsテンプレートの使用方法

テンプレートファイルへのパスを-tまたは--templateフラグで指定することで、これらのテンプレートを使用できます。例:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

テンプレート構文

Handlebarsテンプレートは、プレースホルダと式のためのシンプルな構文を使用します。変数は、生成されたプロンプトに含めるために、{{variable_name}}の二重中括弧内に配置します。
code2promptは、テンプレートで使用できるデフォルトの変数のセットを提供します。

  • absolute_code_path: コードベースへの絶対パス。
  • source_tree: コードベースのソースツリーで、すべてのファイルとディレクトリが含まれます。
  • files: コードベース内のファイルのリストで、パスと内容が含まれます。
  • git_diff: コードベースのgit diff。適用可能な場合。
  • code: 処理中のファイルのコード内容。
  • path: 処理中のファイルのパス。

Handlebarsヘルパーを使用して、テンプレート内で条件付きロジック、ループ、その他の操作を実行することもできます。例:

handlebars
{{#if files}}
  {{#each files}}
    ファイル:
    {{this.path}}
    内容:
    {{this.content}}
  {{/each}}
{{else}}
  ファイルが見つかりません。
{{/if}}

既存のテンプレート

code2promptには、一般的なユースケースのための組み込みテンプレートのセットが付属しています。これらはtemplatesディレクトリで見つけることができます。

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

このテンプレートを使用して、コードのドキュメント化のためのプロンプトを生成します。コードベース内のすべてのパブリック関数、メソッド、クラス、およびモジュールにドキュメントコメントを追加します。

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

このテンプレートを使用して、コードベース内の潜在的なセキュリティ脆弱性を見つけるためのプロンプトを生成します。一般的なセキュリティ問題を探し、それらを修正または軽減する方法に関する推奨事項を提供します。

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

このテンプレートを使用して、コードの品質を向上および改善するためのプロンプトを生成します。読みやすさ、ベストプラクティスの遵守、効率性、エラー処理などの改善機会を探します。

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

このテンプレートを使用して、コードベース内のバグを修正するためのプロンプトを生成します。問題の診断、修正の提案、およびコードの更新を行います。

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

このテンプレートを使用して、2つのブランチのgit diffとgitログを比較して、GitHubプルリクエストの説明をマークダウンで作成します。

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

このテンプレートを使用して、プロジェクト用の高品質のREADMEファイルを生成します。コードベースを分析してその目的と機能を理解し、マークダウン形式でREADMEコンテンツを生成します。

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

このテンプレートを使用して、gitディレクトリ内のステージングされたファイルからgitコミットを生成します。コードベースを分析してその目的と機能を理解し、マークダウン形式でgitコミットメッセージコンテンツを生成します。

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

このテンプレートを使用して、コードベースのパフォーマンスを向上させるためのプロンプトを生成します。最適化の機会を探し、特定の提案を提供し、コードを更新します。

ユーザー定義変数

code2promptは、Handlebarsテンプレートでのユーザー定義変数の使用をサポートしています。テンプレート内のデフォルトコンテキスト(absolute_code_path、source_tree、files)に含まれない変数は、ユーザー定義変数として扱われます。

プロンプト生成中、code2promptはユーザー定義変数の値を入力するようユーザーに求めます。これにより、ユーザーの入力に基づいて生成されたプロンプトをさらにカスタマイズできます。

たとえば、テンプレートに{{challenge_name}}と{{challenge_description}}が含まれている場合、code2promptを実行すると、これらの変数の値を入力するよう求められます。

この機能により、ユーザーが提供した情報に基づいてさまざまなシナリオに適応できる、再利用可能なテンプレートを作成できます。

このページは便宜上、自動的に翻訳されています。元のコンテンツについては英語版を参照してください。


Website Src Content Docs Ja Docs Tutorials Tui (`website/src/content/docs/ja/docs/tutorials/tui.mdx`)


title: ターミナル UI (TUI) の使用

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2Prompt` の完全インタラクティブターミナル UI (TUI) を使いこなす方法をステップバイステップで解説します。

TUI の起動

以下のように --tui フラグを付けてコマンドを実行すると、TUI が起動します。

sh
code2prompt path/to/codebase --tui

1. 選択タブ (ファイルツリー)

  • ナビゲーション: ↑ / ↓ でカーソル移動、← / → でディレクトリ展開/縮小
  • 選択: Space でファイルまたはディレクトリ全体を選択/解除
  • 検索: s または / で検索モードに入り、テキストやワイルドカード (*, ?) で即座にフィルタリング
  • 終了: Enter または Esc で検索モードを抜け、通常のナビゲーションに戻ります

2. 設定タブ

出力形式やトークナイザーなど、生成前に調整したい設定を視覚的に変更できます。

3. 統計タブ

トークン使用量を確認し、LLM に送信する前にコストを把握できます。← / → で 3 つのビューを切り替えます。

4. テンプレートタブ

Handlebars テンプレートを作成・編集できるマルチカラムレイアウトです。キーボードショートカットで 3 つのサブパネルをすばやく切り替えられます。

5. 出力タブ

ファイル選択と設定が完了したら Enter を押して最終出力を生成します。出力タブでは生成されたプロンプトがそのまま表示されます。

  • スクロール: ↑ / ↓, PgUp, PgDn でテキストを確認
  • コピー: c でプロンプト全体をクリップボードにコピー
  • 保存: s でローカルの Markdown ファイルに保存(例: prompt_20260613_204753.md)

不足しているファイルがあれば、1 を押して選択タブに戻り、ファイルをマークして Enter でリアルタイムに再生成できます。


Website Src Content Docs Ru Docs Explanations Glob Pattern Filter (`website/src/content/docs/ru/docs/explanations/glob_pattern_filter.mdx`)


title: Как работает фильтр по паттернам Glob

Code2Prompt использует паттерны glob для включения или исключения файлов и директорий, работая аналогично инструментам типа tree или grep. Он позволяет передавать два независимых списка glob паттернов:

  • список включений (--include или -i) - "эти паттерны разрешают файлы"
  • список исключений (--exclude или -e) - "эти паттерны запрещают файлы"

Code2prompt должен решить для каждого файла в проекте, сохранить его или отбросить. Эта страница объясняет правила и решения дизайна, стоящие за ними.


1. Множества и Символы

На протяжении всего объяснения мы используем обычную нотацию множеств

Символ Значение
$A$ множество файлов, которые соответствуют хотя бы одному паттерну включения
$B$ множество файлов, которые соответствуют хотя бы одному паттерну исключения
$\Omega$ всё дерево проекта (вселенная)
$C = A \cap B$ файлы, которые соответствуют обоим спискам (пересечение)
$D = \Omega \setminus (A \cup B)$ файлы, которые не соответствуют ни одному списку

2. Четыре Ситуации

Обзор четырех ситуаций

Список включений Список исключений Сохранённые файлы
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. Нет списка включений, нет списка исключений

    Если паттерны не указаны, сохраняются все файлы (Ω).

  2. Только список исключений

    В этом случае Code2Prompt действует как чёрный список, удаляя файлы, которые соответствуют исключённым паттернам ( Ω \ B = ¬B).

  3. Только список включений

    Если указан только список включений, Code2Prompt действует как белый список, сохраняя только файлы, которые соответствуют включённым паттернам (A).

  4. Списки включений и исключений

    Если указаны оба списка, Code2Prompt сохраняет файлы, которые соответствуют паттернам включения, но удаляет те, которые соответствуют паттернам исключения (A \ B).


3. Подробнее о пересечении

При наличии обоих списков (A ≠ ∅, B ≠ ∅) у вас есть четыре логические возможности
для пересечения C и остатка D.

Нужно C? Нужно D? Разумно?
Нет Нет Поведение по умолчанию (A \ B)
Да Нет То же поведение, что и случай 3 (A)
Нет Да удивительно ("отбросить то, что я запросил C, сохранить то, что нет")
Да Да То же поведение, что и случай 1 (Ω)

По этой причине была удалена опция --include-priority. Потому что это был бы тот же результат, как если бы у вас был только список включений (случай 3).

4. Таблица быстрого справочника

Хотите сохранить… Используйте
всё нет -i, нет -e
всё кроме некоторых паттернов только -e
только то, что соответствует паттернам только -i
что соответствует -i, минус что соответствует -e -i и -e

Этот дизайн сохраняет ментальную модель простой:

  • Список включений является белым списком, как только он существует.
  • Список исключений является чёрным списком, наложенным сверху.
  • Пересечение отбрасывается по умолчанию

Website Src Content Docs Ru Docs Explanations Glob Patterns (`website/src/content/docs/ru/docs/explanations/glob_patterns.md`)


title: Понимание шаблонов Glob

Шаблоны glob - это простой, но мощный способ сопоставления имен файлов и путей с использованием символов-заменителей. Они обычно используются в интерфейсах командной строки и языках программирования для указания наборов имен файлов или директорий. Вот разбор наиболее часто используемых шаблонов glob:

Базовые шаблоны-заменители

  • *: Сопоставляется с любым количеством символов, включая нулевое количество символов.

    • Пример: *.txt сопоставляется со всеми файлами, оканчивающимися на .txt.
  • ?: Сопоставляется ровно с одним символом.

    • Пример: file?.txt сопоставляется с file1.txt, fileA.txt, но не с file10.txt.
  • []: Сопоставляется с любым из заключенных внутри скобок символов.

    • Пример: file[1-3].txt сопоставляется с file1.txt, file2.txt, file3.txt.
  • [!] или [^]: Сопоставляется с любым символом, не заключенным внутри скобок.

    • Пример: file[!1-3].txt сопоставляется с file4.txt, fileA.txt, но не с file1.txt.

Расширенные шаблоны

  • **: Сопоставляется с любым количеством директорий и поддиректорий рекурсивно.

    • Пример: **/*.txt сопоставляется со всеми файлами .txt в текущей директории и всех поддиректориях.
  • {}: Сопоставляется с любым из шаблонов, перечисленных через запятую внутри скобок.

    • Пример: file{1,2,3}.txt сопоставляется с file1.txt, file2.txt, file3.txt.

Примеры

  1. Сопоставление всех текстовых файлов в директории:

    sh
    *.txt
  2. Сопоставление всех файлов с одним цифровым символом перед расширением:

    sh
    file?.txt
  3. Сопоставление файлов с расширениями .jpg или .png:

    sh
    *.{jpg,png}
  4. Сопоставление всех файлов .txt в любой поддиректории:

    sh
    **/*.txt
  5. Сопоставление файлов, начинающихся с a или b и оканчивающихся на .txt:

    sh
    {a,b}*.txt

Варианты использования

  • Инструменты командной строки: Шаблоны glob широко используются в инструментах командной строки, таких как ls, cp, mv и rm, для указания нескольких файлов или директорий.
  • Языки программирования: Языки, такие как Python, JavaScript и Ruby, поддерживают шаблоны glob для сопоставления файлов через библиотеки, такие как glob в Python.
  • Системы сборки: Инструменты, такие как Makefile, используют шаблоны glob для указания исходных файлов и зависимостей.

Заключение

Шаблоны glob обеспечивают гибкий и интуитивный способ сопоставления имен файлов и путей, что делает их незаменимыми для задач сценариев, автоматизации и управления файлами. Понимание и использование этих шаблонов может существенно повысить вашу производительность и эффективность при работе с файлами и директориями.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Explanations Tokenizers (`website/src/content/docs/ru/docs/explanations/tokenizers.md`)


title: Токенизация в Code2Prompt

При работе с языковыми моделями текст необходимо преобразовать в формат, который модель может понять — токены, являющиеся последовательностями чисел. Это преобразование выполняется токенизатором.


Указанное число токенов — оценка: Code2Prompt параллельно считает токены файлов
после обработки и добавления номеров строк, если они включены, затем прибавляет
оценку затрат шаблона. Полный промпт повторно не токенизируется. Границы фрагментов
и преобразования шаблона могут изменить результат; оценка не гарантирует верхнюю
границу. Числовое поле token_count сохраняет имя и не учитывает оболочку JSON
и экранирование при сериализации.

Что такое токенизатор?

Токенизатор преобразует сырой текст в токены, которые являются строительными блоками для обработки входных данных языковыми моделями. Эти токены могут представлять слова, под слова или даже отдельные символы, в зависимости от конструкции токенизатора.

Для code2prompt мы используем tiktoken токенизатор. Он эффективен, надежен и оптимизирован для моделей OpenAI.
Вы можете изучить его функциональность в официальном репозитории

👉 репозиторий tiktoken на GitHub

Если вы хотите узнать больше о токенизаторе в целом, ознакомьтесь с

👉 Руководством по токенизации Mistral.

Реализация в `code2prompt`

Токенизация реализована с помощью tiktoken-rs. tiktoken поддерживает следующие кодировки, используемые моделями OpenAI:

Аргумент CLI Имя кодировки Модели OpenAI
cl100k cl100k_base Модели ChatGPT, text-embedding-ada-002
p50k p50k_base Модели кода, text-davinci-002, text-davinci-003
p50k_edit p50k_edit Используется для моделей редактирования, таких как text-davinci-edit-001, code-davinci-edit-001
r50k r50k_base (или gpt2) Модели GPT-3, такие как davinci
gpt2 o200k_base Модели GPT-4o

Для более глубокого понимания различных токенизаторов см. OpenAI Cookbook

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs How To Cli (`website/src/content/docs/ru/docs/how_to/cli.mdx`)


title: Основное использование Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

Добро пожаловать в руководство по использованию `Code2Prompt`.

Использование

Генерация промпта из кодовой базы:

sh
code2prompt путь/к/кодовой/базе

Генерация промпта и копирование в буфер обмена:

sh
code2prompt путь/к/кодовой/базе -c

Запуск интерактивного TUI:

sh
code2prompt путь/к/кодовой/базе --tui

Отображение карты токенов:

sh
code2prompt путь/к/кодовой/базе --token-map

Использование пользовательского шаблона Handlebars:

sh
code2prompt путь/к/кодовой/базе -t путь/к/шаблону.hbs

Фильтрация файлов с помощью glob‑шаблонов:

sh
code2prompt путь/к/кодовой/базе --include="*.rs,*.toml"

Исключение файлов с помощью glob‑шаблонов:

sh
code2prompt путь/к/кодовой/базе --exclude="*.txt,*.md"

Исключение файлов/папок из дерева исходного кода по шаблонам исключения:

sh
code2prompt путь/к/кодовой/базе --exclude="*.npy,*.wav"

Отображение количества токенов сгенерированного промпта:

sh
code2prompt путь/к/кодовой/базе --token-format=format

Указание токенизатора для подсчёта токенов:

sh
code2prompt путь/к/кодовой/базе --encoding=p50k

Поддерживаемые токенизаторы: cl100k, p50k, p50k_edit, r50k_bas.

Сохранение сгенерированного промпта в файл:

sh
code2prompt путь/к/кодовой/базе -O output.txt

Вывод в формате JSON:

sh
code2prompt путь/к/кодовой/базе -F JSON

Пример JSON‑вывода:

json
{
  "prompt": "<Сгенерированный промпт>",
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT модели, text-embedding-ada-002",
  "files": []
}

Генерация сообщения коммита Git (для проиндексированных файлов):

sh
code2prompt путь/к/кодовой/базе --diff -t templates/write-git-commit.hbs

Генерация Pull Request с сравнением веток (для проиндексированных файлов):

sh
code2prompt путь/к/кодовой/базе --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Добавление номеров строк к блокам кода:

sh
code2prompt путь/к/кодовой/базе --line-numbers

Отключение обёртки кода в markdown‑блоках:

sh
code2prompt путь/к/кодовой/базе --no-codeblock

Code2Prompt — отличный инструмент для эффективного создания токен‑оптимизированных промптов. Он полезен в различных сценариях, таких как:

  • Переписывание кода на другой язык
  • Поиск багов/уязвимостей
  • Документирование кода
  • Реализация новых функций

Website Src Content Docs Ru Docs How To Config (`website/src/content/docs/ru/docs/how_to/config.mdx`)


title: Создание файла `.c2pconfig`

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

В этом руководстве вы узнаете, как создать и использовать файл `.c2pconfig` для автоматизации вашего рабочего процесса генерации промптов.

Ручное написание длинных шаблонов исключения, настроек токенизатора или пользовательских переменных каждый раз при запуске Code2Prompt может быть утомительным. Создав файл конфигурации .c2pconfig, вы сможете «настроить и забыть» предпочтения вашего проекта. Code2Prompt автоматически ищет этот файл в текущем рабочем каталоге и применяет правила без усилий.

Ниже представлены шаги по созданию вашего первого конфигурационного файла.


Инициализация конфигурационного файла

Перейдите в корневой каталог вашего проекта в терминале и создайте файл с именем .c2pconfig.

bash
cd путь/к/вашему/проекту
touch .c2pconfig

Шаг 2: Определение базового поведения (формат TOML)

Откройте файл .c2pconfig в любимом редакторе. Файл использует синтаксис TOML. Вставьте следующую базовую конфигурацию:

toml
# Настройки поведения по умолчанию
default_output = "clipboard"    # варианты: stdout, clipboard, file
output_format = "xml"           # варианты: markdown, json, xml
line_numbers = false            # Добавлять номера строк к блокам кода
encoding = "o200k"              # Соответствует токенизатору вашей целевой LLM

# Глобальные правила фильтрации
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**",
    "**/target/**",
    "tests/fixtures/**",
    "package-lock.json"
]

Шаг 3: Запуск без аргументов

После сохранения файла .c2pconfig в корне вашей кодовой базы, вам больше не нужно передавать сложные флаги. Просто выполните команду:

bash
code2prompt .

Code2Prompt автоматически прочитает ваш .c2pconfig, отфильтрует файлы согласно вашим glob‑шаблонам, добавит номера строк и отформатирует вывод согласно выбранным настройкам.


Следующие шаги

Для более продвинутых рабочих процессов, переменных и ключей конфигурации по умолчанию ознакомьтесь с учебником:


Website Src Content Docs Ru Docs How To Filter Files (`website/src/content/docs/ru/docs/how_to/filter_files.md`)


title: Фильтрация файлов в Code2Prompt

Использование

Сгенерировать запрос из директории codebase:

sh
code2prompt path/to/codebase

Использовать пользовательский файл шаблона Handlebars:

sh
code2prompt path/to/codebase -t path/to/template.hbs

Фильтровать файлы с помощью шаблонов glob:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

Исключить файлы с помощью шаблонов glob:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

Исключить файлы/папки из дерева исходных файлов на основе шаблонов исключения:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

Отобразить количество токенов сгенерированного запроса:

sh
code2prompt path/to/codebase --token-format=format

Указать токенизатор для подсчета токенов:

sh
code2prompt path/to/codebase --encoding=p50k

Поддерживаемые токенизаторы: cl100k, p50k, p50k_edit, r50k_bas.

[!ПРИМЕЧАНИЕ]
См. Токенизаторы для более подробной информации.

Сохранить сгенерированный запрос в выходной файл:

sh
code2prompt path/to/codebase --output=output.txt

Вывести результат в формате JSON:

sh
code2prompt path/to/codebase --json

Выходные данные в формате JSON будут иметь следующую структуру:

json
{
  "prompt": "<Сгенерированный запрос>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "Модели ChatGPT, text-embedding-ada-002",
  "files": []
}

Сгенерировать сообщение коммита Git (для staged файлов):

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

Сгенерировать запрос на Pull Request с сравнением веток (для staged файлов):

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

Добавить номера строк к блокам исходного кода:

sh
code2prompt path/to/codebase --line-numbers

Отключить оборачивание кода внутри блоков markdown:

sh
code2prompt path/to/codebase --no-codeblock
  • Переписать код на другой язык.
  • Найти ошибки/уязвимости безопасности.
  • Документировать код.
  • Реализовать новые функции.

Изначально я написал это для личного использования, чтобы использовать окно контекста Claude 3.0 размером 200K, и оно оказалось довольно полезным, поэтому я решил сделать его открытым!

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs How To Install (`website/src/content/docs/ru/docs/how_to/install.mdx`)


title: Установка Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

Добро пожаловать в руководство по установке `Code2Prompt`. Этот документ содержит пошаговые инструкции по установке на различных платформах, включая Windows, macOS и Linux.

Краткий обзор

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

Предварительные требования

Убедитесь, что Rust и cargo установлены на вашей системе.

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Это официальный способ установки последней стабильной версии Rust и Cargo. Обязательно обновите переменную PATH после установки Rust. Перезапустите терминал или выполните предложенные установщиком инструкции.

sh
source $HOME/.cargo/env

Вы можете проверить, что всё установлено правильно, выполнив:

sh
cargo --version
git --version

Интерфейс командной строки (CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 Установка последней (неопубликованной) версии с GitHub

Если вы хотите получить последние функции или исправления до их выпуска на crates.io:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

Сборка из исходного кода

Идеально для разработчиков, которые хотят собрать из исходного кода или внести свой вклад в проект.

  1. 🛠️ Установка предварительных требований :

  2. 📥 Клонирование репозитория :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 Установка бинарного файла :

    Чтобы собрать и установить из исходного кода:

    sh
    cargo install --path crates/code2prompt

    Чтобы собрать бинарный файл без установки:

    sh
    cargo build --release

    Бинарный файл будет доступен в каталоге target/release.

  4. 🚀 Запуск :

    sh
    code2prompt --help

Бинарные релизы

Лучше всего для пользователей, которые хотят использовать последнюю версию без сборки из исходного кода.

Загрузите последний бинарный файл для вашей ОС из Релизов.

⚠️ Бинарные релизы могут отставать от последней версии на GitHub. Для получения новейших функций рассмотрите сборку из исходного кода.

AUR

Специально для пользователей Arch Linux, code2prompt доступен в AUR.

code2prompt доступен в AUR. Установите его с помощью любого AUR-клиента.

sh
paru/yay -S code2prompt

Nix

Если вы используете Nix, вы можете установить его с помощью nix-env или nix profile.

sh
# без flakes:
nix-env -iA nixpkgs.code2prompt
# с flakes:
nix profile install nixpkgs#code2prompt

Программный 개발 Kit (SDK) 🐍

Pypi

Вы можете загрузить привязки Python из Pypi

sh
pip install code2prompt_rs

Сборка из исходного кода

  1. 🛠️ Установка предварительных требований :

  2. 📥 Клонирование репозитория :

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 Установка зависимостей :

    uv создаёт .venv, фиксирует зависимости для разработки и собирает нативное расширение в редактируемом режиме.

    sh
    uv sync
  4. 🧪 Запустить тесты :

    Запустите команду тестирования проекта в синхронизированной среде.

    sh
    uv run pytest

Протокол контекста модели (MCP) 🤖

Автоматическая установка

Сервер code2prompt MCP скоро будет доступен в реестрах MCP.

Ручная установка

Сервер code2prompt MCP всё ещё является прототипом и будет интегрирован в основной репозиторий вскоре.

Чтобы запустить сервер MCP локально для использования с Cline, Goose или Aider:

  1. 🛠️ Установка предварительных требований :

  2. 📥 Клонирование репозитория :

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 Установка зависимостей :

    Команда rye создаст виртуальную среду и установит все зависимости в папке .venv.

    sh
    rye sync
  4. 🚀 Запуск сервера :

    Сервер MCP теперь установлен. Вы можете запустить его с помощью:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 Интеграция с агентами :

    text
    Например, вы можете интегрировать его с `Cline`, используя аналогичную конфигурацию:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs How To Ssh (`website/src/content/docs/ru/docs/how_to/ssh.md`)


title: Использование Code2prompt CLI с SSH

Почему это не работает?

Когда вы пытаетесь запустить code2prompt CLI на удаленном сервере через SSH, команда не может найти буфер обмена. Это связано с тем, что code2prompt CLI использует буфер обмена для копирования сгенерированного запроса, а сеансы SSH обычно не имеют доступа к локальному буферу обмена.

Решение

Чтобы использовать code2prompt CLI с SSH, вы можете перенаправить вывод в файл вместо копирования в буфер обмена. Таким образом, вы можете по-прежнему генерировать запрос и сохранять его для последующего использования.

Используйте опцию --output-file, чтобы указать файл вывода, где будет сохранен сгенерированный запрос. Например:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs How To Tui (`website/src/content/docs/ru/docs/how_to/tui.mdx`)


title: Использование терминального пользовательского интерфейса (TUI) Code2Prompt

import { Card } from "@astrojs/starlight/components";

`Code2Prompt` предоставляет полностью интерактивный терминальный пользовательский интерфейс (TUI). Это руководство покажет, как запустить TUI и освоить её пять основных вкладок.

Запуск TUI

Чтобы открыть интерактивный интерфейс, просто добавьте флаг --tui к вашей команде вместе с путём к проекту:

sh
code2prompt путь/к/вашему/codebase --tui

1. Вкладка **Выбор** (дерево файлов)

Эта вкладка позволяет собрать точный контекст, который будет отправлен LLM. Она отображает иерархическое представление вашего проекта, учитывая правила .gitignore и .c2pconfig.

  • Навигация: ↑ / ↓ перемещают курсор, ← / → раскрывают/сворачивают каталоги.
  • Выбор: Space выбирает/снимает выбор файла или целой директории.
  • Поиск: s или / переводит в режим поиска; вводите текст или шаблоны (*, ?) для мгновенной фильтрации.
  • Выход: Enter или Esc закрывает режим поиска и возвращает к обычной навигации.

2. Вкладка **Настройки**

Здесь вы можете визуально изменить параметры вывода перед генерацией, используя чекбоксы и выпадающие списки.

3. Вкладка **Статистика**

Перед тем как отправлять большой промпт в LLM, проверьте ваш токен‑бюджет в этой вкладке.

← / → переключает между тремя мощными представлениями:

4. Вкладка **Шаблон**

Здесь происходит магия. Вы получаете многострочный адаптивный макет, помогающий создавать идеальный Handlebars‑шаблон.

При нахождении в этой вкладке используйте клавиатурные комбинации для мгновенного переключения между тремя подпанелями:

5. Вкладка **Вывод**

После выбора файлов, настройки и шаблона нажмите Enter, чтобы сгенерировать окончательный вывод.

  • Прокрутка: ↑ / ↓, PgUp или PgDn для просмотра сгенерированного текста.
  • Копировать: c копирует весь промпт в системный буфер обмена.
  • Сохранить: s сохраняет промпт в локальный Markdown‑файл (например, prompt_20260613_204753.md).

Если вы забыли добавить файл, нажмите 1, вернитесь к вкладке Выбор, отметьте файл и нажмите Enter для мгновенного пересчёта.


Website Src Content Docs Ru Docs References Command Line Options (`website/src/content/docs/ru/docs/references/command_line_options.md`)


title: Параметры командной строки Code2Prompt

Параметры командной строки

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs References Default Template (`website/src/content/docs/ru/docs/references/default_template.md`)


title: Шаблон по умолчанию для Code2Prompt

Шаблон по умолчанию

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Tutorials Configuration (`website/src/content/docs/ru/docs/tutorials/configuration.mdx`)


title: Конфигурация Code2Prompt 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

Ручное написание длинных шаблонов исключения или специфических настроек токенизатора каждый раз может быть утомительным. Этот учебник покажет, как использовать файл конфигурации `.c2pconfig` для «настройки и забывания» настроек проекта.

Предварительные требования

Убедитесь, что code2prompt установлен. Если нет, см. руководство по установке. Знание синтаксиса TOML полезно, но не обязательно.

Что такое `.c2pconfig`?

.c2pconfig — это файл конфигурации в формате TOML. При запуске code2prompt он автоматически ищет этот файл в текущем рабочем каталоге и применяет настройки.

Вы можете определить:

  • Правила фильтрации: Постоянные include/exclude шаблоны.
  • Форматы вывода: По умолчанию JSON, Markdown или XML.
  • Контекст шаблона: Предопределённые переменные для ваших Handlebars‑шаблонов.

Быстрый старт

Создайте файл .c2pconfig в корне проекта и задайте базовое поведение.

toml
# Базовые настройки
default_output = "stdout"   # варианты: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MyAwesomeProject"
author = "Developer"

Справочник конфигурации

Ключ Тип Описание
path String Путь к кодовой базе (обычно .)
include_patterns Array Glob‑шаблоны файлов для включения
exclude_patterns Array Glob‑шаблоны файлов для исключения
line_numbers Boolean Добавлять номера строк к блокам кода
absolute_path Boolean Использовать абсолютные пути
full_directory_tree Boolean Генерировать полный дерево даже для исключённых файлов
output_format String markdown, json, xml
sort_method String name_asc, name_desc, date_asc, date_desc
encoding String Токенизатор: cl100k, p50k, o200k
diff_enabled Boolean Включать Git‑diff (HEAD vs Index)
token_map_enabled Boolean Показать карту использования токенов

Пошаговое внедрение

1. **Создание конфигурации** ```bash touch .c2pconfig ```
  1. Определение глобальных фильтров
    Исключите тяжёлые каталоги (node_modules, target/) для чистого контекста LLM.

    toml
    exclude_patterns = [
      "**/node_modules/**",
      "package-lock.json",
      "dist/**"
    ]
  2. Выбор токенизатора
    Подберите токенизатор под целевую LLM. Для GPT‑4o используйте o200k, для Claude и GPT‑4 — cl100k.

    toml
    encoding = "o200k"
  3. Добавление пользовательских переменных
    В разделе [user_variables] задайте переменные, которые будут доступны в ваших Handlebars‑шаблонах.

    toml
    [user_variables]
    project_goal = "Рефакторинг модуля аутентификации для повышения безопасности."
  4. Запуск без дополнительных флагов
    После сохранения .c2pconfig просто выполните:

    bash
    code2prompt .

Понимание приоритетов

CLI‑аргументы > .c2pconfig > настройки по умолчанию. Это позволяет иметь базовую конфигурацию и при необходимости переопределять её в командной строке.

Пример «готовый к ревью»

Эта конфигурация оптимизирована для генерации промптов, пригодных для обзора кода.

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

Следующие шаги


Website Src Content Docs Ru Docs Tutorials Getting Started (`website/src/content/docs/ru/docs/tutorials/getting_started.mdx`)


title: Getting Started with Code2Prompt

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

Добро пожаловать в Code2Prompt! Этот учебник предоставляет всестороннее введение в использование Code2Prompt для генерации готовых к использованию ИИ подсказок из вашего кода. Мы рассмотрим его основные функции и продемонстрируем его использование в различных методах интеграции: интерфейс командной строки (CLI), набор средств разработки (SDK) и протокол контекста модели (MCP).

Что такое Code2Prompt?

Code2Prompt - это универсальный инструмент, предназначенный для устранения разрыва между вашим кодом и большими языковыми моделями (LLM).
Он интеллектуально извлекает соответствующие фрагменты кода, применяет мощную фильтрацию и форматирует информацию в структурированные подсказки, оптимизированные для потребления LLM.
Это упрощает задачи, такие как документирование кода, обнаружение ошибок, рефакторинг и многое другое.

Code2Prompt предлагает различные точки интеграции:

Основная библиотека Rust, обеспечивающая основу для потребления кода и подсказок. Дружественный интерфейс командной строки для быстрой генерации подсказок. Идеален для интерактивного использования и одноразовых задач. Мощный набор средств разработки (SDK) для бесшовной интеграции в ваши проекты на Python. Идеален для автоматизации генерации подсказок в рамках более крупных рабочих процессов. Сервер протокола контекста модели (MCP) для расширенной интеграции с агентами LLM. Позволяет осуществлять сложные,实时 взаимодействия с вашим кодом.

📥 Установка

Для получения подробных инструкций по установке всех методов (CLI, SDK, MCP) обратитесь к всестороннему Руководству по установке.

🏁 Генерация подсказок: пример CLI

Давайте начнем с простого примера использования CLI.
Создайте образец проекта:

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

Теперь сгенерируйте подсказку:

bash
code2prompt my_project

Это копирует подсказку в ваш буфер обмена.
Вы можете настроить это:

  • Фильтрация: code2prompt my_project --include="*.rs" --exclude="tests/*" (включает только файлы .rs, исключает каталог tests)
  • Файл вывода: code2prompt my_project --output-file=my_prompt.txt
  • JSON-вывод: code2prompt my_project -O json (структурированный JSON-вывод)
  • Пользовательские шаблоны: code2prompt my_project -t my_template.hbs (требуется создание my_template.hbs)

См. учебники Learn Context Filtering и Learn Handlebar Templates, чтобы узнать о более продвинутом использовании.

🐍 Интеграция SDK (Python)

Для программного управления используйте Python SDK:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

Это требует установки SDK (pip install code2prompt_rs).
Обратитесь к документации SDK для более подробной информации.

🤖 Интеграция с сервером MCP (расширенная)

Для расширенной интеграции с агентами LLM запустите сервер code2prompt MCP (см. руководство по установке для подробностей).
Это позволяет агентам запрашивать контекст кода динамически.
Это расширенная функция, и дополнительная документация доступна на сайте проекта.

Изучите расширенные учебники и документацию, чтобы освоить возможности Code2Prompt и интегрировать его в ваши рабочие процессы.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Tutorials Learn Filters (`website/src/content/docs/ru/docs/tutorials/learn_filters.mdx`)


title: Learn Context Filtering with Code2Prompt

import { Card } from "@astrojs/starlight/components";

В этом руководстве демонстрируется, как использовать инструмент **glob pattern** в интерфейсе командной строки `code2prompt`, чтобы фильтровать и управлять файлами на основе шаблонов включения и исключения.

Шаблоны glob работают аналогично инструментам, таким как tree или grep, обеспечивая мощные возможности фильтрации. Ознакомьтесь с подробным объяснением для получения дополнительной информации.


Требования

Убедитесь, что у вас установлен code2prompt. Если вы еще не установили его, обратитесь к Руководству по установке.


Понимание шаблонов включения и исключения

Шаблоны glob позволяют указать правила для фильтрации файлов и директорий.

  • Шаблоны включения (--include): Укажите файлы и директории, которые вы хотите включить.
  • Шаблоны исключения (--exclude): Укажите файлы и директории, которые вы хотите исключить.
  • Приоритет (--include-priority): Разрешает конфликты между шаблонами включения и исключения.

Настройка окружения

Чтобы практиковаться с шаблонами glob, давайте создадим тестовую структуру папок с некоторыми файлами.

Сценарий Bash для создания тестовой структуры

Запустите этот сценарий, чтобы создать временную структуру директорий:

bash
#!/bin/bash

# Create base directory
mkdir -p test_dir/{lowercase,uppercase,.secret}

# Create files in the structure
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

Чтобы очистить структуру позже, запустите:

bash
rm -rf test_dir

Он создаст следующую структуру директорий:

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.PY - BAR.PY - BAZ.PY - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

Примеры: Фильтрация файлов с помощью шаблонов включения и исключения

Случай 1: Нет включения, нет исключения

Команда:

bash
code2prompt test_dir

Результат

Все файлы включены:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

Случай 2: Исключение определенных типов файлов

Исключить .txt файлы:

bash
code2prompt test_dir --exclude="*.txt"

Результат

Исключены:

  • Все .txt файлы

Включены:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

Случай 3: Включение определенных типов файлов

Включить только Python файлы:

bash
code2prompt test_dir --include="*.py"

Результат

Включены:

  • Все .py файлы

Исключены:

  • .secret/secret.txt

Случай 4: Включение и исключение с приоритетом

Включить .py файлы, но исключить файлы в папке uppercase:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

Результат

Включены:

  • Все lowercase/1 файлы с расширением .py

Исключены:

  • Все uppercase файлы
  • .secret/secret.txt

Резюме

Инструмент glob pattern в code2prompt позволяет эффективно фильтровать файлы и директории с помощью:

  • --include для указания файлов для включения
  • --exclude для указания файлов для исключения
  • --include-priority для разрешения конфликтов между шаблонами

Чтобы практиковаться, настройте тестовую директорию, попробуйте команды и посмотрите, как инструмент динамически фильтрует файлы.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Tutorials Learn Templates (`website/src/content/docs/ru/docs/tutorials/learn_templates.mdx`)


title: Изучите шаблоны Handlebar с Code2Prompt

import { Card } from "@astrojs/starlight/components";

Этот урок демонстрирует, как использовать и создавать пользовательские шаблоны Handlebars для генерации подсказок в CLI `code2prompt`.

Предварительные требования

Убедитесь, что у вас установлен code2prompt. Если вы еще не установили его, обратитесь к Руководству по установке.


Что такое шаблоны Handlebars?

Handlebars — это популярный механизм шаблонов, который позволяет создавать динамические шаблоны с помощью заполнителей.
В code2prompt шаблоны Handlebars используются для форматирования сгенерированных подсказок на основе структуры codebase и переменных, определенных пользователем.

Как использовать шаблоны Handlebars?

Вы можете использовать эти шаблоны, передав флаг -t или --template, за которым следует путь к файлу шаблона. Например:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

Синтаксис шаблонов

Шаблоны Handlebars используют простой синтаксис для заполнителей и выражений. Вы будете помещать переменные в двойные фигурные скобки {{variable_name}}, чтобы включить их в сгенерированную подсказку.
Code2prompt предоставляет набор переменных по умолчанию, которые вы можете использовать в своих шаблонах:

  • absolute_code_path: Абсолютный путь к codebase.
  • source_tree: Дерево исходного кода codebase, которое включает все файлы и директории.
  • files: Список файлов в codebase, включая их пути и содержимое.
  • git_diff: Разница git codebase, если применимо.
  • code: Содержимое кода файла, который обрабатывается.
  • path: Путь файла, который обрабатывается.

Вы также можете использовать помощники Handlebars для выполнения условной логики, циклов и других операций в ваших шаблонах. Например:

handlebars
{{#if files}}
  {{#each files}}
    Файл:
    {{this.path}}
    Содержимое:
    {{this.content}}
  {{/each}}
{{else}}
  Файлы не найдены.
{{/if}}

Существующие шаблоны

code2prompt поставляется с набором встроенных шаблонов для общих случаев использования. Вы можете найти их в директории templates.

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

Используйте этот шаблон для генерации подсказок для документирования кода. Он добавит комментарии документации ко всем публичным функциям, методам, классам и модулям в codebase.

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

Используйте этот шаблон для генерации подсказок для поиска потенциальных уязвимостей безопасности в codebase. Он будет искать общие проблемы безопасности и предоставлять рекомендации по их устранению или смягчению.

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

Используйте этот шаблон для генерации подсказок для очистки и улучшения качества кода. Он будет искать возможности для улучшения читаемости, соблюдения лучших практик, эффективности, обработки ошибок и многого другого.

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

Используйте этот шаблон для генерации подсказок для исправления ошибок в codebase. Он поможет диагностировать проблемы, предоставить предложения по исправлению и обновить код с предложенными исправлениями.

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

Используйте этот шаблон для создания описания pull request GitHub в формате markdown, сравнивая разницу git и журнал git двух веток.

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

Используйте этот шаблон для генерации высококачественного файла README для проекта, подходящего для размещения на GitHub. Он проанализирует codebase, чтобы понять его цель и функциональность, и сгенерирует содержимое README в формате Markdown.

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

Используйте этот шаблон для генерации коммитов git из staged файлов в директории git. Он проанализирует codebase, чтобы понять его цель и функциональность, и сгенерирует содержимое сообщения коммита git в формате Markdown.

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

Используйте этот шаблон для генерации подсказок для улучшения производительности codebase. Он будет искать возможности для оптимизации, предоставлять конкретные предложения и обновлять код с изменениями.

Переменные, определенные пользователем

code2prompt поддерживает использование переменных, определенных пользователем, в шаблонах Handlebars. Любые переменные в шаблоне, которые не являются частью контекста по умолчанию (absolute_code_path, source_tree, files), будут рассматриваться как переменные, определенные пользователем.

Во время генерации подсказок code2prompt предложит пользователю ввести значения для этих переменных, определенных пользователем. Это позволяет для дальнейшей настройки сгенерированных подсказок на основе пользовательского ввода.

Например, если ваш шаблон включает {{challenge_name}} и {{challenge_description}}, вам будет предложено ввести значения для этих переменных при запуске code2prompt.

Эта функция позволяет создавать многоразовые шаблоны, которые могут быть адаптированы к разным сценариям на основе информации, предоставленной пользователем.

Эта страница была автоматически переведена для вашего удобства. Обратитесь к английской версии для получения оригинального содержания.


Website Src Content Docs Ru Docs Tutorials Tui (`website/src/content/docs/ru/docs/tutorials/tui.mdx`)


title: Использование терминального UI (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2Prompt` предоставляет полностью интерактивный терминальный UI (TUI). Этот учебник пошагово покажет, как запустить TUI и управлять её пятью основными вкладками.

Запуск TUI

Для открытия интерактивного интерфейса добавьте флаг --tui к команде вместе с путём к проекту:

sh
code2prompt путь/к/вашему/codebase --tui

1. Вкладка **Выбор** (дерево файлов)

  • Навигация: ↑ / ↓ перемещают курсор, ← / → раскрывают/сворачивают каталоги.
  • Выбор: Space выбирает/снимает выбор файла или целой директории.
  • Поиск: s или / переводит в режим поиска; вводите текст или шаблоны (*, ?) для мгновенной фильтрации.
  • Выход: Enter или Esc закрывает режим поиска и возвращает к обычной навигации.

2. Вкладка **Настройки**

Здесь можно визуально изменить параметры вывода перед генерацией, используя чекбоксы и выпадающие списки.

3. Вкладка **Статистика**

Перед отправкой большого промпта в LLM проверьте ваш токен‑бюджет.

← / → переключает между тремя представлениями.

4. Вкладка **Шаблон**

Здесь происходит магия. Вы получаете адаптивный многоколоночный макет для создания идеального Handlebars‑шаблона.

В режиме Шаблон используйте клавиатурные комбинации для быстрого переключения между тремя подпанелями.

5. Вкладка **Вывод**

После выбора файлов, настройки и шаблона нажмите Enter для генерации окончательного вывода.

  • Прокрутка: ↑ / ↓, PgUp, PgDn для просмотра сгенерированного текста.
  • Копировать: c копирует весь промпт в системный буфер обмена.
  • Сохранить: s сохраняет промпт в локальный Markdown‑файл (например, prompt_20260613_204753.md).

Если вы забыли добавить файл, нажмите 1, вернитесь к вкладке Выбор, отметьте файл и нажмите Enter для мгновенного пересчёта.


Website Src Content Docs Zh Docs Explanations Glob Pattern Filter (`website/src/content/docs/zh/docs/explanations/glob_pattern_filter.mdx`)


title: Glob模式过滤器的工作原理

Code2Prompt 使用 glob 模式来包含或排除文件和目录,工作方式类似于 tree 或 grep 等工具。它允许您传递两个独立的 glob 模式列表:

  • 包含列表 (--include 或 -i) - "这些模式允许文件"
  • 排除列表 (--exclude 或 -e) - "这些模式禁止文件"

Code2prompt 必须为项目中的每个文件决定是保留还是丢弃。本页面解释了规则以及背后的设计选择。


1. 集合和符号

在整个解释过程中,我们使用通常的集合符号

符号 含义
$A$ 匹配至少一个包含模式的文件集合
$B$ 匹配至少一个排除模式的文件集合
$\Omega$ 整个项目树(全集)
$C = A \cap B$ 匹配两个列表的文件(重叠)
$D = \Omega \setminus (A \cup B)$ 不匹配任何列表的文件

2. 四种情况

四种情况概览

包含列表 排除列表 保留的文件
A = ∅ B = ∅ Ω
A = ∅ B ≠ ∅ ¬B
A ≠ ∅ B = ∅ A
A ≠ ∅ B ≠ ∅ A \ B
  1. 没有包含列表,没有排除列表

    如果没有指定模式,则保留所有文件 (Ω)。

  2. 仅排除列表

    在这种情况下,Code2Prompt 充当黑名单,删除匹配排除模式的文件 ( Ω \ B = ¬B)。

  3. 仅包含列表

    如果仅指定包含列表,Code2Prompt 充当白名单,仅保留匹配包含模式的文件 (A)。

  4. 包含和排除列表

    如果同时指定了两个列表,Code2Prompt 保留匹配包含模式的文件,但删除匹配排除模式的文件 (A \ B)。


3. 关于重叠的更多信息

当两个列表都存在时 (A ≠ ∅, B ≠ ∅),对于重叠 C 和其余部分 D,
您有四种逻辑可能性。

需要 C? 需要 D? 合理吗?
否 否 默认行为 (A \ B)
是 否 与情况 3 相同的行为 (A)
否 是 令人惊讶("丢弃我请求的 C,保留我没有请求的")
是 是 与情况 1 相同的行为 (Ω)

正是由于这个原因,--include-priority 选项被删除了。因为这将与只有包含列表(情况 3)的结果相同。

4. 快速参考表

想要保留… 使用
一切 无 -i,无 -e
除某些模式之外的一切 仅 -e
仅匹配模式的内容 仅 -i
匹配 -i 的内容,减去匹配 -e 的内容 -i 和 -e

这种设计保持了心理模型的简单性:

  • 包含列表一旦存在就是白名单。
  • 排除列表是叠加在上面的黑名单。
  • 重叠部分默认被丢弃

Website Src Content Docs Zh Docs Explanations Glob Patterns (`website/src/content/docs/zh/docs/explanations/glob_patterns.md`)


title: Understanding Glob Patterns

Glob 模式是一种简单而强大的方法,用于使用通配符匹配文件名和路径。它们在命令行界面和编程语言中被广泛使用,以指定文件名或目录的集合。以下是一些最常用的 Glob 模式的详细介绍:

基本通配符

  • *:匹配任意数量的字符,包括零个字符。

    • 示例:*.txt 匹配所有以 .txt 结尾的文件。
  • ?:匹配恰好一个字符。

    • 示例:file?.txt 匹配 file1.txt、fileA.txt,但不匹配 file10.txt。
  • []:匹配任意一个括弧内的字符。

    • 示例:file[1-3].txt 匹配 file1.txt、file2.txt、file3.txt。
  • [!] 或 [^]:匹配任意一个不在括弧内的字符。

    • 示例:file[!1-3].txt 匹配 file4.txt、fileA.txt,但不匹配 file1.txt。

高级模式

  • **:递归匹配任意数量的目录和子目录。

    • 示例:**/*.txt 匹配当前目录和所有子目录中的所有 .txt 文件。
  • {}:匹配任意一个用逗号分隔的模式。

    • 示例:file{1,2,3}.txt 匹配 file1.txt、file2.txt、file3.txt。

示例

  1. 匹配目录中的所有文本文件:

    sh
    *.txt
  2. 匹配扩展名前面有一个数字的所有文件:

    sh
    file?.txt
  3. 匹配扩展名为 .jpg 或 .png 的文件:

    sh
    *.{jpg,png}
  4. 匹配任何子目录中的所有 .txt 文件:

    sh
    **/*.txt
  5. 匹配以 a 或 b 开头并以 .txt 结尾的文件:

    sh
    {a,b}*.txt

用例

  • 命令行工具: Glob 模式在 ls、cp、mv 和 rm 等命令行工具中被广泛使用,以指定多个文件或目录。
  • 编程语言: Python、JavaScript 和 Ruby 等语言通过 Python 中的 glob 库等支持文件匹配的 Glob 模式。
  • 构建系统: Makefile 等工具使用 Glob 模式指定源文件和依赖项。

结论

Glob 模式提供了一种灵活直观的方法来匹配文件名和路径,使其对于脚本编写、自动化和文件管理任务来说非常宝贵。理解和利用这些模式可以显著提高您处理文件和目录的效率和生产力。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Explanations Tokenizers (`website/src/content/docs/zh/docs/explanations/tokenizers.md`)


title: Code2Prompt 中的分词

在处理语言模型时,文本需要转换为模型可以理解的格式——tokens,即数字序列。这种转换由 tokenizer 处理。


报告的 token 数是估算值:Code2Prompt 在处理文件并按需添加行号后,
并行统计各文件的 token 数,再加上模板的估算开销。最终提示词不会被整体重新分词。
片段边界和模板转换可能使实际数量不同,因此估算值并不是保证的上限。
数值字段 token_count 保留原名,不包含 JSON 外层结构和序列化时的转义开销。

什么是 Tokenizer?

Tokenizer 将原始文本转换为 tokens,这些是语言模型处理输入的基本单位。这些 tokens 可以根据 tokenizer 的设计表示单词、子单词甚至单个字符。

对于 code2prompt,我们使用 tiktoken tokenizer。它高效、稳健,并针对 OpenAI 模型进行了优化。
您可以在官方仓库中探索其功能

👉 tiktoken GitHub 仓库

如果您想了解更多关于 tokenizer 的信息,请查看

👉 Mistral 分词指南.

在 `code2prompt` 中的实现

分词使用 tiktoken-rs 实现。tiktoken 支持 OpenAI 模型使用的以下编码:

命令行参数 编码名称 OpenAI 模型
cl100k cl100k_base ChatGPT 模型,text-embedding-ada-002
p50k p50k_base 代码模型,text-davinci-002,text-davinci-003
p50k_edit p50k_edit 用于编辑模型,如 text-davinci-edit-001,code-davinci-edit-001
r50k r50k_base(或 gpt2) GPT-3 模型,如 davinci
gpt2 o200k_base GPT-4o 模型

有关不同 tokenizer 的更多上下文,请参阅 OpenAI Cookbook

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs How To Cli (`website/src/content/docs/zh/docs/how_to/cli.mdx`)


title: Code2Prompt 基本使用

import { Card } from "@astrojs/starlight/components";
import { Aside } from "@astrojs/starlight/components";

欢迎使用 `Code2Prompt`。

使用方法

从代码库生成提示:

sh
code2prompt path/to/codebase

生成提示并复制到剪贴板:

sh
code2prompt path/to/codebase -c

启动交互式 TUI:

sh
code2prompt path/to/codebase --tui

显示 token‑map:

sh
code2prompt path/to/codebase --token-map

使用自定义 Handlebars 模板:

sh
code2prompt path/to/codebase -t path/to/template.hbs

使用 glob 模式过滤文件:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

使用 glob 模式排除文件:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

根据排除模式从源树中排除文件/文件夹:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

显示生成提示的 token 数量:

sh
code2prompt path/to/codebase --token-format=format

指定用于 token 计数的 tokenizer:

sh
code2prompt path/to/codebase --encoding=p50k

支持的 tokenizer:cl100k、p50k、p50k_edit、r50k_bas。

将生成的提示保存到输出文件:

sh
code2prompt path/to/codebase -O output.txt

以 JSON 格式输出:

sh
code2prompt path/to/codebase -F JSON

JSON 输出示例:

json
{
  "prompt": "<生成的提示>",
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT 模型, text-embedding-ada-002",
  "files": []
}

为已暂存的文件生成 Git 提交信息:

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

为已暂存的文件生成分支比较的 Pull Request:

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

为源码块添加行号:

sh
code2prompt path/to/codebase --line-numbers

在 Markdown 代码块中禁用代码包装:

sh
code2prompt path/to/codebase --no-codeblock

Code2Prompt 是一个出色的工具,可高效生成 token‑优化的提示。它适用于多种场景,例如:

  • 将代码转换为其他语言
  • 查找错误/安全漏洞
  • 为代码编写文档
  • 实现新功能

Website Src Content Docs Zh Docs How To Config (`website/src/content/docs/zh/docs/how_to/config.mdx`)


title: 创建 `.c2pconfig` 文件

import { Card } from "@astrojs/starlight/components";
import { Aside } from '@astrojs/starlight/components';
import { LinkCard } from '@astrojs/starlight/components';

本指南将教您如何创建并使用 `.c2pconfig` 文件,以自动化 Prompt 生成工作流。

手动为每次运行 Code2Prompt 编写冗长的排除模式、Tokenizer 设置或自定义变量会非常繁琐。通过创建 .c2pconfig 配置文件,您可以“一键配置,忘记它”。Code2Prompt 会在当前工作目录自动查找此文件并无缝应用您的规则。

以下是设置首个配置文件的步骤。


初始化配置文件

在终端中进入项目根目录并创建名为 .c2pconfig 的文件:

bash
cd path/to/your/project
touch .c2pconfig

步骤 2:使用 TOML 格式定义基础行为

打开 .c2pconfig,它使用 TOML 语法。粘贴以下基础配置:

toml
# 默认行为配置
default_output = "clipboard"    # 选项: stdout, clipboard, file
output_format = "xml"           # 选项: markdown, json, xml
line_numbers = false            # 为代码块添加行号
encoding = "o200k"              # 与目标 LLM 的 tokenizer 对应

# 全局过滤规则
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = [
    "**/node_modules/**",
    "**/target/**",
    "tests/fixtures/**",
    "package-lock.json"
]

步骤 3:无需参数直接运行

将 .c2pconfig 保存到代码库根目录后,您无需再传递复杂的标志。直接运行:

bash
code2prompt .

Code2Prompt 将自动读取 .c2pconfig,根据您的 glob 模式过滤文件,添加行号,并根据您的选择格式化输出。


后续步骤

若想进一步探索高级工作流、变量和默认配置键,请参考以下教程:


Website Src Content Docs Zh Docs How To Filter Files (`website/src/content/docs/zh/docs/how_to/filter_files.md`)


title: 在 Code2Prompt 中筛选文件

用法

从代码库目录生成提示:

sh
code2prompt path/to/codebase

使用自定义 Handlebars 模板文件:

sh
code2prompt path/to/codebase -t path/to/template.hbs

使用 glob 模式筛选文件:

sh
code2prompt path/to/codebase --include="*.rs,*.toml"

使用 glob 模式排除文件:

sh
code2prompt path/to/codebase --exclude="*.txt,*.md"

根据排除模式从源树中排除文件/文件夹:

sh
code2prompt path/to/codebase --exclude="*.npy,*.wav"

显示生成的提示的 token 数量:

sh
code2prompt path/to/codebase --token-format=format

指定 token 计数器的 tokenizer:

sh
code2prompt path/to/codebase --encoding=p50k

支持的 tokenizer:cl100k、p50k、p50k_edit、r50k_bas。

[!NOTE]
详见 Tokenizers。

将生成的提示保存到输出文件:

sh
code2prompt path/to/codebase --output=output.txt

以 JSON 格式打印输出:

sh
code2prompt path/to/codebase --json

JSON 输出结构如下:

json
{
  "prompt": "<Generated Prompt>", 
  "directory_name": "codebase",
  "token_count": 1234,
  "model_info": "ChatGPT models, text-embedding-ada-002",
  "files": []
}

生成 Git 提交消息(针对暂存文件):

sh
code2prompt path/to/codebase --diff -t templates/write-git-commit.hbs

生成拉取请求与分支比较(针对暂存文件):

sh
code2prompt path/to/codebase --git-diff-branch 'main, development' --git-log-branch 'main, development' -t templates/write-github-pull-request.hbs

在源代码块中添加行号:

sh
code2prompt path/to/codebase --line-numbers

禁用在 Markdown 代码块中换行代码:

sh
code2prompt path/to/codebase --no-codeblock
  • 将代码重写为另一种语言。
  • 查找错误/安全漏洞。
  • 记录代码。
  • 实现新功能。

我最初编写此工具用于个人使用,以便利用 Claude 3.0 的 200K 上下文窗口,事实证明它非常有用,因此我决定将其开源!

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs How To Install (`website/src/content/docs/zh/docs/how_to/install.mdx`)


title: 安装 Code2Prompt

import { Card } from "@astrojs/starlight/components";
import { Steps } from "@astrojs/starlight/components";

import { Tabs, TabItem } from "@astrojs/starlight/components";

欢迎来到 `Code2Prompt` 安装指南。本文档提供了在各种平台(包括 Windows、macOS 和 Linux)上安装 Code2Prompt 的逐步说明。

TL;DR

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

前置条件

确保您的系统上已安装 Rust 和 cargo。

sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

这是安装最新稳定版 Rust 和 Cargo 的官方方法。安装 Rust 后,请确保刷新您的 PATH 变量。重启您的终端或运行安装程序建议的命令。

sh
source $HOME/.cargo/env

您可以通过运行以下命令检查所有内容是否正确安装:

sh
cargo --version
git --version

命令行界面(CLI) 👨‍💻

bash
# Cargo
$ cargo install code2prompt

# Homebrew
$ brew install code2prompt

🧪 从 GitHub 安装最新(未发布)版本

如果您想要在 crates.io 发布之前使用最新功能或修复:

sh
cargo install --git https://github.com/mufeedvh/code2prompt

源代码构建

适用于想要从源代码构建或为项目做出贡献的开发人员。

  1. 🛠️ 安装前置条件:

  2. 📥 克隆仓库:

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt
  3. 📦 安装二进制文件:

    从源代码构建和安装:

    sh
    cargo install --path crates/code2prompt

    在不安装的情况下构建二进制文件:

    sh
    cargo build --release

    二进制文件将在 target/release 目录中可用。

  4. 🚀 运行它:

    sh
    code2prompt --help

二进制发布

最适合想要使用最新版本而无需从源代码构建的用户。

从 Releases 下载您操作系统的最新二进制文件。

⚠️ 二进制发布可能会落后于最新的 GitHub 版本。若要使用前沿功能,请考虑从源代码构建。

AUR

专门为 Arch Linux 用户,code2prompt 可在 AUR 上使用。

code2prompt 可在 AUR 上使用。通过任何 AUR 助手安装它。

sh
paru/yay -S code2prompt

Nix

如果您正在使用 Nix,可以使用 nix-env 或 nix profile 安装。

sh
# without flakes:
nix-env -iA nixpkgs.code2prompt
# with flakes:
nix profile install nixpkgs#code2prompt

软件开发工具包(SDK) 🐍

Pypi

您可以从 Pypi 下载 Python 绑定。

sh
pip install code2prompt_rs

源代码构建

  1. 🛠️ 安装前置条件:

  2. 📥 克隆仓库:

    sh
    git clone https://github.com/mufeedvh/code2prompt.git
    cd code2prompt/crates/code2prompt-python
  3. 📦 安装依赖项:

    uv 会创建 .venv、锁定开发依赖项,并以可编辑模式构建原生扩展。

    sh
    uv sync
  4. 🧪 运行测试:

    在同步后的环境中运行项目测试命令。

    sh
    uv run pytest

模型上下文协议(MCP) 🤖

自动安装

code2prompt MCP 服务器将很快在 MCP 注册表中可用。

手动安装

code2prompt MCP 服务器仍处于原型阶段,很快将集成到主仓库中。

在本地运行 MCP 服务器,以便与 Cline、Goose 或 Aider 一起使用:

  1. 🛠️ 安装前置条件:

  2. 📥 克隆仓库:

    sh
    git clone https://github.com/odancona/code2prompt-mcp.git
    cd code2prompt-mcp
  3. 📦 安装依赖项:

    rye 命令将创建虚拟环境并在 .venv 文件夹中安装所有依赖项。

    sh
    rye sync
  4. 🚀 运行服务器:

    MCP 服务器现已安装。您可以使用以下命令运行它:

    sh
    . .venv/bin/activate
    python -m src/code2prompt_mcp/main.py
  5. 🔌 与代理集成:

    text
    例如,您可以使用类似的配置将其与 `Cline` 集成:
    
        ```json
        {
          "mcpServers": {
            "code2prompt": {
              "command": "bash",
              "args": [
                "-c",
                "cd /home/olivier/projet/code2prompt-mcp && rye run python /home/olivier/projet/code2prompt-mcp/src/code2prompt_mcp/main.py"
              ],
              "env": {}
            }
          }
        }
        ```

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs How To Ssh (`website/src/content/docs/zh/docs/how_to/ssh.md`)


title: 在 SSH 环境下使用 Code2prompt CLI

为什么无法工作?

当您尝试通过 SSH 在远程服务器上运行 code2prompt CLI 时,命令无法找到剪贴板。这是因为 code2prompt CLI 使用剪贴板复制生成的提示,而 SSH 会话通常无法访问本地剪贴板。

解决方案

要在 SSH 环境下使用 code2prompt CLI,您可以将输出重定向到文件,而不是复制到剪贴板。这样,您仍然可以生成提示并将其保存以备后用。

使用 --output-file 选项指定输出文件,其中将保存生成的提示。例如:

sh
ssh user@remote-server "code2prompt path/to/codebase -O output.txt"

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs How To Tui (`website/src/content/docs/zh/docs/how_to/tui.mdx`)


title: 使用 Code2Prompt 终端 UI (TUI)

import { Card } from "@astrojs/starlight/components";

`Code2Prompt` 提供了完整的交互式终端用户界面 (TUI)。本指南将带您了解如何启动 TUI 并掌握其五个核心标签页。

启动 TUI

在命令中添加 --tui 标志并指定项目路径,即可打开交互式界面:

sh
code2prompt path/to/codebase --tui

1. 选择标签页(文件树)

此标签页用于构建要发送给 LLM 的精确上下文。它显示项目的层次结构,并遵循 .gitignore 与 .c2pconfig 规则。

  • 导航: 使用 ↑ / ↓ 移动光标,← / → 展开或折叠目录。
  • 选择: 按空格键选择或取消选择单个文件或整个目录。
  • 搜索: 按 s 或 / 进入搜索模式,输入文本或通配符 (*, ?) 即时过滤树。
  • 退出: 按 Enter 或 Esc 退出搜索模式,返回常规导航。

2. 设置标签页

在生成之前,您可以通过此标签页的可视化复选框和下拉菜单调整输出格式。

3. 统计标签页

在将大型 Prompt 发送给 LLM 之前,使用此标签页了解您的 token 预算。

使用 ← / → 在三个强大的视图之间切换:

4. 模板标签页

此标签页是魔法发生的地方。它提供了一个多列自适应布局,帮助您创建完美的 Handlebars 模板。

在模板标签页中,使用键盘快捷键可在三个子面板之间快速切换:

5. 输出标签页

完成文件选择、设置调整和模板选择后,按 Enter 生成最终输出。

  • 滚动: 使用 ↑ / ↓、PgUp 或 PgDn 查看生成的文本。
  • 复制: 按 c 将整个 Prompt 复制到系统剪贴板。
  • 保存: 按 s 将 Prompt 保存为本地 Markdown 文件(例如 prompt_20260613_204753.md)。

如果发现遗漏的文件,只需按 1 返回选择标签页,标记文件后再次按 Enter 即可实时重新生成。


Website Src Content Docs Zh Docs References Command Line Options (`website/src/content/docs/zh/docs/references/command_line_options.md`)


title: Code2Prompt 命令行选项

命令行选项

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs References Default Template (`website/src/content/docs/zh/docs/references/default_template.md`)


title: Code2Prompt 默认模板

默认模板

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Tutorials Configuration (`website/src/content/docs/zh/docs/tutorials/configuration.mdx`)


title: Code2Prompt 配置 📖

import { Card, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

手动编写冗长的排除模式或特定的 tokenizer 设置会非常繁琐。本教程将展示 **如何使用 `.c2pconfig` 配置文件** 来实现“一键配置,忘记它”的项目设置。

前置条件

确保已安装 code2prompt。如果尚未安装,请参阅 安装指南。了解 TOML 语法 会有帮助,但不是必需的。

什么是 `.c2pconfig`?

.c2pconfig 是一个 TOML 格式的配置文件。运行 code2prompt 时,它会自动在当前工作目录查找此文件并应用其中的设置。

您可以使用它来定义:

  • 过滤规则: 持久化的 include / exclude 模式。
  • 输出格式: 默认支持 JSON、Markdown 或 XML。
  • 模板上下文: 为 Handlebars 模板预定义变量。

快速入门

在项目根目录创建 .c2pconfig,并设置基础行为。

toml
# 基础行为配置
default_output = "stdout"   # 选项: stdout, clipboard, file
include_patterns = ["src/**/*.rs", "Cargo.toml"]
exclude_patterns = ["**/target/**", "tests/fixtures/**"]
line_numbers = true
output_format = "markdown"

[user_variables]
project_name = "MyAwesomeProject"
author = "Developer"

配置参考

以下表格列出了 .c2pconfig 中可用的键:

键 类型 描述
path String 代码库的默认路径(通常为 .)
include_patterns Array 包含的文件 glob 模式
exclude_patterns Array 排除的文件 glob 模式
line_numbers Boolean 为代码块添加行号
absolute_path Boolean 使用绝对路径而非相对路径
full_directory_tree Boolean 即使是被排除的文件也生成完整目录树
output_format String markdown, json, xml
sort_method String name_asc, name_desc, date_asc, date_desc
encoding String Tokenizer: cl100k, p50k, o200k
diff_enabled Boolean 包含 Git diff(HEAD 与 Index)
token_map_enabled Boolean 显示 token 使用的层次图

实施步骤

1. **初始化配置** ```bash touch .c2pconfig ```
  1. 设置全局过滤
    排除 node_modules、构建产物等大型目录,以保持 LLM 上下文的干净。

    toml
    exclude_patterns = [
      "**/node_modules/**",
      "package-lock.json",
      "dist/**"
    ]
  2. 选择 Tokenizer
    根据目标 LLM 选择 tokenizer。GPT‑4o 使用 o200k,Claude 与 GPT‑4 使用 cl100k。

    toml
    encoding = "o200k"
  3. 添加用户变量
    在 [user_variables] 部分定义将在 Handlebars 模板中使用的自定义变量。

    toml
    [user_variables]
    project_goal = "重构认证模块以提升安全性"
  4. 无需额外标志运行

    bash
    code2prompt .

理解优先级

CLI 参数 > .c2pconfig > 默认设置。这样您可以保留基础配置,同时在需要时通过 CLI 临时覆盖。

“审查准备” 示例配置

如果您的主要目标是为代码审查生成 Prompt,请使用以下配置:

toml
default_output = "clipboard"
include_patterns = ["*.rs"]
exclude_patterns = ["**/test*","**code2prompt-python*"]
line_numbers = false
absolute_path = true

[user_variables]
project = "code2prompt"

接下来的步骤


Website Src Content Docs Zh Docs Tutorials Getting Started (`website/src/content/docs/zh/docs/tutorials/getting_started.mdx`)


title: Code2Prompt入门指南

import { Aside } from "@astrojs/starlight/components";
import { Tabs, TabItem } from "@astrojs/starlight/components";
import { Card, CardGrid } from "@astrojs/starlight/components";

欢迎使用Code2Prompt!本教程将为您全面介绍如何使用Code2Prompt从代码库中生成适用于AI的提示。我们将探索其核心功能,并演示其在不同集成方式下的使用:命令行界面(CLI)、软件开发工具包(SDK)和模型上下文协议(MCP)。

什么是Code2Prompt?

Code2Prompt是一款多功能工具,旨在弥合代码库与大型语言模型(LLM)之间的差距。它智能地提取相关代码片段,应用强大的过滤功能,并将信息格式化为适用于LLM的 structured 提示。这简化了代码文档、错误检测、重构等任务。

Code2Prompt提供不同的集成点:

一个核心的Rust库,为代码读取和提示生成提供基础。 一个用户友好的命令行界面,用于快速生成提示。适用于交互式使用和一次性任务。 一个功能强大的软件开发工具包(SDK),可与Python项目无缝集成。适用于在更大的工作流中自动生成提示。 一个模型上下文协议(MCP)服务器,用于与LLM代理进行高级集成。使代码库能够进行复杂、实时的交互。

📥 安装

有关所有方法(CLI、SDK、MCP)的详细安装说明,请参阅综合安装指南。

🏁 生成提示:CLI示例

让我们从使用CLI的一个简单示例开始。创建一个示例项目:

bash
mkdir -p my_project/{src,tests}
touch my_project/src/main.rs my_project/tests/test_1.rs
echo 'fn main() { println!("Hello, world!"); }' > my_project/src/main.rs

现在,生成一个提示:

bash
code2prompt my_project

这会将提示复制到您的剪贴板。您可以自定义此操作:

  • 过滤: code2prompt my_project --include="*.rs" --exclude="tests/*"(仅包含 .rs 文件,排除 tests 目录)
  • 输出文件: code2prompt my_project --output-file=my_prompt.txt
  • JSON输出: code2prompt my_project -O json(结构化JSON输出)
  • 自定义模板: code2prompt my_project -t my_template.hbs(需要创建 my_template.hbs)

请参阅了解上下文过滤和了解Handlebar模板教程,以了解更多高级用法。

🐍 SDK集成(Python)

对于程序化控制,请使用Python SDK:

python
from code2prompt_rs import Code2PromptConfig, Code2PromptSession

config = Code2PromptConfig(
    "my_project",
    include_patterns=["*.rs"],
    exclude_patterns=["tests/*"],
)

session = Code2PromptSession(config)
result = session.generate_prompt()
print(result.prompt)

这需要安装SDK(pip install code2prompt_rs)。有关更多详细信息,请参阅SDK文档。

🤖 MCP服务器集成(高级)

对于与LLM代理的高级集成,请运行code2promptMCP服务器(有关详细信息,请参阅安装指南)。这允许代理动态请求代码上下文。这是一个高级功能,项目的网站上有进一步的文档。

探索高级教程和文档,以掌握Code2Prompt的功能,并将其集成到您的工作流中。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Tutorials Learn Filters (`website/src/content/docs/zh/docs/tutorials/learn_filters.mdx`)


title: 使用 Code2Prompt 学习上下文过滤

import { Card } from "@astrojs/starlight/components";

本教程演示如何使用 `code2prompt` CLI 中的 **glob 模式工具**,根据包含和排除模式过滤和管理文件。

Glob 模式的工作方式类似于 tree 或 grep 等工具,提供强大的过滤功能。有关更多信息,请查看详细说明。


前提条件

确保您已安装 code2prompt。如果尚未安装,请参考安装指南。


了解包含和排除模式

Glob 模式允许您指定过滤文件和目录的规则。

  • 包含模式 (--include):指定要包含的文件和目录。
  • 排除模式 (--exclude):指定要排除的文件和目录。
  • 优先级 (--include-priority):解决包含和排除模式之间的冲突。

设置环境

为了使用 glob 模式进行实践,我们来创建一个包含一些文件的示例文件夹结构。

生成测试结构的 Bash 脚本

运行此脚本以设置临时目录结构:

bash
#!/bin/bash

# 创建基础目录
mkdir -p test_dir/{lowercase,uppercase,.secret}

# 在结构中创建文件
echo "content foo.py" > "test_dir/lowercase/foo.py"
echo "content bar.py" > "test_dir/lowercase/bar.py"
echo "content baz.py" > "test_dir/lowercase/baz.py"
echo "content qux.txt" > "test_dir/lowercase/qux.txt"
echo "content corge.txt" > "test_dir/lowercase/corge.txt"
echo "content grault.txt" > "test_dir/lowercase/grault.txt"

echo "CONTENT FOO.py" > "test_dir/uppercase/FOO.PY"
echo "CONTENT BAR.py" > "test_dir/uppercase/BAR.PY"
echo "CONTENT BAZ.py" > "test_dir/uppercase/BAZ.PY"
echo "CONTENT QUX.txt" > "test_dir/uppercase/QUX.TXT"
echo "CONTENT CORGE.txt" > "test_dir/uppercase/CORGE.TXT"
echo "CONTENT GRAULT.txt" > "test_dir/uppercase/GRAULT.TXT"

echo "top secret" > "test_dir/.secret/secret.txt"

要清理结构,请运行:

bash
rm -rf test_dir

它将创建以下目录结构:

import { FileTree } from "@astrojs/starlight/components";

- test_dir - lowercase - foo.py - bar.py - baz.py - qux.txt - corge.txt - grault.txt - uppercase - FOO.PY - BAR.PY - BAZ.PY - QUX.txt - CORGE.txt - GRAULT.txt - .secret - secret.txt

示例:使用包含和排除模式过滤文件

案例 1:无包含,无排除

命令:

bash
code2prompt test_dir

结果

所有文件都被包含:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py
  • .secret/secret.txt

案例 2:排除特定文件类型

排除 .txt 文件:

bash
code2prompt test_dir --exclude="*.txt"

结果

已排除:

  • 所有 .txt 文件

已包含:

  • lowercase/foo.py
  • lowercase/bar.py
  • uppercase/FOO.py

案例 3:包含特定文件类型

仅包含 Python 文件:

bash
code2prompt test_dir --include="*.py"

结果

已包含:

  • 所有 .py 文件

已排除:

  • .secret/secret.txt

案例 4:包含和排除具有优先级

包含 .py 文件,但排除 uppercase 文件夹中的文件:

bash
code2prompt test_dir --include="*.py" --exclude="**/uppercase/*" --include-priority=true

结果

已包含:

  • 所有 lowercase/1 文件,具有 .py 扩展名

已排除:

  • 所有 uppercase 文件
  • .secret/secret.txt

总结

code2prompt 中的 glob 模式工具允许您使用以下方法有效地过滤文件和目录:

  • --include 指定要包含的文件
  • --exclude 指定要排除的文件
  • --include-priority 解决模式之间的冲突

要练习,请设置示例目录,尝试运行命令,并查看工具如何动态过滤文件。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Tutorials Learn Templates (`website/src/content/docs/zh/docs/tutorials/learn_templates.mdx`)


title: 使用 Code2Prompt 学习 Handlebar 模板

import { Card } from "@astrojs/starlight/components";

本教程演示如何使用和创建自定义 Handlebars 模板,在 `code2prompt` CLI 中进行提示生成。

先决条件

确保您已安装 code2prompt。如果您尚未安装,请参考 安装指南。


什么是 Handlebars 模板?

Handlebars 是一个流行的模板引擎,允许您使用占位符创建动态模板。在 code2prompt 中,Handlebars 模板用于根据代码库结构和用户定义的变量格式化生成的提示。

如何使用 Handlebars 模板?

您可以通过传递 -t 或 --template 标志,后面跟着模板文件的路径来使用这些模板。例如:

sh
code2prompt path/to/codebase -t templates/document-the-code.hbs

模板语法

Handlebars 模板使用简单的语法表示占位符和表达式。您将变量放在双花括号 {{variable_name}} 中,以将其包含在生成的提示中。 code2prompt 提供了一些默认变量,您可以在模板中使用:

  • absolute_code_path:代码库的绝对路径。
  • source_tree:代码库的源树,包括所有文件和目录。
  • files:代码库中的文件列表,包括其路径和内容。
  • git_diff:代码库的 git diff(如果适用)。
  • code:正在处理的文件的内容。
  • path:正在处理的文件的路径。

您还可以使用 Handlebars 助手在模板中执行条件逻辑、循环和其他操作。例如:

handlebars
{{#if files}}
  {{#each files}}
    文件:
    {{this.path}}
    内容:
    {{this.content}}
  {{/each}}
{{else}}
  未找到文件。
{{/if}}

现有模板

code2prompt 带有一些内置模板,用于常见用例。您可以在 templates 目录中找到它们。

[`document-the-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/document-the-code.hbs)

使用此模板生成文档代码的提示。它将在代码库中的所有公共函数、方法、类和模块中添加文档注释。

[`find-security-vulnerabilities.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/find-security-vulnerabilities.hbs)

使用此模板生成查找代码库中潜在安全漏洞的提示。它将查找常见的安全问题,并提供有关如何修复或缓解它们的建议。

[`clean-up-code.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/clean-up-code.hbs)

使用此模板生成清理和提高代码质量的提示。它将查找改进可读性、遵守最佳实践、效率、错误处理等机会。

[`fix-bugs.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/fix-bugs.hbs)

使用此模板生成修复代码库中错误的提示。它将帮助诊断问题、提供修复建议,并使用建议的修复更新代码。

[`write-github-pull-request.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-pull-request.hbs)

使用此模板通过比较两个分支的 git diff 和 git log,创建 GitHub 拉取请求描述,格式为 Markdown。

[`write-github-readme.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-github-readme.hbs)

使用此模板为项目生成高质量的 README 文件,适合在 GitHub 上托管。它将分析代码库以了解其目的和功能,并以 Markdown 格式生成 README 内容。

[`write-git-commit.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/write-git-commit.hbs)

使用此模板从 git 目录中的暂存文件生成 git 提交。它将分析代码库以了解其目的和功能,并以 Markdown 格式生成 git 提交消息内容。

[`improve-performance.hbs`](https://github.com/mufeedvh/code2prompt/tree/main/crates/code2prompt-core/templates/improve-performance.hbs)

使用此模板生成改进代码库性能的提示。它将查找优化机会、提供具体建议,并使用更改更新代码。

用户定义变量

code2prompt 支持在 Handlebars 模板中使用用户定义的变量。模板中的任何不属于默认上下文(absolute_code_path、source_tree、files)的变量都将被视为用户定义的变量。

在生成提示期间,code2prompt 将提示用户输入这些用户定义的变量的值。这允许根据用户输入进一步自定义生成的提示。

例如,如果您的模板包含 {{challenge_name}} 和 {{challenge_description}},则在运行 code2prompt 时将被提示输入这些变量的值。

此功能使得创建可重用的模板成为可能,这些模板可以根据用户提供的信息适应不同的场景。

为了您的方便,本页面已自动翻译。请参考英文版本获取原始内容。


Website Src Content Docs Zh Docs Tutorials Tui (`website/src/content/docs/zh/docs/tutorials/tui.mdx`)


title: 使用终端 UI (TUI)

import { Card, CardGrid, Steps, Aside, Tabs, TabItem } from "@astrojs/starlight/components";

`Code2Prompt` 提供了完整的交互式终端 UI (TUI)。本教程将逐步演示如何启动 TUI 并使用其五个核心标签页。

启动 TUI

在命令中添加 --tui 标志并指定项目路径,即可打开交互式界面:

sh
code2prompt path/to/codebase --tui

1. 选择标签页(文件树)

  • 导航: ↑ / ↓ 移动光标,← / → 展开或折叠目录。
  • 选择: 按 Space 选择或取消选择单个文件或整个目录。
  • 搜索: 按 s 或 / 进入搜索模式,输入文本或通配符 (*, ?) 即时过滤树。
  • 退出: 按 Enter 或 Esc 退出搜索模式,返回常规导航。

2. 设置标签页

在生成之前,您可以通过此标签页的可视化复选框和下拉菜单调整输出格式。

3. 统计标签页

在将大型 Prompt 发送给 LLM 之前,使用此标签页检查您的 token 预算。

使用 ← / → 在三个强大的视图之间切换:

4. 模板标签页

此标签页是魔法发生的地方。它提供了一个多列自适应布局,帮助您创建完美的 Handlebars 模板。

在模板标签页中,使用键盘快捷键可在三个子面板之间快速切换:

5. 输出标签页

完成文件选择、设置调整和模板选择后,按 Enter 生成最终输出。

  • 滚动: ↑ / ↓, PgUp 或 PgDn 查看生成的文本。
  • 复制: 按 c 将整个 Prompt 复制到系统剪贴板。
  • 保存: 按 s 将 Prompt 保存为本地 Markdown 文件(例如 prompt_20260613_204753.md)。

如果忘记添加文件,只需按 1 返回选择标签页,标记文件后再次按 Enter 即可实时重新生成。


--- METRICS ---