LINUX.ORG.RU

Neural Shell - человекопонятный CLI

 , , , ,


1

4

Всем привет

Я написал небольшую CLI утилиту, которая переводит человекопонятный запрос в соответствующую shell-команду или one-liner при помощи подключаемой LLM прямо в терминале, и хотел бы поделиться ей с миром. Знаю, что подобные утилиты уже давно существуют, но в своей я реализовал несколько удобных мне фич, и надеюсь что кто-нибудь тоже найдёт их полезными для себя.

Вот ссылка на GitHub, там-же из README можно узнать все детали.

Также есть на PyPI, установить и попробовать можно и через pip:

pip install neural-shell

Если коротко, тулза работает так:

nlsh find all pdfs modified in the last 2 days and compress them
# Example output:
# Suggested: find . -name "*.pdf" -mtime -2 -exec tar czvf archive.tar.gz {} +
# [Confirm] Run this command? (y/N/e/r/x) y 
# Executing:
# (command output appears here)

Из фич:

  • можно запросить объяснение сгенерированной команды (x)
  • перегенерировать с большей креативностью («температурой»), если команда не подходит (r)
  • отредактировать команду перед выполнением (e)
  • после выполнения, если exit code != 0, тулза предложит исправить команду, проанализировав её вывод и exit code
  • при генерации учитывает информацию о системе

Конфигурируется ямлем в ~/.nlsh/config.yml, можно настроить несколько бэкендов, и переключаться между ними флагами -0, -1, -2, и т. д.:

shell: "zsh"  # Override with env $NLSH_SHELL
backends:
  - name: "local-ollama"
    url: "http://localhost:11434/v1"
    api_key: "ollama"
    model: "llama3"
  - name: "groq-cloud"
    url: "https://api.groq.com/v1"
    api_key: $GROQ_KEY
    model: "llama3-70b-8192"
  - name: "deepseek-reasoner"
    url: "https://api.deepseek.com/v1"
    api_key: $DEEPSEEK_API_KEY
    model: "deepseek-reasoner"
    is_reasoning_model: true  # Mark as a reasoning model for verbose mode
default_backend: 0

# Configuration for the 'nlgc' (Neural Git Commit) command
# Override with environment variable: NLSH_NLGC_INCLUDE_FULL_FILES (true/false)
nlgc:
  # Whether to include the full content of changed files in the prompt
  # sent to the LLM for commit message generation. Provides more context
  # but increases token usage significantly. Can be overridden with
  # --full-files or --no-full-files flags.
  include_full_files: true

Бонусом идёт тулза nlgc для генерации красивых коммит месседжей на основе диффов.

Буду рад отзывам, баг репортам и фич реквестам, а также MR’ам.

Спасибо за внимание


~/.nlsh/config.yml

лучше в

${XDG_CONFIG_HOME}/nlsh/config.yml

demidrol ★★★★★
()

а вот например бесплатный gemini

generate linux command to find all pdfs modified in the last 2 days and compress them to zip

response:

find . -name "*.pdf" -mtime -2 -print0 | xargs -0 -I {} sh -c 'echo "Compressing {} to {}.zip"; zip "{}.zip" "{}"'

explanation:

Explanation:

find . -name "*.pdf" -mtime -2 -print0:

This part is identical to the previous command and finds all PDF files modified within the last 2 days.
find .: Searches in the current directory and its subdirectories.
-name "*.pdf": Filters for files ending with .pdf.
-mtime -2: Filters for files modified within the last 2 days.
-print0: Prints filenames separated by null characters, which is safer for filenames with spaces or special characters.
| xargs -0 -I {} sh -c '...':

This pipes the null-separated list of filenames from find to xargs.
xargs -0: Reads the null-separated input.
-I {}: Defines a placeholder {} that will be replaced by each filename from find.
sh -c '...': Executes a shell command for each found PDF file.
'echo "Compressing {} to {}.zip"; zip "{}.zip" "{}"':

echo "Compressing {} to {}.zip": Prints a message indicating which PDF is being compressed and the name of the resulting zip file.
zip "{}.zip" "{}": This is the command that performs the compression:
zip: The command-line utility for creating zip archives. You'll need to have zip installed on your system (e.g., sudo apt-get install zip on Debian/Ubuntu, sudo yum install zip on CentOS/RHEL, sudo pacman -S zip on Arch Linux).
"{}.zip": The name of the zip archive to be created. It will have the same base name as the PDF file with the .zip extension.
"{}": The PDF file that will be added to the zip archive.
How to use it:

Save the command: Copy and paste this command into your terminal.
Execute: Run the command from the directory where you want to start the search.
Important Considerations:

zip Installation: Ensure that the zip command-line tool is installed on your Linux system.
Output Filenames: The compressed archives will be created in the same directory as the original PDF files and will have the .zip extension appended to the PDF filename.
Compression Level: The zip command without any additional options will use the default compression level. You can specify different compression levels using options like -0 (store only, no compression), -1 (fastest compression), -9 (best compression, slowest). For example:
Bash

find . -name "*.pdf" -mtime -2 -print0 | xargs -0 -I {} sh -c 'echo "Compressing {} to {}.zip"; zip -9 "{}.zip" "{}"'
Subdirectories: The find . command will recursively search through all subdirectories. If you only want to search in the current directory, remove the ..
Overwriting: If a zip file with the same name already exists, zip might overwrite it. Be cautious if you have existing .zip files with the same base names as your PDFs. You might want to add logic to handle this if necessary.
Resource Usage: Compressing files can be CPU-intensive, especially for large files or when using higher compression levels.
FishHook
()
Ответ на: комментарий от IPR

Должен, по идее, не пробовал. Но вообще почти все мейнстримные LLM’ки умеют в русский язык. Буду считать это фич-реквестом, и подумаю, как это можно сконфигурировать, спасибо)

eqld
() автор топика
Ответ на: комментарий от FishHook

Это черкз мою тулзу он такое объяснение выдал? Если да, то это подтверждает моё наблюдение что гемини немного раздолбай, и часто не следует даже чётко сформулированным инструкциям, и лепит отсебятину.

eqld
() автор топика
Ответ на: комментарий от eqld

Должен, по идее, не пробовал. Но вообще почти все мейнстримные LLM’ки умеют в русский язык. Буду считать это фич-реквестом, и подумаю, как это можно сконфигурировать, спасибо)

Русский язык — родной, на нём в любом случае я сформулирую запрос яснее, тем более для нейросети. Так что да, фичреквест.

IPR ★★★★★
()
Ответ на: комментарий от eqld

Это черкз мою тулзу он такое объяснение выдал?

эм, нет. Это через браузер.

FishHook
()
Ответ на: комментарий от firkax

Она всё это локально делает?

в стартовом посте:

backends:
  - name: "local-ollama"
    url: "http://localhost:11434/v1"
    api_key: "ollama"
    model: "llama3"
  - name: "groq-cloud"
    url: "https://api.groq.com/v1"
    api_key: $GROQ_KEY
    model: "llama3-70b-8192"
  - name: "deepseek-reasoner"
    url: "https://api.deepseek.com/v1"
    api_key: $DEEPSEEK_API_KEY
    model: "deepseek-reasoner"
FishHook
()
Ответ на: комментарий от firkax

Можно к локальной LLM’ке подсоединить, да. Я, например, в качестве дефолтного бэкенда использую локально запусченую qwen2.5-coder-3b-instruct через LM Studio - простые команды довольно неплохо генерит. Но если железо позволяет, то я бы рекомендовал модель по-умнее, хотя-бы на 7B параметров.

eqld
() автор топика
Ответ на: комментарий от Puzan

Спасибо, позаимствую отсюда пару фичей: понравился пайпинг содержимого файла в STDIN для его процессинга, и revise.

eqld
() автор топика
Ответ на: комментарий от eqld

Попробуй deepseek-coder-v2. Она 16B, но MoE. Качество почти не страдает, а скорость как у 3B. Она же (-base) есть для автодополнения fill-in-the-middle.

Puzan ★★★★★
()
Последнее исправление: Puzan (всего исправлений: 1)
Для того чтобы оставить комментарий войдите или зарегистрируйтесь.