Skip to content

Instantly share code, notes, and snippets.

@zvchei
Last active April 7, 2025 10:55
Show Gist options
  • Save zvchei/9904fd29702c6ab1e3c7f6353b824c17 to your computer and use it in GitHub Desktop.
Save zvchei/9904fd29702c6ab1e3c7f6353b824c17 to your computer and use it in GitHub Desktop.
#!/bin/bash
# MIT No Attribution
#
# Copyright (c) 2025 zvchei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Configuration
SERVICE_NAME="gemini"
KEY_ATTRIBUTE="api-key"
PREDEFINED_PROMPT="Answer the following question directly and provide the single best answer."
# Functions
get_api_key() {
API_KEY=$(secret-tool lookup "$SERVICE_NAME" "$KEY_ATTRIBUTE")
if [[ -z "$API_KEY" ]]; then
echo "Gemini API key not found in the keyring." >&2
echo "Please enter your Gemini API key." >&2
if secret-tool store --label='Gemini API Key' "$SERVICE_NAME" "$KEY_ATTRIBUTE"; then
echo "Gemini API key stored successfully in the keyring." >&2
API_KEY=$(secret-tool lookup "$SERVICE_NAME" "$KEY_ATTRIBUTE")
else
echo "Failed to store the Gemini API key." >&2
exit 1
fi
fi
echo "$API_KEY"
}
check_dependencies() {
DEPENDENCIES=("jq" "secret-tool")
MISSING_DEPENDENCIES=()
for DEP in "${DEPENDENCIES[@]}"; do
if ! command -v "$DEP" &>/dev/null; then
MISSING_DEPENDENCIES+=("$DEP")
fi
done
if [ ${#MISSING_DEPENDENCIES[@]} -ne 0 ]; then
echo "Error: The following dependencies are missing: ${MISSING_DEPENDENCIES[*]}" >&2
echo "Please install them using your system's package manager." >&2
echo "Example: sudo apt-get install ${MISSING_DEPENDENCIES[*]}" >&2
exit 1
fi
}
# Main
check_dependencies
API_KEY=$(get_api_key)
API_URL="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" # Gemini 2.0 Flash
PROMPT="$PREDEFINED_PROMPT $@"
DATA=$(cat <<EOF
{
"contents": {
"parts": [
{
"text": "$PROMPT"
}
]
}
}
EOF
)
RESPONSE=$(
curl -s -X POST \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $API_KEY" \
-d "$DATA" \
"$API_URL"
)
RESULT=$(echo "$RESPONSE" | jq -r '.candidates[0].content.parts[0].text')
echo "$RESULT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment