Install the OpenAI CLI
mainTo install the OpenAI CLI in a Python virtual environment, use pip:
pip install openai-clirepository·main·Indexed 42 days ago
https://github.com/peterdemin/openai-cliA command-line interface for interacting with OpenAI's text completion API. It features a `complete` command for piped input or file-based prompts and a `repl` command for interactive conversational sessions. The tool supports configuration via environment variables such as OPENAI_API_KEY and OPENAI_API_URL, and provides global options for adjusting the model, max-tokens, and temperature.
To install the OpenAI CLI in a Python virtual environment, use pip:
pip install openai-cliThe OpenAI API requires an authentication token. You can provide the token to the CLI using one of two methods:
-t or --token flag.OPENAI_API_KEY environment variable.Tokens can be obtained from the OpenAI API keys page.
# Using an environment variable
export OPENAI_API_KEY='your-api-key-here'
# Using a command-line argument
openai complete -t 'your-api-key-here' -You can build a standalone binary using pex and then move it into your PATH for easier access.
make openai && mv openai ~/bin/
openai replmake openai && mv openai ~/bin/By default, the CLI invokes https://api.openai.com/v1/completions. To use a different endpoint (e.g., a proxy or a local model server), set the OPENAI_API_URL environment variable.
export OPENAI_API_URL='https://your-alternative-endpoint.com/v1'The openai-cli uses environment variables to manage authentication and endpoint configuration. You can set these variables in your shell to avoid passing them manually.
OPENAI_API_KEY: Your OpenAI API key.OPENAI_API_URL: The base URL for the Chat Completions API. If not set, it defaults to https://api.openai.com/v1/chat/completions.export OPENAI_API_KEY="your-api-key-here"
export OPENAI_API_URL="https://api.openai.com/v1/chat/completions"The complete command returns an OpenAI completion for a prompt provided from a source (typically stdin). Currently, only the text completion API is supported.
Example using a pipe:
echo "Are cats faster than dogs?" | openai complete -The repl command starts an interactive shell session for the OpenAI completion API. This allows you to enter multiple prompts sequentially without restarting the CLI. Press Ctrl+C to exit the session.
$ openai repl
Prompt: Can generative AI replace humans?
No, generative AI cannot replace humans...
Prompt: ^Copenai replUse generate_response() to send a prompt to the OpenAI API. This function handles session initialization, message construction (including system messages and conversation history), and response parsing.
By default, it uses values defined in the project configuration for model, max_tokens, temperature, and system_message.
from openai_cli.client import generate_response
# Basic usage
response = generate_response("Hello, how are you?")
print(response)
# Usage with conversation history and custom parameters
history = [
{"role": "user", "content": "My name is Alice"},
{"role": "assistant", "content": "Nice to meet you, Alice!"}
]
response = generate_response(
prompt="What is my name?",
conversation_history=history,
model="gpt-4",
temperature=0.7,
system_message="You are a helpful assistant."
)
print(response)The openai_cli package uses a custom OpenAIError exception to signal failures related to authentication or API communication.
Common causes for this error include:
OPENAI_API_KEY environment variable.When using generate_response(), you should wrap the call in a try-except block to handle these errors gracefully.
from openai_cli.client import generate_response, OpenAIError
try:
response = generate_response("Tell me a joke.")
except OpenAIError as e:
print(f"An error occurred: {e}")The generate_response function accepts the following arguments:
| Argument | Type | Default | Description |
|---|---|---|---|
prompt | str | Required | The user prompt to generate a response for. |
conversation_history | Optional[List[Dict[str, str]]] | None | A list of previous messages in the format [{"role": "...", "content": "..."}, ...] |
model | str | DEFAULT_MODEL | The OpenAI model identifier to use. |
max_tokens | int | MAX_TOKENS | The maximum number of tokens to generate in the response. |
temperature | float | TEMPERATURE | Controls randomness (higher values make output more random). |
system_message | str | SYSTEM_MESSAGE | The system message used to set the context for the assistant. |
The openai-cli provides several global options that can be applied to all commands. These options control the model, token limits, generation randomness, and authentication.
--model, -m: Specifies the OpenAI model to use. (Default: DEFAULT_MODEL)--max-tokens, -k: Sets the maximum number of tokens in the response. (Default: MAX_TOKENS)--temperature, -p: Sets the temperature for response generation. (Default: TEMPERATURE)--token, -t: Provides the OpenAI API token directly for the session.# Example of using global options with a command
openai-cli --model gpt-4 --temperature 0.7 replThe complete command reads a prompt from a specified file and returns the OpenAI completion. It maintains a conversation history within the scope of the command execution.
Usage:
openai-cli complete SOURCE
Where SOURCE is a path to a text file containing your prompt.
openai-cli complete prompt.txt