-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathcli.py
261 lines (216 loc) · 8.57 KB
/
cli.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# pylint: disable=E0401
# pylint: disable=W0122
# pylint: disable=W0718
import os
import openai
import sys
import argparse
import traceback
from getpass import getpass
from rich import print as rprint
from utils.utils import print_markdown, print_exception, extract_code_blocks, print_help
from utils.stream import TextStream
from utils.ai import (
retrieve_context,
construct_prompt,
get_remote_chat_response,
get_other_chat_response,
)
from constants.cli import ARGUMENTS, LIBRARIES, OPENAI_MODELS
from constants.ai import MODELS_TO_TOKENS
def main():
parser = argparse.ArgumentParser(description="Fleet Data Retriever", add_help=False)
parser.add_argument("help", nargs="?", default=argparse.SUPPRESS)
# Add arguments
for arg in ARGUMENTS:
if arg["type"] == bool:
default = arg["default"] if "default" in arg else None
parser.add_argument(
f'-{arg["nickname"]}',
f'--{arg["name"]}',
dest=arg["name"],
help=arg["help_text"],
action="store_true",
default=default,
)
elif arg["type"] == list:
choices = arg["choices"] if "choices" in arg else None
default = arg["default"] if "default" in arg else None
parser.add_argument(
f'-{arg["nickname"]}',
f'--{arg["name"]}',
dest=arg["name"],
help=arg["help_text"],
type=str,
nargs="+",
choices=choices,
default=default,
)
else:
choices = arg["choices"] if "choices" in arg else None
default = arg["default"] if "default" in arg else None
parser.add_argument(
f'-{arg["nickname"]}',
f'--{arg["name"]}',
dest=arg["name"],
help=arg["help_text"],
type=arg["type"],
choices=choices,
default=default,
)
# Hit the retrieve endpoint
args = parser.parse_args()
k = args.k_value
model = args.model
cite_sources = args.cite_sources
filters = {}
if getattr(args, "help", None) is not None:
print_help()
return
# If library specified, match library name to uuid
if args.libraries:
for library in args.libraries:
if library not in LIBRARIES:
rprint(
"Library not found. Please refer to the list of available libraries."
)
return
filters["library_name"] = args.libraries
# Get context window
if model in OPENAI_MODELS:
context_window = MODELS_TO_TOKENS[model]
else:
context_window = args.context_window
# If local model requested, use LMStudio
api_key = ""
if args.local:
model = "local-model"
print_markdown(
f"""---
**You are using a local model.**
We're working with LM Studio to provide access to local models for you. Download and start your model to get started.
Instructions:
1. Download LM Studio. You can find the download link here: https://lmstudio.ai
2. Open LM Studio and download your model of choice.
3. Click the **↔ icon** on the very left sidebar
4. Select your model and click "Start Server"
Note that your context window is set to {context_window}. To change this, run `context --context_window <context window>`.
---"""
)
else:
openrouter_key = os.environ.get("OPENROUTER_API_KEY")
openai_key = os.environ.get("OPENAI_API_KEY")
# Get the OpenAI API key, if not found
if model in OPENAI_MODELS and not openai_key:
print_markdown(
"""---
!!!**OpenAI API key not found.**
Please provide a key to proceed.
---
"""
)
openai_key = getpass("OpenAI API key: ")
os.environ["OPENAI_API_KEY"] = openai_key
print_markdown(
"""
---
**Tip**: To save this key for later, run `export OPENAI_API_KEY=<your key>` on mac/linux or `setx OPENAI_API_KEY <your key>` on windows.
For non-OpenAI models, you should set `OPENROUTER_API_KEY`, and optionally `OPENROUTER_APP_URL` and `OPENROUTER_APP_TITLE`.
---"""
)
# Otherwise, grab the openrouter key, if not found
elif model not in OPENAI_MODELS and not openrouter_key:
print_markdown(
"""---
!!!**OpenRouter API key not found.**
Please provide a key to proceed.
---
"""
)
api_key = getpass("OpenRouter API key: ")
os.environ["OPENROUTER_API_KEY"] = api_key
print_markdown(
f"""
---
**Tip**: To save this key for later, run `export OPENROUTER_API_KEY=<your key>` on mac/linux or `setx OPENROUTER_API_KEY <your key>` on windows.
You can optionally set `OPENROUTER_APP_URL` and `OPENROUTER_APP_TITLE`, too.
Note that your context window is set to {context_window}. To change this, run `context --context_window <context window>`.
---"""
)
if model == "gpt-4-1106-preview":
print_markdown(
"""!!!Welcome to Fleet Context!
Generate and run code using the most up-to-date libraries.
*Warning*: You are using gpt-4-turbo, which is not yet stable and is rate limited at 100 requests per day. Please use with caution.
"""
)
else:
print_markdown(
"""!!!Welcome to Fleet Context!
Generate and run code using the most up-to-date libraries.
"""
)
messages = []
while True:
try:
query = input("> ")
query = query.strip()
if not query:
continue
if query.lower() == "exit":
rprint("Exiting. Goodbye!")
break
messages.append({"role": "user", "content": query})
rag_context = retrieve_context(query, k=k, filters=filters)
prompts = construct_prompt(
messages,
rag_context,
model=model,
cite_sources=cite_sources,
context_window=context_window,
)
full_response = ""
try:
streamer = TextStream()
if model in OPENAI_MODELS:
for response in get_remote_chat_response(prompts, model=model):
if response:
full_response += response
streamer.print_stream(full_response)
else:
for response in get_other_chat_response(prompts, model=model):
if response:
full_response += response
streamer.print_stream(full_response)
finally:
streamer.end_stream()
rprint("\n")
# Add to messages
messages.append({"role": "assistant", "content": full_response})
# Execute code blocks
code_blocks = extract_code_blocks(full_response)
if code_blocks:
while True:
user_response = input("Run code? (y/n): ")
if user_response not in ["y", "n"]:
rprint("Invalid response. Please input 'y' or 'n'.")
elif user_response == "y":
try:
exec(code_blocks)
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
print_exception(exc_type, exc_value, exc_traceback)
messages.append(
{
"role": "user",
"content": f"An exception occured. {''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))}",
}
)
break
else:
break
except KeyboardInterrupt:
rprint("\nExiting. Goodbye!")
break
if __name__ == "__main__":
main()