-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsiesta.py
executable file
·215 lines (169 loc) · 5.19 KB
/
siesta.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python3
import os
import shlex
import io
import sys
import subprocess
from uuid import uuid4
import hashlib
import json
import re
import shelve
from litellm import completion
from concurrent.futures import ThreadPoolExecutor
from jinja2 import Environment, FileSystemLoader
from jinja2.exceptions import TemplateNotFound
class Siesta:
def __init__(self, argv):
self.argv = argv
self.template_file = argv[1]
self._uuid2futures = {}
self.env = Environment(
loader=FileSystemLoader(os.path.dirname(self.template_file)),
lstrip_blocks=True,
)
def run(self):
self.pool = ThreadPoolExecutor()
self.cache = shelve.open(os.path.expanduser("~/.prompt_cache"))
template = self.env.get_template(os.path.basename(self.template_file))
output = template.render(argv=sys.argv, input=" ".join(sys.argv[2:]))
lines = output.splitlines()
if lines and lines[0].startswith("#!"):
lines = lines[1:]
print("\n".join(lines).strip("\n"))
def filter(self, func):
name = func.__name__.rstrip("_")
self.env.filters[name] = lambda *args, **kwargs: self._expand_futures(
func(*args, **kwargs)
)
return func
def _expand_futures(self, stri):
for uuid, future in self._uuid2futures.items():
if uuid in stri:
stri = stri.replace(uuid, future.result())
return stri
def register_future(self, future):
uuid = str(uuid4())
self._uuid2futures[uuid] = future
return uuid
try:
siesta = Siesta(sys.argv)
except IndexError:
print("usage: siesta <template-file> <args>")
sys.exit(1)
@siesta.filter
def run(input, cmd="bash", label=False, silentfail=False):
# Start the process
if not isinstance(cmd, str):
cmd = shlex.join(cmd)
input = input.strip(" \n")
process = subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, text=True
)
# Send input and capture output
stdout, _ = process.communicate(input=input)
# Print the results
if process.returncode != 0:
if silentfail:
return ""
print(f"Error calling subprocess: {cmd}")
sys.exit(1)
if label:
return f"```{cmd}\n$ {input}\n{stdout}\n\n```"
return stdout
@siesta.filter
def debug(input):
print(input)
print("=== DEBUG DIE DIE ===")
sys.exit(0)
def prompt_sync(prompt, model, **kwargs):
# Import on-demand because its slow
cache_key = hashlib.sha256(f"{model}:{prompt}:{kwargs}".encode()).hexdigest()
if os.environ.get("SIESTA_CACHE") in ("yes", "true", "1"):
cached = None
else:
cached = siesta.cache.get(cache_key)
if cached is not None:
return cached
else:
response = completion(
model=model,
messages=[{"content": prompt, "role": "user"}],
stream=True,
**kwargs,
)
msg = io.StringIO()
for chunk in response:
delta = chunk.choices[0].delta.content
if not delta:
break
msg.write(delta)
if os.environ.get("SIESTA_VERBOSE") in ("yes", "true", "1"):
sys.stderr.write(delta)
sys.stderr.flush()
msgval = msg.getvalue()
siesta.cache[cache_key] = msgval
return msgval
@siesta.filter
def prompt(model, input, **kwargs):
future = siesta.pool.submit(prompt_sync, model, input, **kwargs)
return siesta.register_future(future)
@siesta.filter
def catfiles(np):
files = re.findall(r"(\w+\/[\w/\.]+)", inp) # BUGGED, rewrite re
contents = io.StringIO()
for file in files:
if os.path.exists(file):
with open(file, "r") as f:
content = f.read()
contents.write(f"=== file: {file} ===\n{content}\n======\n")
return contents.getvalue()
@siesta.filter
def code(inp):
triple_quotes = re.findall(r"```(.*?)```", inp, re.DOTALL)
single_quotes = re.findall(r"`(.*?)`", inp, re.DOTALL)
if triple_quotes:
return "\n".join(triple_quotes[-1].splitlines()[1:])
if single_quotes:
return single_quotes[-1]
return inp
@siesta.filter
def askrun(inp):
print(f"$ {inp}")
try:
ask = input("[R]epeat, E[x]ecute, E[d] or [Q]uit?")
except KeyboardInterrupt:
print()
sys.exit(130)
if ask == "":
ask = "r"
if ask == "x":
os.execlp("bash", "bash", "-c", inp)
elif ask == "r":
siesta.run()
elif ask == "q":
sys.exit(0)
return ""
@siesta.filter
def quote(stri):
return shlex.quote(stri)
@siesta.filter
def print_(stri):
print(stri)
return stri
@siesta.filter
def json_(stri):
return json.loads(stri)
@siesta.filter
def askedit(stri, label="Edit"):
result = subprocess.run(
["dialog", "--inputbox", label, "10", "100", stri], # Example command
text=True, # Handle output as text (str)
stderr=subprocess.PIPE, # Capture only stderr
check=True, # Raise an exception on s;
)
return result.stderr
def main():
siesta.run()
if __name__ == "__main__":
main()