From 52506a9621516d884223e0945c663b262b3e0466 Mon Sep 17 00:00:00 2001 From: Nakul Gupta Date: Wed, 6 Sep 2023 16:49:05 +0530 Subject: [PATCH] Error handling (#104) --- examples/openai-bot/main.py | 28 +++++++++++++++++++++++----- textbase/textbase_cli.py | 17 +++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/examples/openai-bot/main.py b/examples/openai-bot/main.py index ebc25837..b0fa48ca 100644 --- a/examples/openai-bot/main.py +++ b/examples/openai-bot/main.py @@ -1,6 +1,7 @@ from textbase import bot, Message from textbase.models import OpenAI from typing import List +import click # Load your OpenAI API key OpenAI.api_key = "" @@ -15,11 +16,28 @@ def on_message(message_history: List[Message], state: dict = None): # Generate GPT-3.5 Turbo response - bot_response = OpenAI.generate( - system_prompt=SYSTEM_PROMPT, - message_history=message_history, # Assuming history is the list of user messages - model="gpt-3.5-turbo", - ) + try: + bot_response = OpenAI.generate( + system_prompt=SYSTEM_PROMPT, + message_history=message_history, # Assuming history is the list of user messages + model="gpt-3.5-turbo", + ) + except Exception as e : + click.secho(str(e), fg='red') + return { + "status_code": 500, + "response": { + "data": { + "messages": [], + "state": state + }, + "errors": [ + { + "message": str(e) + } + ] + } + } response = { "data": { diff --git a/textbase/textbase_cli.py b/textbase/textbase_cli.py index 1f9381db..e0651009 100644 --- a/textbase/textbase_cli.py +++ b/textbase/textbase_cli.py @@ -1,3 +1,4 @@ +import inspect import click import requests import subprocess @@ -20,6 +21,22 @@ def cli(): @click.option("--path", prompt="Path to the main.py file", required=True) @click.option("--port", prompt="Enter port", required=False, default=8080) def test(path, port): + # Check if the file exists + if not os.path.exists(path): + click.secho("Incorrect main.py path.", fg='red') + return + + # Load the module dynamically + spec = importlib.util.spec_from_file_location("module.name", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + # Check if 'on_message' exists and is a function + if "on_message" in dir(module) and inspect.isfunction(getattr(module, "on_message")): + click.secho("The function 'on_message' exists in the specified main.py file.", fg='yellow') + else: + click.secho("The function 'on_message' does not exist in the specified main.py file.", fg='red') + return server_path = importlib.resources.files('textbase').joinpath('utils', 'server.py') try: if os.name == 'posix':