Skip to content

Commit 92b9af1

Browse files
committed
Added v 2.2.0, Support for saving/executing Commands/Script, Fix Logger Issues
1 parent 84abe8c commit 92b9af1

9 files changed

+212
-117
lines changed

Diff for: README.md

+13-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ Here are the available commands:
239239
- 🚪 `/list` - List all the _models/modes/language_ available.
240240
- 📝 `/version` - Display the version of the interpreter.
241241
- 🚪 `/exit` - Exit the interpreter.
242-
- 🐞 `/debug` - Debug the generated code for errors.
242+
- 🐞 `/fix` - Fix the generated code for errors.
243243
- 📜 `/log` - Toggle different modes of logging.
244244
-`/upgrade` - Upgrade the interpreter.
245245
- 📁 `/prompt` - Switch the prompt mode _File or Input_ modes.
@@ -324,6 +324,18 @@ If you're interested in contributing to **Code-Interpreter**, we'd love to have
324324
- **v2.1.4** - Added **GPT-4o** models they are most effecient and cost effective models from **OpenAI**
325325
- **v2.1.5** - Fixed OS type detection **Bug** for MacOS and feautre to open file with default editor.
326326

327+
# 🔥 **v2.2**
328+
- **Save/Execute**: Added support to **save and execute code, commands, and scripts** directly to external files.
329+
- **Updated Commands**:
330+
- Removed the `/debug` command and replaced it with the `/fix` command.
331+
- `/debug` command now handles application debugging and issue resolution effectively.
332+
- **Improved Logger**:
333+
- Fixed issues with logging to both **files and console** simultaneously.
334+
- **Dependency Management**:
335+
- Resolved pip package installation issues for smoother and more reliable setup.
336+
337+
---
338+
327339
## 📜 **License**
328340

329341
This project is licensed under the **MIT License**. For more details, please refer to the LICENSE file.

Diff for: interpreter.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
from libs.utility_manager import UtilityManager
2525

2626
# The main version of the interpreter.
27-
INTERPRETER_VERSION = "2.1.5"
27+
INTERPRETER_VERSION = "2.2.0"
28+
2829

2930
def main():
3031
parser = argparse.ArgumentParser(description='Code - Interpreter')

Diff for: libs/code_interpreter.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
class CodeInterpreter:
1818

1919
def __init__(self):
20-
self.logger = Logger.initialize_logger("logs/code-interpreter.log")
20+
self.logger = Logger.initialize("logs/code-interpreter.log")
2121

2222
def _execute_script(self, script: str, shell: str):
2323
stdout = stderr = None

Diff for: libs/gemini_vision.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
class GeminiVision:
77
def __init__(self, api_key=None) -> None:
8-
self.logger = Logger.initialize_logger('logs/vision_interpreter.log')
8+
self.logger = Logger.initialize('logs/vision_interpreter.log')
99
self.logger.info("Initializing Gemini Vision")
1010
self.api_key = api_key
1111

Diff for: libs/history_manager.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
class History:
88
def __init__(self, history_file: str):
99
self.history_file = history_file
10-
self.logger = Logger.initialize_logger("logs/interpreter.log")
10+
self.logger = Logger.initialize("logs/interpreter.log")
1111

1212
def save_history_json(self, task, mode, os_name, language, prompt, code_snippet, code_output, model_name):
1313
try:

Diff for: libs/interpreter_lib.py

+80-37
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import os
1515
import subprocess
1616
import time
17-
import litellm # Main libray for LLM's
17+
import litellm # Main libray for LLM's
1818
from typing import List
1919
from libs.code_interpreter import CodeInterpreter
2020
from libs.history_manager import History
@@ -25,6 +25,7 @@
2525
from dotenv import load_dotenv
2626
import shlex
2727
import shutil
28+
import logging
2829

2930
class Interpreter:
3031
logger = None
@@ -40,7 +41,7 @@ def __init__(self, args):
4041
self.code_interpreter = CodeInterpreter()
4142
self.package_manager = PackageManager()
4243
self.history_manager = History(self.history_file)
43-
self.logger = Logger.initialize_logger("logs/interpreter.log")
44+
self.logger = Logger.initialize("logs/interpreter.log")
4445
self.client = None
4546
self.config_values = None
4647
self.system_message = ""
@@ -188,7 +189,7 @@ def get_prompt(self, message: str, chat_history: List[dict]) -> str:
188189

189190
# Use the Messages API from Anthropic.
190191
if 'claude-3' in self.INTERPRETER_MODEL:
191-
messages=[
192+
messages = [
192193
{
193194
"role": "user",
194195
"content": [
@@ -212,15 +213,16 @@ def get_prompt(self, message: str, chat_history: List[dict]) -> str:
212213

213214
def execute_last_code(self, os_name):
214215
try:
215-
code_file,code_snippet = self.utility_manager.get_code_history(self.INTERPRETER_LANGUAGE)
216-
216+
code_file, code_snippet = self.utility_manager.get_output_history(mode=self.INTERPRETER_MODE, os_name=os_name, language=self.INTERPRETER_LANGUAGE)
217+
217218
# check if the code is empty
218-
if code_snippet is None:
219-
self.logger.error("Code history is empty.")
220-
print("Code history is empty. - Please use -s or --save_code to save the code.")
219+
if code_snippet is None or code_file is None:
220+
self.logger.error("Code history or file is empty.")
221+
display_markdown_message("Code history or file is empty. - Please use **-s** flag or **/save** command to save the code.")
221222
return
222223

223-
display_code(code_snippet)
224+
display_code(code_snippet) # Display the code first.
225+
224226
# Execute the code if the user has selected.
225227
code_output, code_error = self.execute_code(code_snippet, os_name)
226228
if code_output:
@@ -449,19 +451,19 @@ def get_mode_prompt(self, task, os_name):
449451

450452
def execute_code(self, extracted_code, os_name):
451453
# If the interpreter mode is Vision, do not execute the code.
452-
if self.INTERPRETER_MODE in ['vision','chat']:
454+
if self.INTERPRETER_MODE in ['vision', 'chat']:
453455
return None, None
454456

455457
execute = 'y' if self.EXECUTE_CODE else input("Execute the code? (Y/N): ")
456458
if execute.lower() == 'y':
457459
try:
458460
code_output, code_error = "", ""
459461
if self.SCRIPT_MODE:
460-
code_output, code_error = self.code_interpreter.execute_script(extracted_code, os_type=os_name)
462+
code_output, code_error = self.code_interpreter.execute_script(script=extracted_code, os_type=os_name)
461463
elif self.COMMAND_MODE:
462-
code_output, code_error = self.code_interpreter.execute_command(extracted_code)
464+
code_output, code_error = self.code_interpreter.execute_command(command=extracted_code)
463465
elif self.CODE_MODE:
464-
code_output, code_error = self.code_interpreter.execute_code(extracted_code, language=self.INTERPRETER_LANGUAGE)
466+
code_output, code_error = self.code_interpreter.execute_code(code=extracted_code, language=self.INTERPRETER_LANGUAGE)
465467
return code_output, code_error
466468
except Exception as exception:
467469
self.logger.error(f"Error occurred while executing code: {str(exception)}")
@@ -623,20 +625,21 @@ def interpreter_main(self, version):
623625
continue
624626

625627
# LOG - Command section.
626-
elif task.lower() == '/log':
627-
# Toggle the log level to Verbose/Silent.
628-
628+
elif task.lower() == '/debug':
629+
630+
# Toggle the log level to Debug/Silent.
629631
logger_mode = Logger.get_current_level()
630632
logger_mode = logger_mode.lower()
631-
632-
if logger_mode == 'debug':
633-
Logger.set_silent_mode()
634-
display_markdown_message("Logger mode changed to **Silent**.")
633+
print("Logger mode: {}".format(logger_mode))
634+
635+
if logger_mode == 'error':
636+
Logger.set_level_to_info()
637+
display_markdown_message("**Debug** mode **disabled**")
635638
else:
636-
Logger.set_verbose_mode()
637-
display_markdown_message("Logger mode changed to **Verbose**.")
639+
Logger.set_level_to_debug()
640+
display_markdown_message("**Debug** mode **enabled**")
638641
continue
639-
642+
640643
# LIST - Command section.
641644
elif task.lower() == '/list':
642645
# Get the models info
@@ -673,26 +676,66 @@ def interpreter_main(self, version):
673676

674677
# EXECUTE - Command section.
675678
elif task.lower() == '/execute':
679+
os_name = os_platform[0].lower()
676680
self.execute_last_code(os_name)
677681
continue
678682

679683
# SAVE - Command section.
680684
elif task.lower() == '/save':
681-
latest_code_extension = 'py' if self.INTERPRETER_LANGUAGE == 'python' else 'js'
682-
latest_code_name = f"output/code_{time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime())}." + latest_code_extension
685+
mode_type = self.INTERPRETER_MODE
686+
latest_code_extension: str = ""
687+
688+
# Get the OS platform.
689+
os_name = os_platform[0].lower()
690+
691+
# Set the script or command extension based on the OS platform and mode type
692+
extensions = {
693+
"script": {
694+
"darwin": ".applescript",
695+
"linux": ".sh",
696+
"windows": ".bat"
697+
},
698+
"command": {
699+
"darwin": ".sh",
700+
"linux": ".sh",
701+
"windows": ".bat"
702+
},
703+
"code": lambda lang: '.py' if lang == 'python' else '.js'
704+
}
705+
706+
lower_os_name = os_name.lower()
707+
if mode_type.lower() in extensions:
708+
if mode_type.lower() == "code":
709+
latest_code_extension = extensions["code"](self.INTERPRETER_LANGUAGE)
710+
else:
711+
for key in extensions[mode_type.lower()]:
712+
if key in lower_os_name:
713+
latest_code_extension = extensions[mode_type.lower()][key]
714+
break
715+
else:
716+
raise ValueError(f"Unsupported operating system: {os_name}")
717+
else:
718+
raise ValueError(f"Unsupported mode type: {mode_type}")
719+
720+
latest_code_name = f"output/{mode_type}_{time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime())}" + latest_code_extension
683721
latest_code = code_snippet
684722
self.code_interpreter.save_code(latest_code_name, latest_code)
685-
display_markdown_message(f"Code saved successfully to {latest_code_name}.")
723+
display_markdown_message(f"{mode_type.capitalize()} saved successfully to **{latest_code_name}**")
686724
continue
687725

688726
# EDIT - Command section.
689727
elif task.lower() == '/edit':
690-
code_file, code_snippet = self.utility_manager.get_code_history(self.INTERPRETER_LANGUAGE)
691-
692728
# Get the OS platform.
693-
os_platform = self.utility_manager.get_os_platform()
694729
os_name = os_platform[0].lower()
730+
731+
code_file, code_snippet = self.utility_manager.get_output_history(mode=self.INTERPRETER_MODE, os_name=os_name, language=self.INTERPRETER_LANGUAGE)
695732

733+
# check if the code is empty
734+
if code_snippet is None or code_file is None:
735+
self.logger.error("Code history or file is empty.")
736+
display_markdown_message("Code history or file is empty. - Please use **-s** flag or **/save** command to save the code.")
737+
continue
738+
696739
# Attempt to open with default editor.
697740
self.logger.info(f"Opening code in default editor for os '{os_platform}'")
698741
try:
@@ -714,8 +757,8 @@ def interpreter_main(self, version):
714757
self.logger.error("No suitable editor found.")
715758
continue
716759

717-
# DEBUG - Command section.
718-
elif task.lower() == '/debug':
760+
# FIX - Command section.
761+
elif task.lower() == '/fix':
719762

720763
if not code_error:
721764
code_error = code_output
@@ -724,12 +767,12 @@ def interpreter_main(self, version):
724767
display_markdown_message("Error: No error found in the code to fix.")
725768
continue
726769

727-
debug_prompt = f"Fix the errors in {self.INTERPRETER_LANGUAGE} language.\nCode is \n'{code_snippet}'\nAnd Error is \n'{code_error}'\n"
770+
fix_prompt = f"Fix the errors in {self.INTERPRETER_LANGUAGE} language.\nCode is \n'{code_snippet}'\nAnd Error is \n'{code_error}'\n"
728771
f"give me output only in code and no other text or explanation. And comment in code where you fixed the error.\n"
729772

730773
# Start the LLM Request.
731-
self.logger.info(f"Debug Prompt: {debug_prompt}")
732-
generated_output = self.generate_content(debug_prompt, self.history, config_values=self.config_values, image_file=extracted_file_name)
774+
self.logger.info(f"Fix Prompt: {fix_prompt}")
775+
generated_output = self.generate_content(fix_prompt, self.history, config_values=self.config_values, image_file=extracted_file_name)
733776

734777
# Extract the code from the generated output.
735778
self.logger.info(f"Generated output type {type(generated_output)}")
@@ -910,7 +953,7 @@ def interpreter_main(self, version):
910953
prompt += "\n" + "using Python use Pandas save the table in file called 'table.md'"
911954
elif self.INTERPRETER_LANGUAGE == 'javascript':
912955
prompt += "\n" + "using JavaScript use DataTables save the table in file called 'table.html'"
913-
956+
914957
# Start the LLM Request.
915958
self.logger.info(f"Prompt: {prompt}")
916959

@@ -953,11 +996,11 @@ def interpreter_main(self, version):
953996
elif self.SAVE_CODE and self.COMMAND_MODE:
954997
self.code_interpreter.save_code(f"output/command_{current_time}.txt", code_snippet)
955998
self.logger.info("Command saved successfully.")
956-
999+
9571000
elif self.SAVE_CODE and self.SCRIPT_MODE:
9581001
self.code_interpreter.save_code(f"output/script_{current_time}.txt", code_snippet)
9591002
self.logger.info("Script saved successfully.")
960-
1003+
9611004
# Execute the code if the user has selected.
9621005
code_output, code_error = self.execute_code(code_snippet, os_name)
9631006

0 commit comments

Comments
 (0)