diff --git a/pilot/helpers/Debugger.py b/pilot/helpers/Debugger.py index 76a2328107..6d101a7d8a 100644 --- a/pilot/helpers/Debugger.py +++ b/pilot/helpers/Debugger.py @@ -47,7 +47,7 @@ class Debugger: if ask_before_debug or i > 0: print('yes/no', type='button') - answer = ask_user(self.agent.project, 'Can I start debugging this issue?', require_some_input=False) + answer = ask_user(self.agent.project, 'Can I start debugging this issue [Y/n/error details]?', require_some_input=False) if answer.lower() in NEGATIVE_ANSWERS: return True if answer and answer.lower() not in AFFIRMATIVE_ANSWERS: diff --git a/pilot/main.py b/pilot/main.py index 7b64f63cd3..8fe3a2bca0 100644 --- a/pilot/main.py +++ b/pilot/main.py @@ -46,7 +46,6 @@ if __name__ == "__main__": builtins.print, ipc_client_instance = get_custom_print(args) - if '--api-key' in args: os.environ["OPENAI_API_KEY"] = args['--api-key'] if '--get-created-apps-with-steps' in args: @@ -76,10 +75,14 @@ if __name__ == "__main__": # TODO get checkpoint from database and fill the project with it project = Project(args, ipc_client_instance=ipc_client_instance) + if project.check_ipc(): + telemetry.set("is_extension", True) + project.start() project.finish() telemetry.set("end_result", "success") - except Exception: + except Exception as err: + telemetry.record_crash(err) print(color_red('---------- GPT PILOT EXITING WITH ERROR ----------')) traceback.print_exc() print(color_red('--------------------------------------------------')) diff --git a/pilot/prompts/dev_ops/debug.prompt b/pilot/prompts/dev_ops/debug.prompt index a3c97a02db..48f84b7d6e 100644 --- a/pilot/prompts/dev_ops/debug.prompt +++ b/pilot/prompts/dev_ops/debug.prompt @@ -3,12 +3,11 @@ You wanted me to check this - `{{ issue_description }}` but there was a problem {%- else -%} Ok, we need to debug this issue {%- endif -%} -{% if command %} and we need to be able to execute `{{ command }}` successfully. {% else %}. -Here is a brief explanation of what's happening: +{% if command %} and we need to be able to execute `{{ command }}` successfully. {% endif %}. +{% if user_input %}Here is a brief explanation of what's happening: ``` {{ user_input }} -``` -{% endif -%} +```{% endif -%} {{ context }} I want you to create a list of steps that are needed to debug this issue. diff --git a/pilot/test/utils/test_settings.py b/pilot/test/utils/test_settings.py index 780d11ca13..d356a1dc6c 100644 --- a/pilot/test/utils/test_settings.py +++ b/pilot/test/utils/test_settings.py @@ -143,7 +143,7 @@ def test_get_git_commit(): def test_get_package_version(): - assert get_package_version() == "0.0.0" + assert get_package_version().startswith("0.0.") def test_get_version(): @@ -155,4 +155,4 @@ def test_get_version(): except Exception: commit_suffix = "" - assert get_version() == "0.0.0" + commit_suffix + assert get_version().endswith(commit_suffix) diff --git a/pilot/test/utils/test_telemetry.py b/pilot/test/utils/test_telemetry.py index a348bc6ad0..0bacaa8d9a 100644 --- a/pilot/test/utils/test_telemetry.py +++ b/pilot/test/utils/test_telemetry.py @@ -320,3 +320,24 @@ def test_send_clears_data_after_sending(mock_settings, _mock_post): telemetry.send() assert telemetry.data["model"] is None + + +@patch("utils.telemetry.settings") +def test_record_crash(mock_settings): + mock_settings.telemetry = { + "id": "test-id", + "endpoint": "test-endpoint", + "enabled": True, + } + + telemetry = Telemetry() + try: + raise ValueError("test error") + except Exception as err: + telemetry.record_crash(err) + + diag = telemetry.data["crash_diagnostics"] + assert diag["exception_class"] == "ValueError" + assert diag["exception_message"] == "test error" + assert diag["frames"][0]["file"] == "pilot/test/utils/test_telemetry.py" + assert "ValueError: test error" in diag["stack_trace"] diff --git a/pilot/utils/exit.py b/pilot/utils/exit.py index b6d259ac9d..7aad7f109f 100644 --- a/pilot/utils/exit.py +++ b/pilot/utils/exit.py @@ -67,6 +67,8 @@ def ask_to_store_prompt(project, path_id): response.raise_for_status() except requests.RequestException as err: print(f"Failed to store prompt: {err}") + except KeyboardInterrupt: + pass def ask_user_feedback(project, path_id, ask_feedback): @@ -79,18 +81,18 @@ def ask_user_feedback(project, path_id, ask_feedback): send_feedback(feedback, path_id) -def ask_user_email(project, path_id, ask_feedback): - if not ask_feedback: - return False - +def ask_user_email(project): question = ( "How did GPT Pilot do? We'd love to talk with you and hear your thoughts. " "If you'd like to be contacted by us, please provide your email address, or just press ENTER to exit:" ) - feedback = styled_text(project, question, ignore_user_input_count=True) - if feedback: # only send if user provided feedback - telemetry.set("user_contact", feedback) - return True + try: + feedback = styled_text(project, question, ignore_user_input_count=True) + if feedback: # only send if user provided feedback + telemetry.set("user_contact", feedback) + return True + except KeyboardInterrupt: + pass return False def exit_gpt_pilot(project, ask_feedback=True): @@ -99,9 +101,9 @@ def exit_gpt_pilot(project, ask_feedback=True): send_telemetry(path_id) - ask_to_store_prompt(project, path_id) - - ask_user_email(project, path_id, ask_feedback) + if ask_feedback: + ask_to_store_prompt(project, path_id) + ask_user_email(project) # TODO: Turned off for now because we're asking for email, and we don't want to # annoy people. diff --git a/pilot/utils/llm_connection.py b/pilot/utils/llm_connection.py index e2d894e5a0..f62238a4e9 100644 --- a/pilot/utils/llm_connection.py +++ b/pilot/utils/llm_connection.py @@ -20,39 +20,40 @@ from utils.questionary import styled_text from .telemetry import telemetry +tokenizer = tiktoken.get_encoding("cl100k_base") + + def get_tokens_in_messages(messages: List[str]) -> int: - tokenizer = tiktoken.get_encoding("cl100k_base") # GPT-4 tokenizer tokenized_messages = [tokenizer.encode(message['content']) for message in messages] return sum(len(tokens) for tokens in tokenized_messages) +# TODO: not used anywhere def num_tokens_from_functions(functions): """Return the number of tokens used by a list of functions.""" - encoding = tiktoken.get_encoding("cl100k_base") - num_tokens = 0 for function in functions: - function_tokens = len(encoding.encode(function['name'])) - function_tokens += len(encoding.encode(function['description'])) + function_tokens = len(tokenizer.encode(function['name'])) + function_tokens += len(tokenizer.encode(function['description'])) if 'parameters' in function: parameters = function['parameters'] if 'properties' in parameters: for propertiesKey in parameters['properties']: - function_tokens += len(encoding.encode(propertiesKey)) + function_tokens += len(tokenizer.encode(propertiesKey)) v = parameters['properties'][propertiesKey] for field in v: if field == 'type': function_tokens += 2 - function_tokens += len(encoding.encode(v['type'])) + function_tokens += len(tokenizer.encode(v['type'])) elif field == 'description': function_tokens += 2 - function_tokens += len(encoding.encode(v['description'])) + function_tokens += len(tokenizer.encode(v['description'])) elif field == 'enum': function_tokens -= 3 for o in v['enum']: function_tokens += 3 - function_tokens += len(encoding.encode(o)) + function_tokens += len(tokenizer.encode(o)) function_tokens += 11 num_tokens += function_tokens @@ -305,9 +306,10 @@ def stream_gpt_completion(data, req_type, project): model = os.getenv('MODEL_NAME', 'gpt-4') endpoint = os.getenv('ENDPOINT') - # This will be set many times but we don't care, as there are no side-effects to it. + # Model will be set many times but we don't care, as there are no side-effects to it. telemetry.set("model", model) telemetry.inc("num_llm_requests") + telemetry.inc("num_llm_tokens", get_tokens_in_messages(data['messages'])) logger.info(f'> Request model: {model}') if logger.isEnabledFor(logging.DEBUG): diff --git a/pilot/utils/settings.py b/pilot/utils/settings.py index c5ee61c84b..5c9390f50a 100644 --- a/pilot/utils/settings.py +++ b/pilot/utils/settings.py @@ -1,3 +1,4 @@ +import ast import json from logging import getLogger from os import getenv, makedirs @@ -295,9 +296,29 @@ def get_package_version() -> str: Note: until we have the packaging set up, this always returns "0.0.0". - :return: package version as defined in setup.py or pyproject.toml + :return: package version as defined in setup.py """ - return "0.0.0" + UNKNOWN = "0.0.0" + + setup_file = Path(__file__).parent.parent.parent / "setup.py" + if not setup_file.is_file(): + return UNKNOWN + + try: + with open(setup_file, "r", encoding="utf-8") as fp: + code = ast.parse(fp.read(), filename="setup.py") + for node in code.body: + if ( + isinstance(node, ast.Assign) + and len(node.targets) == 1 + and isinstance(node.targets[0], ast.Name) + and node.targets[0].id == "VERSION" + and isinstance(node.value, ast.Constant) + ): + return str(node.value.value) + except: # noqa + return UNKNOWN + def get_version() -> str: diff --git a/pilot/utils/telemetry.py b/pilot/utils/telemetry.py index a42afa34db..0967e7a583 100644 --- a/pilot/utils/telemetry.py +++ b/pilot/utils/telemetry.py @@ -1,6 +1,8 @@ from logging import getLogger +from pathlib import Path import sys import time +import traceback from typing import Any from uuid import uuid4 @@ -45,6 +47,7 @@ class Telemetry: """ DEFAULT_ENDPOINT = "https://api.pythagora.io/telemetry" + MAX_CRASH_FRAMES = 3 def __init__(self): self.enabled = False @@ -74,6 +77,8 @@ class Telemetry: "python_version": sys.version, # GPT Pilot version "pilot_version": version, + # Is extension used + "is_extension": False, # LLM used "model": None, # Initial prompt @@ -98,6 +103,8 @@ class Telemetry: "user_feedback": None, # Optional user contact email "user_contact": None, + # If GPT Pilot crashes, record diagnostics + "crash_diagnostics": None, } if sys.platform == "linux": try: @@ -194,7 +201,49 @@ class Telemetry: return self.end_time = time.time() - self.data["elapsed_time"] = self.end_time - self.start_time + self.data["elapsed_time"] = int(self.end_time - self.start_time) + + def record_crash( + self, + exception: Exception, + ): + """ + Record crash diagnostics. + + :param error: exception that caused the crash + + Records the following crash diagnostics data: + * full stack trace + * exception (class name and message) + * file:line for the last (innermost) 3 frames of the stack trace + """ + if not self.enabled: + return + + root_dir = Path(__file__).parent.parent.parent + stack_trace = traceback.format_exc() + exception_class_name = exception.__class__.__name__ + exception_message = str(exception) + + tb = exception.__traceback__ + frames = [] + while tb is not None: + frame = tb.tb_frame + file_path = Path(frame.f_code.co_filename).absolute().relative_to(root_dir).as_posix() + frame_info = { + "file": file_path, + "line": tb.tb_lineno + } + frames.append(frame_info) + tb = tb.tb_next + + frames.reverse() + self.data["crash_diagnostics"] = { + "stack_trace": stack_trace, + "exception_class": exception_class_name, + "exception_message": exception_message, + "frames": frames[:self.MAX_CRASH_FRAMES], + } def send(self, event:str = "pilot-telemetry"): """ diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000..b97383c047 --- /dev/null +++ b/setup.py @@ -0,0 +1,26 @@ +from setuptools import setup + +VERSION = "0.0.1" + +requirements = open("requirements.txt").readlines() + +if __name__ == "__main__": + setup( + name='gpt-pilot', + version=VERSION, + packages=['pilot'], + url='https://www.pythagora.ai', + license='MIT', + author_email='info@pythagora.ai', + description='GPT Pilot - an AI developer that works with you to build complex projects', + long_description=open('README.md').read(), + long_description_content_type='text/markdown', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3', + ], + install_requires=requirements, + python_requires='>=3.9', + )