-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplayground_streamlit.py
306 lines (273 loc) · 8.54 KB
/
playground_streamlit.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
from typing import List, Union
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder
import streamlit as st
import diskcache
from oai_client import OAIClient
from settings import Settings
import utils
PROMPT_DIR = "./data/prompts"
DEFAULT_PROMPT_ID = "default_prompt"
# TODO(bfortuner): Update with token limits
MODELS = [
"text-davinci-002",
"text-curie-001",
"text-babbage-001",
"text-ada-001",
"code-davinci-002",
"code-cushman-001",
]
STOP_SEQUENCES = [
"newline",
"double-newline",
"Human:",
"Assistant:",
"Q:",
"A:",
"INPUT",
"OUTPUT",
]
DEFAULT_PROMPT = utils.load_prompt(DEFAULT_PROMPT_ID, PROMPT_DIR)
@st.cache(ttl=60 * 60 * 24)
def init_oai_client():
ctx = Settings.from_env_file(".env.secret")
cache = diskcache.Cache(directory=ctx.disk_cache_dir)
oai_client = OAIClient(
api_key=ctx.openai_api_key,
organization_id=ctx.openai_org_id,
cache=cache,
)
return oai_client
@st.cache(ttl=5)
def list_prompts(prompt_dir: str) -> List[str]:
return utils.list_prompts(prompt_dir)
def create_prompt(
prompt_name: str, prompt_text: str, params: dict, inputs: dict, prompt_dir: str
):
prompt_id = utils.make_prompt_id(prompt_name)
utils.save_prompt(
prompt_id,
prompt_text=prompt_text,
params=params,
inputs=inputs,
prompt_dir=prompt_dir,
)
return prompt_id
def run_completion(
oai_client: OAIClient,
prompt_text: str,
model: str,
stop: Union[List[str], None],
max_tokens: int,
temperature: float,
):
print("Running completion!")
if stop:
if "double-newline" in stop:
stop.remove("double-newline")
stop.append("\n\n")
if "newline" in stop:
stop.remove("newline")
stop.append("\n")
resp = oai_client.complete(
prompt_text,
model=model, # type: ignore
max_tokens=max_tokens, # type: ignore
temperature=temperature,
stop=stop or None,
)
return resp
def run_all(
oai_client: OAIClient,
prompt_template: str,
model: str,
stop: Union[List[str], None],
max_tokens: int,
temperature: float,
inputs_df: pd.DataFrame,
) -> pd.DataFrame:
"""Run openai completion for all inputs."""
for index, row in inputs_df.iterrows():
inputs = row.to_dict()
prompt_text = utils.inject_inputs(prompt_template, inputs.keys(), inputs)
resp = run_completion(
oai_client,
prompt_text,
model,
stop,
max_tokens,
temperature,
)
inputs_df.loc[index, "output"] = resp["completion"]
print(inputs_df)
return inputs_df
def main():
utils.init_page_layout()
session = st.session_state
oai_client = init_oai_client()
prompt_ids = list_prompts(PROMPT_DIR)
print("PromptIds: ", prompt_ids)
## RUN + SAVE PROMPT
col1, col2, col3, col4 = st.columns([4, 2, 2, 2])
with col2:
run_button = st.button("Run Prompt", help="Run the prompt")
with col3:
save_button = st.button("Save Prompt", help="Save the prompt")
with col4:
delete_prompt = st.button("Delete Prompt", help="Delete the prompt")
## SIDEBAR
with st.sidebar:
prompt_id_index = len(prompt_ids) - 1
if "prompt_id" in session:
prompt_id_index = prompt_ids.index(session.prompt_id)
prompt_id = st.selectbox(
"Select Prompt",
options=prompt_ids,
index=prompt_id_index,
key="prompt_id",
)
if not prompt_id:
return
else:
session.prompt = utils.load_prompt(prompt_id, PROMPT_DIR)
## MODEL PARAMS
model = st.selectbox(
"Model",
MODELS,
index=MODELS.index(session.prompt["params"]["model"]),
)
max_tokens = st.number_input(
"Max tokens",
value=session.prompt["params"]["max_tokens"],
min_value=0,
max_value=2048,
step=2,
)
temperature = st.number_input(
"Temperature", value=session.prompt["params"]["temperature"], step=0.05
)
stop = st.multiselect(
"Stop",
STOP_SEQUENCES,
default=session.prompt["params"]["stop"]
if session.prompt["params"]["stop"]
else None,
)
def create_prompt_fn(session_state, prompt_name, params):
if not prompt_name:
st.error("Prompt name is required")
return
new_prompt_id = create_prompt(
prompt_name=prompt_name,
prompt_text="",
params=params,
inputs={},
prompt_dir=PROMPT_DIR,
)
session_state.prompt_id = new_prompt_id
session_state.prompt = utils.load_prompt(prompt_id, PROMPT_DIR)
## CREATE PROMPT
st.markdown("---")
st.markdown("New Prompt")
prompt_name = st.text_input("Prompt Name")
params = dict(
model=model,
max_tokens=max_tokens,
temperature=temperature,
stop=stop,
)
st.button(
"New Prompt",
help="Create a new prompt",
on_click=create_prompt_fn,
kwargs={
"session_state": session,
"prompt_name": prompt_name,
"params": params,
},
)
prompt_tab, inputs_tab = st.tabs(["Prompt", "Inputs"])
## PROMPT TAB
with prompt_tab:
prompt_area = st.empty()
prompt_text = prompt_area.text_area(
"Prompt",
value=session.prompt["prompt_text"],
height=300,
label_visibility="hidden",
placeholder="Prompt text..",
)
# TODO(bfortuner): Allow running with CMD + ENTER
if run_button:
resp = run_completion(
oai_client=oai_client,
prompt_text=prompt_text,
model=model, # type: ignore
stop=stop,
max_tokens=max_tokens, # type: ignore
temperature=temperature,
)
completion_text = st.text_area(
"Completion",
height=300,
value=resp.get("completion"),
disabled=True,
# label_visibility="hidden",
)
if completion_text:
print("Completion Result: \n\n", completion_text)
inputs_df = None
with inputs_tab:
uploaded_file = st.file_uploader("Upload Inputs CSV", type="csv")
if uploaded_file is not None:
inputs_df = pd.read_csv(uploaded_file)
session.prompt["inputs"] = inputs_df.to_dict()
elif session.prompt.get("inputs"):
inputs_df = pd.DataFrame(session.prompt["inputs"])
if inputs_df is not None:
gb = GridOptionsBuilder.from_dataframe(inputs_df)
gb.configure_default_column(editable=True)
response = AgGrid(
inputs_df,
gridOptions=gb.build(),
fit_columns_on_grid_load=True,
allow_unsafe_jscode=True,
)
print(response["data"])
if st.button("Run All", help="Run all inputs"):
inputs_df = run_all(
oai_client=oai_client,
inputs_df=response["data"],
prompt_template=prompt_text,
model=model,
stop=stop,
max_tokens=max_tokens,
temperature=temperature,
)
st.write(inputs_df)
# button for "Run Selected"
# button for "Save"
if save_button:
inputs_dict = inputs_df.to_dict() if inputs_df is not None else {}
utils.save_prompt(
prompt_id=prompt_id,
prompt_text=prompt_text,
params=dict(
model=model,
max_tokens=max_tokens,
temperature=temperature,
stop=stop,
),
inputs=inputs_dict,
prompt_dir=PROMPT_DIR,
)
prompt_name = ""
if delete_prompt:
if len(prompt_ids) <= 1:
st.error("Cannot delete last prompt")
else:
utils.delete_prompt(session.prompt_id, PROMPT_DIR)
del session.prompt_id
st.experimental_rerun()
if __name__ == "__main__":
main()