Skip to content

Commit

Permalink
Added: limited usage data with usage_stats_today() (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
signebedi committed Apr 6, 2023
1 parent da02922 commit 57a2b51
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 21 deletions.
27 changes: 27 additions & 0 deletions gptty/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ async def chat_async_wrapper(config_path:str, verbose:bool):
# create the output file if it doesn't exist
with open (configs['output_file'], 'a'): pass

# Authenticate with OpenAI using your API key
# click.echo (configs['api_key'])
if configs['api_key'].rstrip('\n') == "":
click.echo(f"{RED}FAILED to initialize connection to OpenAI. Have you added an API token? See gptty docs <https://github.com/signebedi/gptty#configuration> or <https://platform.openai.com/account/api-keys> for more information.")
return

# Run the main function
# create_chat_room(configs=configs, config_path=config_path)
# asyncio.run(create_chat_room(configs=configs, config_path=config_path))
Expand All @@ -152,16 +158,32 @@ def query(config_path:str, additional_context:str, question:str, tag:str, verbos


async def query_async_wrapper(config_path:str, question:str, tag:str, additional_context:str, verbose:bool, json:bool, quiet:bool):

if not os.path.exists(config_path):
click.echo(f"{RED}FAILED to access app config file at {config_path}. Are you sure this is a valid config file? Run `gptty chat --help` for more information.")
return

# load the app configs
configs = get_config_data(config_file=config_path)

# Here, we verify that we have a wifi connection and if not, exit
if not has_internet_connection(configs['verify_internet_endpoint']):
click.echo(f"{RED}FAILED to verify connection at {configs['verify_internet_endpoint']}. Are you sure you are connected to the internet?")
return

# create the output file if it doesn't exist
with open (configs['output_file'], 'a'): pass

# Authenticate with OpenAI using your API key
# click.echo (configs['api_key'])
if configs['api_key'].rstrip('\n') == "":
click.echo(f"{RED}FAILED to initialize connection to OpenAI. Have you added an API token? See gptty docs <https://github.com/signebedi/gptty#configuration> or <https://platform.openai.com/account/api-keys> for more information.")
return

if len(questions) < 1 or not isinstance(questions, tuple):
click.echo(f"{RED}FAILED to query ChatGPT. Did you forget to ask a question? Run `gptty chat --help` for more information.")
return

await run_query(questions=question, tag=tag, configs=configs, additional_context=additional_context, config_path=config_path, verbose=verbose, return_json=json, quiet=quiet)


Expand All @@ -177,6 +199,11 @@ def log(config_path):
# create the output file if it doesn't exist
with open (configs['output_file'], 'a'): pass

if not os.path.exists(config_path):
click.echo(f"{RED}FAILED to access app config file at {config_path}. Are you sure this is a valid config file? Run `gptty chat --help` for more information.")
return


df = return_log_as_df(configs)

click.echo(df)
Expand Down
38 changes: 17 additions & 21 deletions gptty/gptty.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@
`[a:b] what is the meaning of life` - pass context positionally
"""


def usage_stats_today():

r = openai.api_requestor.APIRequestor()
resp = r.request("GET", f'/usage?date={datetime.now().strftime("%Y-%m-%d")}')
resp_object = resp[0].data

requests_today = resp_object['data'][0]['n_requests'] # num requests
query_tokens_today = resp_object['data'][0]['n_context_tokens_total'] # query tokens
response_tokens_today = resp_object['data'][0]['n_generated_tokens_total'] # response tokens

return requests_today, query_tokens_today, response_tokens_today

## VALIDATE MODELS - these functions are use to validate the model passed by the user and raises an exception if
## the model does not exist.
def get_available_models():
Expand Down Expand Up @@ -187,11 +200,6 @@ async def create_chat_room(configs=get_config_data(), log_responses:bool=True, c
- None
"""

# Authenticate with OpenAI using your API key
# click.echo (configs['api_key'])
if configs['api_key'].rstrip('\n') == "":
click.echo(f"{RED}FAILED to initialize connection to OpenAI. Have you added an API token? See gptty docs <https://github.com/signebedi/gptty#configuration> or <https://platform.openai.com/account/api-keys> for more information.")
return

# here we add a pandas df reference object, see
# https://github.com/signebedi/gptty/issues/15
Expand All @@ -202,7 +210,6 @@ async def create_chat_room(configs=get_config_data(), log_responses:bool=True, c
df = pd.DataFrame(columns=['timestamp','tag','question','response'])

try:

openai.api_key = configs['api_key'].rstrip('\n')
except:
click.echo(f"{RED}FAILED to initialize connection to OpenAI. Have you added an API token? See gptty docs <https://github.com/signebedi/gptty#configuration> or <https://platform.openai.com/account/api-keys> for more information.")
Expand All @@ -228,9 +235,11 @@ async def create_chat_room(configs=get_config_data(), log_responses:bool=True, c
# Get user input
try:

usage = usage_stats_today() if verbose else ""

with patch_stdout():
i = await session.prompt_async(ANSI(f"{CYAN}> "), style=Style.from_dict({'': 'ansicyan'}))
print(f"{ERASE_LINE}{MOVE_CURSOR_UP}{GREY}> {i}\n", end="")
i = await session.prompt_async(ANSI(f"{CYAN}{usage}> "), style=Style.from_dict({'': 'ansicyan'}))
print(f"{ERASE_LINE}{MOVE_CURSOR_UP}{GREY}{usage}> {i}\n", end="")

# i = await ainput(f"{CYAN}> ")
tag,question = get_tag_from_text(i)
Expand Down Expand Up @@ -330,19 +339,6 @@ async def run_query(questions:list, tag:str, configs=get_config_data(), addition
if return_json is False and quiet is True, returns None
"""

if not os.path.exists(config_path):
click.echo(f"{RED}FAILED to access app config file at {config_path}. Are you sure this is a valid config file? Run `gptty chat --help` for more information.")
return

# Authenticate with OpenAI using your API key
# click.echo (configs['api_key'])
if configs['api_key'].rstrip('\n') == "":
click.echo(f"{RED}FAILED to initialize connection to OpenAI. Have you added an API token? See gptty docs <https://github.com/signebedi/gptty#configuration> or <https://platform.openai.com/account/api-keys> for more information.")
return

if len(questions) < 1 or not isinstance(questions, tuple):
click.echo(f"{RED}FAILED to query ChatGPT. Did you forget to ask a question? Run `gptty chat --help` for more information.")
return

# here we add a pandas df reference object, see
# https://github.com/signebedi/gptty/issues/15
Expand Down

0 comments on commit 57a2b51

Please sign in to comment.