Skip to content

Instantly share code, notes, and snippets.

@izikeros
Last active July 4, 2023 03:27
Show Gist options
  • Save izikeros/dd253dcfd234f0c42d3d9a9ae323ede4 to your computer and use it in GitHub Desktop.
Save izikeros/dd253dcfd234f0c42d3d9a9ae323ede4 to your computer and use it in GitHub Desktop.
Bash script that calls the Azure OpenAI API to ask a question and returns the answer

ask_gpt.sh

A script to call the Azure OpenAI API and ask a question, returning the answer.

Description

ask_gpt.sh is a Bash script that interacts with the Azure OpenAI API to ask a question and retrieve the corresponding answer. It simplifies the process of making API calls and handling the JSON response.

Usage

./ask_gpt.sh "What is the meaning of life?"

Replace "What is the meaning of life?" with your desired question.

Requirements

  • The jq command line tool must be installed.
  • The following environment variables must be set:
    • AZURE_OPENAI_API_KEY: Azure OpenAI API key.
    • AZURE_OPENAI_ENDPOINT: Azure OpenAI endpoint.
    • OPENAI_API_VERSION: Azure OpenAI API version.
    • CHAT_DEPLOYMENT: Azure OpenAI deployment name.

Installation

  1. Clone the repository:

    git clone <repository_url>
  2. Change into the repository directory:

    cd ask-gpt
  3. Make the script executable:

    chmod +x ask_gpt.sh

Execution

Run the script with your desired question as an argument:

./ask_gpt.sh "What is the meaning of life?"

Output

The script sends a request to the Azure OpenAI API, passing the question as a user message. It then retrieves the answer from the API response and displays it in the console.

License

This project is licensed under the MIT License.

#!/usr/bin/env bash
#
# ask_gpt.sh
# Usage: ./ask_gpt.sh "What is the meaning of life?"
#
# Description: This script calls the Azure OpenAI API to ask a question and returns the answer.
#
# Arguments:
# - The question is passed as the first argument to the script.
#
# Requirements:
# - The jq command line tool must be installed.
# - The Azure OpenAI API key must be set in the AZURE_OPENAI_API_KEY environment variable.
# - The Azure OpenAI endpoint must be set in the AZURE_OPENAI_ENDPOINT environment variable.
# - The Azure OpenAI API version must be set in the OPENAI_API_VERSION environment variable.
# - The Azure OpenAI deployment name must be set in the CHAT_DEPLOYMENT environment variable.
# Make API call to Azure OpenAI API and print the answer
curl -s "$AZURE_OPENAI_ENDPOINT/openai/deployments/$CHAT_DEPLOYMENT/chat/completions?api-version=$OPENAI_API_VERSION" \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-d "{\"messages\":[{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},{\"role\": \"user\", \"content\": \"$1\"}]}" \
| jq '.choices | .[0] | .message | .content' \
| echo -e "$(cat -)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment