←  cshw: The C Shell for Windows

Chapter 17

AI in Your Shell: The genai Command

In This Chapter

This is the chapter that earns cshw the right to be called something other than a shell. Most shells expect you to shell out to Python or curl to talk to an AI provider. cshw has the integration built in: register your API key once, and genai becomes an ordinary command in your shell, ready to ask, analyze, and generate at the prompt or inside any script. Combined with the coroutines from Chapter 14 and the networking from Chapter 16, you can do real concurrent LLM work in 30 lines of shell script.

You don't need an AI provider to read this chapter usefully, but you do need one to run the examples. The good news: both major providers (OpenAI and Anthropic) offer free credits to new accounts, and cshw also supports local model runners like Ollama and LM Studio that cost nothing and work offline. By the time you finish this chapter, you'll have a path to whichever model fits your budget and privacy preferences.


Why AI in a Shell?

The shell has always been the right place for small automation. Renaming files, extracting columns, filtering logs, batch processing — the stuff that's annoying to write a full program for but tedious to do by hand. The shell's been the answer for fifty years.

What LLMs add is judgment. The shell is great at deterministic transformations: "for every file matching this pattern, do this exact thing." It's bad at "look at this log and figure out which lines are interesting." It's bad at "summarize this report in one sentence." It's bad at "is this email a phishing attempt?"

Those are exactly the cases LLMs handle well. So genai is the answer to "I want the shell to do the parts of the job that need judgment, while everything else stays normal shell scripting." A for loop over a folder of files, calling genai analyze on each one to classify them. A pipeline that runs wc, sort, and uniq, then pipes the result through genai ask to produce an English summary. Five lines instead of a Python script.

The shell stays a shell. The AI handles the judgment.


Registering a Provider

Before genai can do anything, you need to tell it where to send requests. The register command sets up a provider — an API key, an endpoint, a default model, all bundled under a nickname you choose.

Cloud providers

The two big ones:

genai register gpt4 openai sk-xxxxx
genai register claude anthropic sk-ant-xxxxx

Format: genai register <NICKNAME> <TYPE> <API_KEY>. The nickname is whatever you want to call this provider in commands later (gpt4, claude, assistant, whatever fits). The type tells genai which API protocol to use; the supported types are:

Optional flags

The register command takes a few flags to configure the provider further:

genai register gpt4 openai sk-xxxxx -m gpt-4o                                   # pick a model
genai register claude anthropic sk-ant-xxxxx -m claude-opus-4-8                 # likewise
genai register azure_gpt azure sk-xxxxx -e https://my.openai.azure.com \
    -d gpt-4-deployment -v 2024-02-15-preview                                   # Azure needs more

The model name in -m is whatever string the provider currently exposes — gpt-4o, claude-opus-4-8, claude-sonnet-5, claude-haiku-4-5 for the cloud providers as of writing. Use genai models NICKNAME (covered below) to see the current list for any registered provider.

The flag set:

Local providers — free, offline, private

For the privacy-conscious or the cost-conscious, you can register a local model server. Ollama is the easiest path; install it from ollama.com, run ollama pull llama3 to download a model, and:

genai register llama ollama - -e http://localhost:11434 -m llama3

Note the - where the API key would go — local providers don't need a key, so use a dash as a placeholder.

LM Studio works similarly:

genai register lmstudio_local lmstudio - -e http://localhost:1234 -m mistral-7b

Both run entirely on your machine. No data leaves your computer; no per-request cost; no rate limits beyond what your GPU can handle.

TIP

Register multiple providers and switch between them as needed. A common setup: register Claude for serious reasoning ("claude" → Anthropic), register a fast cheap model for routine tasks ("fast" → GPT-4o-mini or a small local model), and use whichever the task calls for. Switching is genai ask -n claude "..." vs genai ask -n fast "...".

WARNING

Your API keys are stored on disk (under %APPDATA%\cshw\). Treat them as you would any other credential: don't commit your shell config to a public repo, don't share screen-recordings showing the file contents, and rotate keys when you suspect exposure. For high-security environments, consider local providers (Ollama, LM Studio) that don't have API keys at all.


Managing Providers

A handful of commands for inspecting and adjusting your registered providers:

genai list

Shows all registered providers:

genai list

Output:

NICKNAME     TYPE         MODEL                          DEFAULT
--------     ----         -----                          -------
gpt4         openai       gpt-4o                         
claude       anthropic    claude-opus-4-8                *
llama        ollama       llama3                         

The asterisk in the DEFAULT column shows which provider is currently the default — the one used when you don't specify -n NAME in ask/analyze/code.

genai default [NICKNAME]

With no argument, shows the current default. With a nickname, sets it:

genai default              # show -- prints "claude"
genai default gpt4         # change -- gpt4 is now the default

genai test [NICKNAME]

Sends a minimal test request to verify the provider is reachable and the credentials work:

genai test claude

Output (on success):

Testing connection to 'claude'...
Connection successful!

Run this once after registering each provider — it's the fastest way to catch a fat-fingered API key or a typo in the endpoint URL.

genai models [NICKNAME]

Asks the provider for a list of available models:

genai models claude

Output:

Available models for 'claude':
  claude-opus-4-8
  claude-sonnet-5
  claude-haiku-4-5

Useful for picking a specific model in -m. The list comes from the provider's models endpoint, so it'll show whatever's currently available on your account.

genai remove NICKNAME

Forgets a provider:

genai remove gpt4

Removes the entry from the config file. The API key is dropped from disk; you'd need to register again to use the provider.


The Three Interaction Commands

With a provider registered, three commands actually talk to the AI:

Command Purpose
genai ask General-purpose Q&A
genai analyze Send a file's contents plus a prompt
genai code Code generation with code-tuned defaults

genai ask — the workhorse

genai ask "What's the time complexity of merge sort?"

The simplest case: pass a prompt as a quoted string, get a response printed to stdout. The response is also stored in $genai_result for the next command to use.

A few flags worth knowing:

genai ask -n claude "..."                # use the 'claude' provider
genai ask -t 0.2 "..."                   # set temperature (lower = more deterministic)
genai ask --max-tokens 200 "..."         # cap the response length
genai ask -m gpt-4o "..."                # override the default model for this call

Temperature is the standard 0.0–2.0 knob: low = focused, predictable, repetitive; high = creative, varied, occasionally unhinged. The default is 0.7, which is a reasonable middle ground.

Piped input — your real superpower

genai ask accepts piped input. Whatever the pipe sends becomes part of the prompt. This is the single feature that makes genai integrate cleanly with the rest of the shell:

type error.log | genai ask "What might be causing these errors?"

processlist | genai ask "Which of these processes look suspicious?"

dir /b | genai ask "Group these filenames by what they appear to be"

The model sees both the prompt and the piped content; it answers in the context of the data. This pattern — transform with the shell, then think with the AI — is the bread-and-butter of cshw + genai workflows.

genai analyze — file-targeted

When you want to send a specific file to the AI, analyze saves you the type FILE | genai ask dance:

genai analyze main.cpp "Find any bugs in this code"
genai analyze report.txt "Summarize this in three bullet points"
genai analyze suspicious.exe "Could this file be malware?"

The file's contents are sent along with the prompt; the response prints to stdout and lands in $genai_result like ask.

analyze takes the same flags as ask: -n NAME, -t TEMP, --max-tokens N, -m MODEL.

genai code — code generation with code-tuned defaults

For "write me some code," genai code is genai ask with two things changed:

  1. The temperature defaults to 0.3 (more deterministic — you want correctness, not creativity).
  2. The system prompt steers the model toward "output code, nothing else" so responses don't include long explanations unless asked.
genai code "function to reverse a linked list"
genai code -l python "function to reverse a linked list"
genai code -l cpp "function to reverse a linked list"

The -l LANGUAGE flag adds that language to the system prompt. Without -l, the model picks based on context (or asks); with -l, the model commits to the language you specified.

A typical use is generating boilerplate inline in a script:

genai code -l python "FastAPI endpoint that returns the current time" > endpoint.py

One command, one file, no copy-paste from a browser.


The $genai_result Variable

Every successful ask/analyze/code call sets $genai_result to the full response text. This is the bridge between the AI and the rest of your script:

genai ask "Pick a random fruit name. Just the name, nothing else."
echo "Today's fruit is $genai_result"

# Or feed it into another command:
genai ask "Generate a SHA-256 password hash for 'hunter2'"
echo $genai_result | tr a-z A-Z          # transform with normal tools

The variable is persistent — it stays in your shell until the next genai call overwrites it. So you can do things like:

genai analyze report.txt "Summarize in one sentence"
set summary = $genai_result

genai analyze report.txt "Estimate reading time in minutes"
set reading_time = $genai_result

echo "Summary: $summary"
echo "Reading time: $reading_time minutes"

Two separate AI calls, two captured results, both available for the rest of the script.

TIP

When you want the model to give you a single value you can use programmatically (a number, a yes/no, a category name), tell it explicitly. "Just the name, nothing else." "Answer with only Y or N." "Return only a number." Otherwise you'll get prose around the value, and parsing it out is annoying. The combination of low temperature + explicit instruction usually gives clean, structured output.

TRY IT

Save your API key, then try:

dir | genai ask "How many entries are in this listing?"

The model will count what it sees and give you a number. Now imagine doing this for 100 directories with a foreach loop. That's the level of automation genai opens up.


Streaming

By default, genai waits for the full response before printing anything. For long responses, that's a noticeable pause. Stream mode prints chunks as they arrive — like watching the model "type" the answer:

genai settings stream on        # enable streaming globally
genai settings stream off       # disable (default)
genai settings stream           # show current value

With streaming on, you'll see text appear progressively. The trade-off is that streaming responses don't include the trailing token-count summary that buffered responses do (and the [N tokens used] line at the end). For interactive use, streaming feels much better; for scripts that just want the result, leave it off.

TECHNICAL STUFF

genai code always streams, regardless of the global setting — code generation benefits visibly from progressive output. The $genai_result variable is populated correctly either way: the streaming callback accumulates chunks into the final response, and the variable gets the complete text once the stream ends.


Settings

Beyond per-call flags, genai settings adjusts defaults that apply to every call:

genai settings                          # show all settings
genai settings stream on                # toggle streaming
genai settings temperature 0.5          # set default temperature
genai settings max-tokens 2048          # cap default response length

Set these once in your .cshrc and they apply to every interactive genai call you make.


Practical Patterns

This is where genai actually earns its keep. A few patterns you'll reach for again and again.

Log analysis

tail -n 200 server.log | genai ask "What were the most common issues in this log?"

Twelve seconds, one English summary of two hundred log lines. Compare to the time it would take to scan it manually or write a regex pipeline.

Code review

genai analyze new_feature.py "Review this code. List concerns with line numbers."

A code review pass without leaving the terminal. Pair this with version control — git diff main -- new_feature.py | genai ask "Review this diff" is a one-liner that runs every time you're about to commit.

Quick classification

proc classify_file
    genai analyze "$1" "Classify this file as one of: code, prose, config, data, log. Just the category."
    echo "$1 -> $genai_result"
endproc

foreach f (*)
    classify_file "$f"
end

A folder of mystery files becomes a folder with categories. The procedure-plus-foreach idiom you learned in Chapter 10 turns into a working tool once genai is in the loop.

Inline data transformation

echo "alice@example.com,bob@example.com,charlie@example.com" | \
    genai ask "Convert this comma-separated list to a JSON array. Just the JSON, nothing else."

The "just the JSON, nothing else" framing is doing real work — it tells the model to skip the explanation and emit clean output you can pipe into the next command.

Generate test data

genai ask --max-tokens 500 "Generate 10 realistic-looking sample users in CSV format with columns name, email, age, role. Just the CSV." > sample_users.csv

Test data fixtures, on demand. No more hand-typing fake names.

REMEMBER

The model is not deterministic by default. Two calls with the same prompt won't always give the same answer. For repeatable output (test data, code generation that has to match a snapshot), set temperature low (-t 0.0 or -t 0.1). For brainstorming, where variety helps, leave the default 0.7.


Parallel genai with Coroutines

This is the chapter's payoff. You learned coroutines in Chapter 14 and semaphores in Chapter 15. Combine them with genai and you have an LLM analyzer that processes many items concurrently, with bounded fan-out so you don't blow your rate limit.

# parallel_analyze.cshw — concurrent file classifier
#
# Usage: parallel_analyze.cshw [folder]
#
# For each file in the folder, runs `genai analyze` in parallel,
# bounded to 4 concurrent calls. Saves results to results.txt.

set folder = $1
if ("$folder" == "") then
    set folder = "."
endif

semcreate api_pool 4 4

proc classify_one
    set fname = $1
    semaphore api_pool acquire

    genai analyze "$fname" "Classify this file in one word: code, prose, config, data, log, or other. Just the word."

    semaphore api_pool release

    # Append to results (mutex-protected because all coroutines write here)
    mutex out_lock lock
    echo "$fname -> $genai_result" >> results.txt
    mutex out_lock unlock
endproc

# Clear previous results
echo "" > results.txt

# Fan out
foreach f ($folder/*)
    if (-f "$f") then
        corunproc classify_one "$f"
    endif
end

cowait /all
sync destroyall

echo ""
echo "Done. Results in results.txt"
type results.txt

What this does:

For 100 files at 2 seconds each, that's 50 seconds instead of 200. For 1000 files at 3 seconds each, that's ~12 minutes instead of 50.

TIP

Tune the semaphore size to your provider's rate limit. OpenAI's tier-1 free accounts allow 3 requests/minute (so use 1–2 concurrent at most); a paid OpenAI tier might allow 500 concurrent; Anthropic's tiers vary; local providers (Ollama, LM Studio) are limited only by your hardware. Check your provider's docs and pick a semcreate value that uses your headroom without tripping rate-limit errors.

TECHNICAL STUFF

$genai_result is set in the coroutine's local scope (per the Chapter 14 variable-scope rules), so each coroutine sees its own response without interfering with the others. That's exactly what you want — coroutine A's result doesn't get overwritten by coroutine B. The mutex protects the output file write, not the variable read.


Cost, Privacy, and Security

Every shell book chapter that adds AI integration owes the reader an honest discussion of the tradeoffs.

Cost

Cloud AI providers bill per token (roughly per word, give or take). A short query is fractions of a cent; an analysis of a 10-page document is a few cents. Burning through your free credits with a tight foreach loop is easy and surprisingly expensive — the parallel analyzer above on a thousand files could cost a few dollars at GPT-4 rates.

Practical advice:

Privacy

By default, cloud providers may use submitted text for training (policies vary; check your provider's TOS). For sensitive data — source code under NDA, customer records, internal documents — pay close attention to:

Security

The model can be prompted into doing weird things, including by data you didn't write. If you pipe a log file from an untrusted source into genai ask, and that log file contains carefully-crafted text, the model might follow instructions in the log rather than answering your question. This is "prompt injection," and there's no fully reliable defense.

In practice:

WARNING

genai ask "Run this on my files: $piped_user_input" is a footgun if $piped_user_input could contain "Ignore previous instructions and ..." text. The model might play along. For automation that touches the filesystem or runs commands, prefer well-defined narrow outputs ("classify as: a, b, c") and parse them with normal shell logic, rather than letting the model dictate next steps.


Honest Limits

A few things genai doesn't do (yet, in this version):

For most "talk to the AI" use cases, those limits don't matter. For agentic workflows (tool-calling, multi-turn reasoning, structured output), you might want to drop into Python with a proper SDK.


Onward

That's genai. You can now have your shell think alongside doing — log analysis, code review, classification, summarization, code generation, all available as ordinary shell commands that compose with everything else you've learned. Add coroutines and semaphores and you can run hundreds of AI tasks in parallel.

Chapter 18 comes next: extending cshw with plugin DLLs. The chapters so far have shown what cshw can do out of the box. Chapter 18 shows how to make cshw do more — write your own command in C or C++, compile it as a DLL, load it into the shell with rcl (register command library), and use it like any built-in command. We'll also look at dllimport and rundllproc for calling functions in arbitrary Windows DLLs without writing any C at all.

After that, Chapter 19 puts it all together into standalone servers — the tsrvd daemon family, including a working mail stack — before Part V wraps up with the Top Tens (Ten Commands You'll Use Every Day, Ten Things cshw Does cmd.exe Doesn't, Ten Tricks for When You're Stuck) and the Appendix cheat sheet.

For now, you've added AI to your shell vocabulary. That's a chapter that didn't exist in the shell-scripting books anyone wrote five years ago — and might not in many of the ones being written today.

Welcome to the future of the command line.