-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnlcmd.sh
More file actions
62 lines (51 loc) · 2.06 KB
/
nlcmd.sh
File metadata and controls
62 lines (51 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# nlcmd - natural language query to bash terminal command
d() {
set -f # no globbing
# check for openAI API key loaded by .bashrc
if [ -z "$OPENAI_API_KEY" ]; then
printf 'OPENAI_API_KEY is not set\n' >&2; set +f; return 1
fi
# check for jq dependency
command -v jq >/dev/null 2>&1 || { printf 'jq not found\n' >&2; set +f; return 1; }
# define local variables
local query="$*"
local shell_name=$(basename "$SHELL")
local term_type=${TERM:-unknown}
local prompt
local payload
local resp
local cmd
# build prompt
prompt="You are a command line expert. The user wants to run a command but they don't know how. The user is running the query inside a ${shell_name} shell with terminal ${term_type}. Here is what they asked: ${query}. Return ONLY the exact shell command needed. Do not prepend with an explanation, no markdown, no code blocks - just return the raw command you think will best solve their query."
# build JSON payload
payload=$(
jq -n --arg model "gpt-5-mini" --arg prompt "$prompt" \
'{model:$model, input:[{role:"user", content:$prompt}]}'
)
# call openAI API
resp=$(
curl -sS https://api.openai.com/v1/responses \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-H "Content-Type: application/json" \
-d "$payload"
) || { printf 'curl failed\n' >&2; set +f; return 1; }
# show API error if present
if printf '%s\n' "$resp" | jq -e '.error' >/dev/null 2>&1; then
printf 'API error: %s\n' "$(printf '%s' "$resp" | jq -r '.error.message')" >&2
set +f; return 1
fi
# filter text content from response
cmd=$(printf '%s\n' "$resp" | jq -r '
.output[] | select(.type=="message")
| .content[] | select(.type=="output_text") | .text' \
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
# print raw response if filter fails
if [ -z "$cmd" ] || [ "$cmd" = "null" ]; then
printf 'No command found. Raw response:\n%s\n' "$resp" >&2
set +f; return 1
fi
# print and append command to history
printf '%s\n' "$cmd"
history -s "$cmd"
set +f # set globbing
}