Git Product home page Git Product logo

openai-cli's Introduction

OpenAI command-line client

Installation

To install OpenAI CLI in Python virtual environment, run:

pip install openai-cli

Token authentication

OpenAI API requires authentication token, which can be obtained on this page: https://beta.openai.com/account/api-keys

Provide token to the CLI either through a command-line argument (-t/--token <TOKEN>) or through an environment variable (OPENAI_API_TOKEN).

Usage

Currently only text completion API is supported.

Example usage:

$ echo "Are cats faster than dogs?" | openai complete -
It depends on the breed of the cat and dog. Generally,
cats are faster than dogs over short distances,
but dogs are better at sustained running.

Interactive mode supported (Press Ctrl+C to exit):

$ openai repl
Prompt: Can generative AI replace humans?

No, generative AI cannot replace humans.
While generative AI can be used to automate certain tasks,
it cannot replace the creativity, intuition, and problem-solving
skills that humans possess.
Generative AI can be used to supplement human efforts,
but it cannot replace them.

Prompt: ^C

Run without arguments to get a short help message:

$ openai
Usage: openai [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  complete  Return OpenAI completion for a prompt from SOURCE.
  repl      Start interactive shell session for OpenAI completion API.

Build a standalone binary using pex and move it into PATH:

$ make openai && mv openai ~/bin/
$ openai repl
Prompt:

Alternative API URL

CLI invokes https://api.openai.com/v1/completions by default. To override the endpoint URL, set OPENAI_API_URL environment variable.

Example usage

Here's an example usage scenario, where we first create a Python module with a Fibonacci function implementation, and then generate a unit test for it:

$ mkdir examples
$ touch examples/__init__.py
$ echo "Write Python function to calculate Fibonacci numbers" | openai complete - | black - > examples/fib.py
$ (echo 'Write unit tests for this Python module named "fib":\n'; cat examples/fib.py) | openai complete - | black - > examples/test_fib.py
$ pytest -v examples/test_fib.py
============================== test session starts ==============================

examples/test_fib.py::TestFibonacci::test_eighth_fibonacci_number PASSED                                 [ 10%]
examples/test_fib.py::TestFibonacci::test_fifth_fibonacci_number PASSED                                  [ 20%]
examples/test_fib.py::TestFibonacci::test_first_fibonacci_number PASSED                                  [ 30%]
examples/test_fib.py::TestFibonacci::test_fourth_fibonacci_number PASSED                                 [ 40%]
examples/test_fib.py::TestFibonacci::test_negative_input PASSED                                          [ 50%]
examples/test_fib.py::TestFibonacci::test_ninth_fibonacci_number PASSED                                  [ 60%]
examples/test_fib.py::TestFibonacci::test_second_fibonacci_number PASSED                                 [ 70%]
examples/test_fib.py::TestFibonacci::test_seventh_fibonacci_number PASSED                                [ 80%]
examples/test_fib.py::TestFibonacci::test_sixth_fibonacci_number PASSED                                  [ 90%]
examples/test_fib.py::TestFibonacci::test_third_fibonacci_number PASSED                                  [100%]

=============================== 10 passed in 0.02s ==============================

$ cat examples/fib.py
def Fibonacci(n):
    if n < 0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n == 1:
        return 0
    # Second Fibonacci number is 1
    elif n == 2:
        return 1
    else:
        return Fibonacci(n - 1) + Fibonacci(n - 2)
$ cat examples/test_fib.py
import unittest
from .fib import Fibonacci


class TestFibonacci(unittest.TestCase):
    def test_negative_input(self):
        self.assertEqual(Fibonacci(-1), None)

    def test_first_fibonacci_number(self):
        self.assertEqual(Fibonacci(1), 0)

    def test_second_fibonacci_number(self):
        self.assertEqual(Fibonacci(2), 1)

    def test_third_fibonacci_number(self):
        self.assertEqual(Fibonacci(3), 1)

    def test_fourth_fibonacci_number(self):
        self.assertEqual(Fibonacci(4), 2)

    def test_fifth_fibonacci_number(self):
        self.assertEqual(Fibonacci(5), 3)

    def test_sixth_fibonacci_number(self):
        self.assertEqual(Fibonacci(6), 5)

    def test_seventh_fibonacci_number(self):
        self.assertEqual(Fibonacci(7), 8)

    def test_eighth_fibonacci_number(self):
        self.assertEqual(Fibonacci(8), 13)

    def test_ninth_fibonacci_number(self):
        self.assertEqual(Fibonacci(9), 21)


if __name__ == "__main__":
    unittest.main()
$ (echo "Add type annotations for this Python code"; cat examples/fib.py) | openai complete - | black - | tee tmp && mv tmp examples/fib.py
def Fibonacci(n: int) -> int:
    if n < 0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n == 1:
        return 0
    # Second Fibonacci number is 1
    elif n == 2:
        return 1
    else:
        return Fibonacci(n - 1) + Fibonacci(n - 2)
$ mypy examples/fib.py
examples/fib.py:1: error: Missing return statement  [return]
Found 1 error in 1 file (checked 1 source file)
$ (echo "Fix mypy warnings in this Python code"; cat examples/fib.py; mypy examples/fib.py) | openai complete - | black - | tee tmp && mv tmp examples/fib.py
def Fibonacci(n: int) -> int:
    if n < 0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n == 1:
        return 0
    # Second Fibonacci number is 1
    elif n == 2:
        return 1
    else:
        return Fibonacci(n - 1) + Fibonacci(n - 2)
    return None  # Added return statement
$ mypy examples/fib.py
examples/fib.py:12: error: Incompatible return value type (got "None", expected "int")  [return-value]
Found 1 error in 1 file (checked 1 source file)
$ (echo "Fix mypy warnings in this Python code"; cat examples/fib.py; mypy examples/fib.py) | openai complete - | black - | tee tmp && mv tmp examples/fib.py
def Fibonacci(n: int) -> int:
    if n < 0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n == 1:
        return 0
    # Second Fibonacci number is 1
    elif n == 2:
        return 1
    else:
        return Fibonacci(n - 1) + Fibonacci(n - 2)
    return 0  # Changed return statement to return 0
$ mypy examples/fib.py
Success: no issues found in 1 source file
$ (echo "Rewrite these tests to use pytest.parametrized"; cat examples/test_fib.py) | openai complete - | black - | tee tmp && mv tmp examples/test_fib.py
import pytest
from .fib import Fibonacci


@pytest.mark.parametrize(
    "n, expected",
    [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (6, 5), (7, 8), (8, 13), (9, 21), (10, 34)],
)
def test_fibonacci(n, expected):
    assert Fibonacci(n) == expected

openai-cli's People

Contributors

abravalheri avatar azhx avatar bhrutledge avatar darkvertex avatar hugovk avatar jaraco avatar kolanich avatar peterdemin avatar unosd avatar webknjaz avatar wimglenn avatar zacharyburnett avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openai-cli's Issues

Missing token option

openai --token "sk-..."
Usage: openai [OPTIONS] COMMAND [ARGS]...
Try 'openai --help' for help.

Error: No such option: --token

openai -t "sk-..."
Usage: openai [OPTIONS] COMMAND [ARGS]...
Try 'openai --help' for help.

Error: No such option: --token

not accepting --token flag

I'm noting that the CLI requires the interface to be "openai repl -t KEY"
in the examples below, I tried "openai -t key repl" and it would fail uninformatively

% openai repl  
Usage: openai repl [OPTIONS]
Try 'openai repl --help' for help.

Error: Either --token option or OPENAI_API_TOKEN environment variable must be provided
% openai --token '<...>' repl
Usage: openai [OPTIONS] COMMAND [ARGS]...
Try 'openai --help' for help.

Error: No such option: --token

% openai -t '...' repl
Usage: openai [OPTIONS] COMMAND [ARGS]...
Try 'openai --help' for help.

Error: No such option: -t

404 Client Error: Not Found for url: https://api.openai.com/v1/completions

Python 3.11.6 (main, Nov 2 2023, 04:39:43) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin

~ » echo "Are cats faster than dogs?" | openai complete -                      yosef.yudilevich@IL-YosefY-2
Traceback (most recent call last):
  File "/opt/homebrew/bin/openai", line 8, in <module>
    sys.exit(cli())
             ^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
    return self.main(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1078, in main
    rv = self.invoke(ctx)
         ^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1688, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/click/core.py", line 783, in invoke
    return __callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/openai_cli/cli.py", line 24, in complete
    result = client.generate_response(prompt, model)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/lib/python3.11/site-packages/openai_cli/client.py", line 36, in generate_response
    response.raise_for_status()
  File "/opt/homebrew/lib/python3.11/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.openai.com/v1/completions

can you help please

401 Error using repl

➜  ~ openai repl --token <my api key>
Prompt: hello my name is
Traceback (most recent call last):
  File "/Users/mawagner/.pyenv/versions/3.9.4/bin/openai", line 8, in <module>
    sys.exit(cli())
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/openai_cli/cli.py", line 37, in repl
    print(client.generate_response(input("Prompt: "), model))
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/openai_cli/client.py", line 36, in generate_response
    response.raise_for_status()
  File "/Users/mawagner/.pyenv/versions/3.9.4/lib/python3.9/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.openai.com/v1/completions

Env token not recognized

mac

OPENAI_API_TOKEN=sk-...
openai repl
Usage: openai repl [OPTIONS]
Try 'openai repl --help' for help.

Error: Either --token option or OPENAI_API_TOKEN environment variable must be provided

openai.exe installed but commands missing.

I enter openai --help when none of the documented commands seemed to work. That gave:
openai --help
Usage: openai [OPTIONS] COMMAND [ARGS]...

Options:
--help Show this message and exit.

Commands:
complete Return OpenAI completion for a prompt from SOURCE.
repl Start interactive shell session for OpenAI completion API.

how do I get full functionality.

Unexpected exception

I did:

echo "do something" | openai complete -

and I got an error in models.py, line 1021, in my first time usage:

requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://api.openai.com/v1/completions

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.