Skip to content

Commit e793c81

Browse files
committed
Better profiles, script improvements
1 parent 8c15fa9 commit e793c81

File tree

9 files changed

+673
-511
lines changed

9 files changed

+673
-511
lines changed

archive/wtf copy.py

Lines changed: 474 additions & 0 deletions
Large diffs are not rendered by default.

interpreter_1/cli.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ def _profile_to_arg_params(profile: Profile) -> Dict[str, Dict[str, Any]]:
8585
"help": "Overwrite system message",
8686
},
8787
"custom_instructions": {
88-
"flags": ["--custom-instructions"],
89-
"default": profile.custom_instructions,
88+
"flags": ["--instructions"],
89+
"default": profile.instructions,
9090
"help": "Appended to default system message",
9191
},
9292
"max_budget": {
@@ -213,6 +213,9 @@ async def async_load():
213213
message = args["input_message"]
214214
else:
215215
message = sys.stdin.read().strip()
216+
# print("---")
217+
# print(message)
218+
# print("---")
216219
interpreter.messages = [{"role": "user", "content": message}]
217220

218221
# Run the generator until completion

interpreter_1/interpreter.py

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import traceback
88
import uuid
99
from datetime import datetime
10-
from typing import Any, List, Optional, cast
10+
from typing import Any, cast
1111

1212
from prompt_toolkit import PromptSession
1313
from prompt_toolkit.formatted_text import HTML
@@ -24,20 +24,22 @@
2424
from urllib.parse import quote
2525

2626
import litellm
27-
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex
27+
28+
litellm.suppress_debug_info = True
29+
litellm.REPEATED_STREAMING_CHUNK_LIMIT = 99999999
30+
litellm.modify_params = True
31+
32+
from anthropic import Anthropic
2833
from anthropic.types.beta import (
2934
BetaContentBlock,
3035
BetaContentBlockParam,
3136
BetaImageBlockParam,
3237
BetaMessage,
33-
BetaMessageParam,
3438
BetaRawContentBlockDeltaEvent,
3539
BetaRawContentBlockStartEvent,
3640
BetaRawContentBlockStopEvent,
37-
BetaTextBlock,
3841
BetaTextBlockParam,
3942
BetaToolResultBlockParam,
40-
BetaToolUseBlockParam,
4143
)
4244

4345
from .misc.spinner import SimpleSpinner
@@ -54,21 +56,6 @@
5456
# Initialize markdown renderer
5557
md = MarkdownRenderer()
5658

57-
# System prompt with dynamic values
58-
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
59-
* You are an AI assistant with access to a machine running on {"Mac OS" if platform.system() == "Darwin" else platform.system()} with internet access.
60-
* When using your computer function calls, they take a while to run and send back to you. Where possible/feasible, try to chain multiple of these calls all into one function calls request.
61-
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
62-
* The user's cwd is {os.getcwd()} and username is {os.getlogin()}.
63-
</SYSTEM_CAPABILITY>"""
64-
65-
# Update system prompt for Mac OS
66-
if platform.system() == "Darwin":
67-
SYSTEM_PROMPT += """
68-
<IMPORTANT>
69-
* Open applications using Spotlight by using the computer tool to simulate pressing Command+Space, typing the application name, and pressing Enter.
70-
</IMPORTANT>"""
71-
7259

7360
# Helper function used in async_respond()
7461
def _make_api_tool_result(
@@ -216,16 +203,20 @@ async def async_respond(self):
216203
tools.append(ComputerTool())
217204

218205
tool_collection = ToolCollection(*tools)
219-
system = BetaTextBlockParam(
220-
type="text",
221-
text=SYSTEM_PROMPT,
222-
)
223206

224207
model_info = litellm.get_model_info(self.model)
225208
if self.provider == None:
226209
self.provider = model_info["litellm_provider"]
227210
max_tokens = model_info["max_tokens"]
228211

212+
system_message = self.system_message + "\n\n" + self.instructions
213+
system_message = system_message.strip()
214+
215+
system = BetaTextBlockParam(
216+
type="text",
217+
text=system_message,
218+
)
219+
229220
while True:
230221
self._spinner.start()
231222

@@ -493,7 +484,7 @@ async def async_respond(self):
493484

494485
params = {
495486
"model": actual_model,
496-
"messages": [{"role": "system", "content": SYSTEM_PROMPT}]
487+
"messages": [{"role": "system", "content": system_message}]
497488
+ self.messages,
498489
"stream": stream,
499490
"api_base": api_base,

interpreter_1/misc/help.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def help_message(u):
4141
{BLUE_COLOR}--auto-run{RESET_COLOR}, {BLUE_COLOR}-y{RESET_COLOR} Auto-run suggested commands
4242
4343
{BLUE_COLOR}--system-message{RESET_COLOR} Override default system message
44-
{BLUE_COLOR}--instructions{RESET_COLOR} Additional instructions to append
44+
{BLUE_COLOR}--instructions{RESET_COLOR} Additional instructions in system message
4545
{BLUE_COLOR}--max-budget{RESET_COLOR} Maximum spend allowed (-1 for unlimited)
4646
{BLUE_COLOR}--max-turns{RESET_COLOR} Maximum conversation turns (-1 for unlimited)
4747

interpreter_1/profiles.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
11
import json
22
import os
3+
import platform
4+
from datetime import datetime
5+
6+
# System prompt with dynamic values
7+
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
8+
* You are an AI assistant with access to a machine running on {"Mac OS" if platform.system() == "Darwin" else platform.system()} with internet access.
9+
* When using your computer function calls, they take a while to run and send back to you. Where possible/feasible, try to chain multiple of these calls all into one function calls request.
10+
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
11+
* The user's cwd is {os.getcwd()} and username is {os.getlogin()}.
12+
</SYSTEM_CAPABILITY>"""
13+
14+
# Update system prompt for Mac OS
15+
if platform.system() == "Darwin":
16+
SYSTEM_PROMPT += """
17+
<IMPORTANT>
18+
* Open applications using Spotlight by using the computer tool to simulate pressing Command+Space, typing the application name, and pressing Enter.
19+
</IMPORTANT>"""
320

421

522
class Profile:
@@ -45,8 +62,8 @@ def __init__(self):
4562

4663
# Conversation state
4764
self.messages = [] # List of conversation messages
48-
self.system_message = None # System prompt override
49-
self.custom_instructions = None # Additional model instructions
65+
self.system_message = SYSTEM_PROMPT # System prompt override
66+
self.instructions = "" # Additional model instructions
5067

5168
# Available tools and settings
5269
self.tools = ["interpreter", "editor"] # Enabled tool modules

interpreter_1/ui/tool.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ def __init__(self, style):
3434
self.rendered_content = ""
3535
self.spinner = SimpleSpinner("")
3636
self.is_spinning = False
37-
self.terminal_width = os.get_terminal_size().columns
37+
try:
38+
self.terminal_width = os.get_terminal_size().columns
39+
except:
40+
self.terminal_width = 50
3841
self.safety_padding = 4 # Extra padding to prevent edge cases
3942
self.json_obj = None
4043

@@ -328,10 +331,13 @@ def __init__(self, style):
328331
self.line_number = 1
329332
self.rendered_content = ""
330333
self.is_spinning = False
331-
self.spinner = yaspin(Spinners.simpleDots, text=" ")
334+
self.spinner = SimpleSpinner("")
332335
self.code_lang = "python"
333336
self.buffer = ""
334-
self.terminal_width = os.get_terminal_size().columns
337+
try:
338+
self.terminal_width = os.get_terminal_size().columns
339+
except:
340+
self.terminal_width = 50
335341
self.prefix_width = 5 # "123 │ " = 6 characters
336342
self.safety_padding = 2 # Extra padding to prevent edge cases
337343
self.show_context = True
@@ -506,7 +512,10 @@ def __init__(self, style):
506512
self.rendered_content = ""
507513
self.line_number = 1
508514
self.code_lang = "python"
509-
self.terminal_width = os.get_terminal_size().columns
515+
try:
516+
self.terminal_width = os.get_terminal_size().columns
517+
except:
518+
self.terminal_width = 50
510519
self.prefix_width = 6
511520
self.safety_padding = 4
512521
self.buffer = "" # Add buffer for line-by-line processing
@@ -623,7 +632,10 @@ class SchemaRenderer:
623632

624633
@staticmethod
625634
def print_separator(char="─", newline=True, line=True):
626-
terminal_width = os.get_terminal_size().columns
635+
try:
636+
terminal_width = os.get_terminal_size().columns
637+
except:
638+
terminal_width = 50
627639
if newline:
628640
sys.stdout.write("\n")
629641
if line:

pyproject.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,11 @@ requires = ["poetry-core>=1.0.0"]
2929
build-backend = "poetry.core.masonry.api"
3030

3131
[tool.poetry.scripts]
32-
interpreter = "interpreter.terminal_interface.start_terminal_interface:main"
32+
i = "interpreter_1.cli:main"
33+
interpreter = "interpreter_1.cli:main"
34+
3335
wtf = "scripts.wtf:main"
3436
interpreter-classic = "interpreter.terminal_interface.start_terminal_interface:main"
35-
i = "interpreter_1.cli:main"
3637

3738
[tool.black]
3839
target-version = ['py311']

scripts/setup.py

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
"""
2+
Shell Integration Setup for Open Interpreter
3+
4+
This script installs shell integration that:
5+
1. Maintains a transcript of terminal interactions (commands and their outputs)
6+
2. Captures both successful commands and their results
7+
3. Routes unknown commands to the interpreter with full terminal history as context
8+
4. Works with both zsh and bash shells
9+
10+
The history is stored in ~/.shell_history_with_output in a chat-like format:
11+
user: <command>
12+
computer: <output>
13+
"""
14+
15+
import os
16+
import re
17+
from pathlib import Path
18+
19+
20+
def get_shell_config():
21+
"""Determine user's shell and return the appropriate config file path."""
22+
shell = os.environ.get("SHELL", "").lower()
23+
home = str(Path.home())
24+
25+
if "zsh" in shell:
26+
return os.path.join(home, ".zshrc"), "zsh"
27+
elif "bash" in shell:
28+
bash_rc = os.path.join(home, ".bashrc")
29+
bash_profile = os.path.join(home, ".bash_profile")
30+
31+
if os.path.exists(bash_rc):
32+
return bash_rc, "bash"
33+
elif os.path.exists(bash_profile):
34+
return bash_profile, "bash"
35+
36+
return None, None
37+
38+
39+
def get_shell_script(shell_type):
40+
"""Return the appropriate shell script based on shell type."""
41+
base_script = """# Create log file if it doesn't exist
42+
touch ~/.shell_history_with_output
43+
44+
# Function to capture terminal interaction
45+
function capture_output() {
46+
local cmd=$1
47+
echo "user: $cmd" >> ~/.shell_history_with_output
48+
echo "computer:" >> ~/.shell_history_with_output
49+
eval "$cmd" >> ~/.shell_history_with_output 2>&1
50+
}
51+
52+
# Command not found handler that pipes context to interpreter
53+
command_not_found_handler() {
54+
cat ~/.shell_history_with_output | interpreter
55+
return 0
56+
}
57+
58+
# Hook into preexec"""
59+
60+
if shell_type == "zsh":
61+
return base_script + '\npreexec() {\n capture_output "$1"\n}\n'
62+
elif shell_type == "bash":
63+
return (
64+
base_script
65+
+ '\ntrap \'capture_output "$(HISTTIMEFORMAT= history 1 | sed "s/^[ ]*[0-9]*[ ]*//")" \' DEBUG\n'
66+
)
67+
return None
68+
69+
70+
def main():
71+
"""Install or reinstall the shell integration."""
72+
print("Starting installation...")
73+
config_path, shell_type = get_shell_config()
74+
75+
if not config_path or not shell_type:
76+
print("Could not determine your shell configuration.")
77+
print(
78+
"Please visit docs.openinterpreter.com/shell for manual installation instructions."
79+
)
80+
return
81+
82+
# Clean up history file
83+
history_file = os.path.expanduser("~/.shell_history_with_output")
84+
if os.path.exists(history_file):
85+
os.remove(history_file)
86+
87+
# Create fresh history file
88+
with open(history_file, "w") as f:
89+
f.write("")
90+
91+
# Read existing config
92+
try:
93+
with open(config_path, "r") as f:
94+
content = f.read()
95+
except FileNotFoundError:
96+
content = ""
97+
98+
start_marker = "### <openinterpreter> ###"
99+
end_marker = "### </openinterpreter> ###"
100+
101+
# Check if markers exist
102+
if start_marker in content:
103+
response = input(
104+
"Open Interpreter shell integration appears to be already installed. Would you like to reinstall? (y/n): "
105+
)
106+
if response.lower() != "y":
107+
print("Installation cancelled.")
108+
return
109+
110+
# Remove existing installation
111+
pattern = f"{start_marker}.*?{end_marker}"
112+
content = re.sub(pattern, "", content, flags=re.DOTALL)
113+
114+
# Get appropriate shell script
115+
shell_script = get_shell_script(shell_type)
116+
117+
# Create new content
118+
new_content = (
119+
f"{content.rstrip()}\n\n{start_marker}\n{shell_script}\n{end_marker}\n"
120+
)
121+
122+
# Write back to config file
123+
try:
124+
with open(config_path, "w") as f:
125+
f.write(new_content)
126+
print(
127+
f"Successfully installed Open Interpreter shell integration to {config_path}"
128+
)
129+
print("Please restart your shell or run 'source ~/.zshrc' to apply changes.")
130+
except Exception as e:
131+
print(f"Error writing to {config_path}: {e}")
132+
print(
133+
"Please visit docs.openinterpreter.com/shell for manual installation instructions."
134+
)
135+
136+
137+
if __name__ == "__main__":
138+
main()

0 commit comments

Comments
 (0)