mono/packages/kbot/docs_/examples.md
2025-06-04 13:58:25 +02:00

304 lines
12 KiB
Markdown

# CLI Examples
This page shows various ways to use `kbot` from the command line.
## Basic Modifications
Modify project files based on a prompt:
```bash
# Request a change in the current directory context
kbot "Add comprehensive error handling to all API route handlers"
# Use stdin for the prompt
echo "Refactor the database connection logic into a reusable module" | kbot
# Use a file containing the prompt
kbot --prompt ./prompts/refactor_request.md
# Specify target files using glob patterns
kbot --include "src/controllers/**/*.ts" "Ensure all controller methods return consistent JSON responses"
# Target specific files
kbot --include "src/utils/auth.ts,src/middleware/auth.js" "Update authentication logic to support JWT refresh tokens"
```
## Working with Different Input Sources
`kbot` can process various types of input specified via the `--include` parameter:
```bash
# Include local files and directories
kbot --include "./docs/api.md,./src/server.ts" "Update the API documentation based on the server code"
# Include content from a web URL
kbot --include "https://raw.githubusercontent.com/user/repo/main/README.md" "Summarize this project's README"
# Combine different sources
kbot --include "./config.yaml,https://example.com/api/spec.json" "Generate documentation based on the config and the API spec"
```
## Advanced Data Transformation & Iteration
These examples demonstrate more complex scenarios involving data processing, structured output, and iteration.
### Transforming Data with the Iterator Factory
The `iterator-factory-example.ts` demonstrates advanced usage including transforming specific fields within complex JSON objects, handling arrays, caching results, and generating structured output using the `--format` option.
To run this example:
```bash
# Ensure dependencies are installed, then run:
npm run examples:iterator-factory
# Run without caching:
npm run examples:iterator-factory -- --no-cache
```
This example uses the `createIterator` function for fine-grained control. Explore the code in `src/examples/core/iterator-factory-example.ts` for details.
### Structured Output with `--format`
Force the AI to return data in a specific JSON structure. You can provide the schema as a JSON string, a file path, or a Zod schema string.
```bash
# Using a JSON schema file
kbot --include ./product_review.txt \
--format file:./schemas/review_analysis_schema.json \
"Analyze this review and extract sentiment, pros, and cons according to the schema"
# Using an inline JSON schema string
kbot --include ./data.json \
--format '{"type":"object","properties":{"summary":{"type":"string"},"keywords":{"type":"array","items":{"type":"string"}}},"required":["summary","keywords"]}' \
"Summarize this data and extract keywords"
```
### Iterating with `--each`
Process multiple items (files, models, strings) in sequence.
```bash
# Iterate over specific files and output to separate files
kbot --each "./src/moduleA.ts,./src/moduleB.ts" \
--dst "./docs/${ITEM}.md" \
"Generate documentation for the module defined in ${ITEM}"
# Test a prompt against multiple models
kbot --each "openai/gpt-4o,anthropic/claude-3-sonnet" \
--include ./my_code.py \
--dst "${ITEM}_review.txt" \
"Review this Python code for potential bugs and suggest improvements"
# Iterate over files matching a glob pattern
kbot --each "./tests/**/*.test.js" \
--dst "./coverage/${ITEM}.txt" \
"Analyze the test coverage for ${ITEM}"
```
## Configuration and Control
### Using Profiles and Environments
Load variables from configuration files for different environments.
```bash
# Load variables from a profile and specify an environment
kbot --profile ./config/profiles.json --env staging "Deploy the staging configuration using variables from the profile"
```
### Custom Output Paths
Control where results are saved.
```bash
# Save modifications to a different directory (tool mode)
kbot --output ./refactored_code "Refactor all functions to use async/await"
# Save completion result to a specific file (completion mode)
kbot --mode completion --dst ./summary.md "Summarize the included documents"
```
### Model and Router Selection
Choose the AI provider and specific model.
```bash
# Use a specific OpenAI model
kbot --router openai --model gpt-4o "Translate the included text to French"
# Use a model via OpenRouter (default router)
kbot --model anthropic/claude-3.5-sonnet "Write a poem about the included text"
```
### Tool Control
Enable or disable specific tools or categories.
```bash
# Disable the 'git' category tools
kbot --disable git "Update code documentation without committing changes"
# Disable specific tools by name
kbot --disableTools "npm_install,file_save" "Analyze dependencies but do not install or save files"
```
## More Examples
For more in-depth examples demonstrating various features like custom tools, different modes, and advanced configurations, please explore the code within the `src/examples/` directory of this package.
## Using `--dst` to Specify Output File
The `--dst` parameter allows you to specify a destination file for the output, particularly useful in `completion` or `assistant` mode. You can use variables like `${MODEL_NAME}` and `${ROUTER}` in the filename.
```bash
# Summarize a document and save it to a specific file
kbot --prompt "Summarize the key points of this document." \
--include "./project_report.txt" \
--dst "./summaries/report_summary.md" \
--mode "completion"
# Generate code and save it with model name in the filename
kbot --prompt "Write a Python function to calculate factorial." \
--dst "./output_code/${MODEL_NAME}_factorial.py" \
--model "openai/gpt-4o" \
--mode "completion"
```
## Excluding Files with `--exclude`
The `--exclude` parameter helps you filter out files or directories that you don't want `kbot` to process, even if they match the `--include` patterns.
```bash
# Process all .ts files in the src directory, excluding test files and the node_modules directory
kbot --prompt "Analyze code quality for all non-test TypeScript files." \
--include "./src/**/*.ts" \
--exclude "./src/**/*.test.ts,./src/**/*.spec.ts,node_modules/**" \
--mode "tools"
# Include all markdown files but exclude those in a 'drafts' subdirectory
kbot --prompt "Check for broken links in all published markdown files." \
--include "./docs/**/*.md" \
--exclude "./docs/drafts/*.md"
```
## Finding Related Files with `--globExtension`
The `--globExtension` parameter is used to find files related to the input items (often specified with `--each` or `--include`). This is useful when a task requires context from associated files, like a C++ source file and its corresponding header.
It can take a preset (e.g., `match-cpp`) or a custom glob pattern using variables:
* `${SRC_DIR}`: Directory of the source file.
* `${SRC_NAME}`: Name of the source file without extension.
* `${SRC_EXT}`: Extension of the source file.
```bash
# For each .cpp file, find its corresponding .h file and generate documentation
# (Assumes 'match-cpp' preset is defined to find .h files for .cpp inputs)
kbot --each "./src/modules/*.cpp" \
--globExtension "match-cpp" \
--prompt "Generate documentation for ${ITEM} and its header file." \
--dst "./docs/api/${ITEM}.md"
# For a given C source file, include its header file using a custom pattern
# The --include parameter will be expanded by the globExtension logic to also find the .h file
kbot --prompt "Analyze the C file ${ITEM} and its associated header." \
--include "./src/utils.c" \
--globExtension "'${SRC_DIR}/${SRC_NAME}.h'" \
--dst "./analysis/utils_analysis.txt"
```
This can be particularly powerful when combined with prompts that instruct the AI to consider all included files. The files found by `globExtension` are added to the context.
**Advanced Example: Generating Docs for C++ Headers and Sources**
Here's a more comprehensive example for generating documentation from C++ header files (`.h`). It iterates through each header file found by `--each`, uses `--globExtension="match-cpp"` to automatically include the corresponding `.cpp` source file in the context for the AI, and then generates documentation based on a prompt script.
The output is saved to the `./docs-c/` directory, with each file named after the original header's base name (e.g., `utils.h` becomes `utils.md`).
Key features in this example:
* `--each="./src/*.h"`: Processes each header file in the `src` directory.
* `--globExtension="match-cpp"`: For each `.h` file, it finds and includes the corresponding `.cpp` file.
* `--mode="completion"` and `--dst='./docs-c/${SRC_NAME}.md'`: This combination ensures that if a documentation file for a header already exists at the destination, `kbot` will skip regenerating it, effectively "skipping existing files." The `${SRC_NAME}` variable refers to the base name of the header file.
* `--prompt=./scripts/docs-c.md`: Uses an external markdown file as the prompt.
* `--filters=markdown`: Applies a markdown filter to the output.
* `--exclude='./docs-c/${SRC_NAME}*.md'`: This pattern prevents any existing markdown documentation files in the output directory from being accidentally treated as *input sources* during the process.
```bash
kbot --model=anthropic/claude-3.7-sonnet \
--prompt=./scripts/docs-c.md \
--each=./src/*.h \
--globExtension=match-cpp \
--mode=completion \
--filters=markdown \
--preferences=none \
--exclude='./docs-c/${SRC_NAME}*.md' \
--dst='./docs-c/${SRC_NAME}.md'
```
## Extracting Structured Data from Images (e.g., Modbus Manuals)
This example demonstrates how `kbot` can be used to iterate over a series of images (e.g., pages from a scanned PDF manual) and extract structured information into a single document. It leverages a multimodal model capable of understanding image content.
**Scenario:** Extract Modbus parameters and error codes from JPG images of a device manual and compile them into a Markdown file.
**Command:**
```bash
kbot --model=google/gemini-2.5-pro-preview-03-25 \
--prompt=./tests/pdf/prompt_manual.md \
--each=./tests/pdf/780/*.jpg \
--mode=completion --preferences=none \
--dst=./tests/pdf/sako_manual.md \
--filters=code --append=concat
```
**Key Features Illustrated:**
* `--model=google/gemini-2.5-pro-preview-03-25`: Specifies a multimodal model capable of processing images.
* `--prompt=./tests/pdf/prompt_manual.md`: Uses an external file for a detailed prompt. The content of this prompt is crucial for guiding the AI.
* `--each=./tests/pdf/780/*.jpg`: Iterates over all JPG files in the specified directory.
* `--mode=completion`: The task is a direct completion based on the prompt and each image.
* `--dst=./tests/pdf/sako_manual.md`: All extracted information will be saved to this file.
* `--append=concat`: As `kbot` processes each image (`${ITEM}` from `--each`), the output generated for that image is appended to the `sako_manual.md` file. This is useful for building a cumulative document from multiple sources.
* `--filters=code`: This filter can help clean the output, for instance, by removing potential Markdown code fences if the model wraps its entire response in them, ensuring the content is directly usable.
* `--preferences=none`: Ensures no external user preferences interfere with the prompt.
**Content of the Prompt (`./tests/pdf/prompt_manual.md`):**
```markdown
Extract all parameters, as Markdown tables,
return "Skipping Number Page : Nothing found" if nothing has been found, otherwise use this layout and structure (only valid Markdown!!) :
## Parameters (if provided)
### Columns
- parameter
- description
- if provided, parameter group
- range
- default
- Dont comment or explain, just return Markdown
- insert new lines before and after headers
- insert a descriptive chapter name, header level 3 with the page number
## Error Codes (if provided)
### Columns
- code
- description
- if provided, parameter group
- Dont comment or explain, just return Markdown
- insert new lines before and after headers
- insert a descriptive chapter name, header level 3 with the page number
```
This detailed prompt instructs the AI on:
* The specific information to look for (parameters, error codes).
* The desired output format (Markdown tables).
* The exact column names for the tables.
* How to handle cases where no information is found on a page.
* Formatting details like new lines and header levels, including dynamic information like page numbers (which the AI would infer or be instructed to extract if page numbers are visible in the images and the prompt is adjusted accordingly for `${ITEM}`).