Skip to content

Instantly share code, notes, and snippets.

@ftk
Created August 20, 2025 11:00
Show Gist options
  • Save ftk/c2ea3d25530d035da4ecc5bbf9a5bf32 to your computer and use it in GitHub Desktop.
Save ftk/c2ea3d25530d035da4ecc5bbf9a5bf32 to your computer and use it in GitHub Desktop.
Simple script to call OpenAI compatible endpoint with specified messages
#!/bin/bash
## Calls OpenAI v1 chat compatible endpoint with specified messages. Each passed argument is 1 message.
## Environment variables to set: OPENAI_API_KEY, optionally: OPENAI_API_BASE, OPENAI_MODEL, PROMPT
## Please note that your API key would be visible in curl aguments in the process list.
##
## Usage: ./llm.sh [-v] [-s "system prompt"] "message 1"...
## Example: ./llm.sh "count the number of lines in:" "$(cat file.txt)"
## --verbose|-v: debug the LLM call, prints input and output
set -euo pipefail
[[ $# -ge 1 && $1 == --help ]] && exec sed -n 's/^## //p' -- "$0"
[[ $# -ge 1 && ( $1 == --verbose || $1 == -v ) ]] && set -x && VERBOSE="--trace-ascii /dev/stderr" && shift 1
# check for system prompt
if [[ $# -ge 2 && ( $1 == -s || $1 == --system) ]]
then
PROMPT="$2"
shift 2
fi
if [[ -v PROMPT ]]
then
jq -n --arg model "${OPENAI_MODEL-gpt-5}" --arg system "$PROMPT" '{"model": $model, messages: [{role:"system", content: $system}, ($ARGS.positional.[] | {role:"user", content: .}) ]}' --args -- "$@"
else
jq -n --arg model "${OPENAI_MODEL-gpt-5}" '{model: $model, messages: [$ARGS.positional.[]| {role:"user", content: .} ]}' --args -- "$@"
fi | \
curl --compressed --no-progress-meter -X POST --fail-with-body ${VERBOSE-} \
"${OPENAI_API_BASE-https://openai.com/v1}/chat/completions" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- | \
jq -r '.choices[0].message.content'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment