openai-cli

repository·main·Indexed 42 days ago

https://github.com/peterdemin/openai-cli

A 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.

Tokens
1.8K
Snippets
12
Records
13
Agent score
51%

What's inside openai-cli

  1. Authenticate with OpenAI API

    main

    The OpenAI API requires an authentication token. You can provide the token to the CLI using one of two methods:

    1. Command-line argument: Use the -t or --token flag.
    2. Environment variable: Set the 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' -
  2. Configure an alternative API URL

    main

    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'
  3. Configure OpenAI API credentials via environment variables

    main

    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"
  4. Use the `complete` command

    main

    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 -
  5. Use the `repl` command for interactive mode

    main

    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: ^C
    openai repl
  6. Generate a response with `generate_response()`

    main

    Use 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)
  7. Handle `OpenAIError` exceptions

    main

    The openai_cli package uses a custom OpenAIError exception to signal failures related to authentication or API communication.

    Common causes for this error include:

    • Missing OPENAI_API_KEY environment variable.
    • Network issues or request failures during the API call.

    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}")
  8. Parameters for `generate_response()`

    main

    The generate_response function accepts the following arguments:

    ArgumentTypeDefaultDescription
    promptstrRequiredThe user prompt to generate a response for.
    conversation_historyOptional[List[Dict[str, str]]]NoneA list of previous messages in the format [{"role": "...", "content": "..."}, ...]
    modelstrDEFAULT_MODELThe OpenAI model identifier to use.
    max_tokensintMAX_TOKENSThe maximum number of tokens to generate in the response.
    temperaturefloatTEMPERATUREControls randomness (higher values make output more random).
    system_messagestrSYSTEM_MESSAGEThe system message used to set the context for the assistant.
  9. Global CLI options for openai-cli

    main

    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 repl
  10. Get OpenAI completion from a file using `complete`

    main

    The 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