quick openai call from the terminal

Summary

  • Create an “ai” executable – allow “ai <query>” in the command line
  • Create an “aiv” executable – this uses vim

How do create “ai” executable

  • create an “~/scripts/ai” python executable
  • chmod +x ~/scripts/ai
  • add “~/scripts” to path
  • try calling “ai test”
Python
vim ~/scripts/ai
# copy code from below

chmod +x ~/scripts/ai

echo "export PATH="$HOME/scripts:$PATH" >> ~/.zshrc

exec zsh
Python
#!/usr/bin/env python3
import os
import sys
import json
import requests

api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    print("Error: OPENAI_API_KEY not set.")
    sys.exit(1)

# Read from stdin or CLI args
if not sys.stdin.isatty():
    prompt = sys.stdin.read()
else:
    prompt = " ".join(sys.argv[1:])

if not prompt.strip():
    print("Error: empty prompt.")
    sys.exit(1)

payload = {
    "model": "gpt-4-turbo",
    "messages": [{"role": "user", "content": prompt}]
}

response = requests.post(
    "https://api.openai.com/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    },
    json=payload
)

if response.status_code == 200:
    print(response.json()['choices'][0]['message']['content'])
else:
    print(f"Error: {response.status_code}")
    print(response.text)

You use vim.

How do create “aiv” executable.
Same steps as above.

Python
#!/usr/bin/env python3
import os
import subprocess
import tempfile
import requests
import json

# Get API key
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    print("Error: OPENAI_API_KEY not set.")
    exit(1)

# Create a temp file and open it in $EDITOR (default to vim)
with tempfile.NamedTemporaryFile(suffix=".txt", mode="r+", delete=False) as tmp:
    tmp_path = tmp.name

editor = os.environ.get("EDITOR", "vim")
subprocess.run([editor, tmp_path])

# Read prompt
with open(tmp_path, "r") as f:
    prompt = f.read().strip()

# Clean up
os.remove(tmp_path)

# Exit early if prompt is empty
if not prompt:
    print("Prompt was empty or cancelled.")
    exit(0)

# Build payload
payload = {
    "model": "gpt-4-turbo",
    "messages": [{"role": "user", "content": prompt}]
}

# Send request
response = requests.post(
    "https://api.openai.com/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    },
    json=payload
)

# Print result
if response.status_code == 200:
    print(response.json()['choices'][0]['message']['content'])
else:
    print(f"Error: {response.status_code}")
    print(response.text)