forked from togethercomputer/MoA
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
432 lines (386 loc) · 15.7 KB
/
app.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import streamlit as st
import json
from typing import Iterable, Optional
from moa.agent import MOAgent
from moa.agent.moa import ResponseChunk
from streamlit_ace import st_ace
import copy
from dotenv import load_dotenv
from PIL import Image
import requests
import os
load_dotenv()
# Update the default configuration
default_config = {
"main_model": "rys-llama3.1:8b-instruct-Q8_0",
"main_system_prompt": "You are a helpful assistant. Written text should always use British English spelling.",
"cycles": 2,
"layer_agent_config": {},
}
layer_agent_config_def = {
"layer_agent_1": {
"system_prompt": "Written text should always use British English spelling. Think through your response step by step. {helper_response}",
"model_name": "rys-llama3.1:8b-instruct-Q8_0",
"temperature": 0.6,
},
"layer_agent_2": {
"system_prompt": "Written text should always use British English spelling. Respond with a thought and then your response to the question. {helper_response}",
"model_name": "qwen2-7b-maziyarpanahi-v0_8-instruct:Q6_K",
"temperature": 0.5,
},
"layer_agent_3": {
"system_prompt": "You are an expert programmer. Written text should always use British English spelling. Always use the latest libraries and techniques. {helper_response}",
"model_name": "mistral-nemo:12b-instruct-2407-q6_K",
"temperature": 0.3,
},
}
default_model_names = [
"rys-llama3.1:8b-instruct-Q8_0",
"qwen2-7b-maziyarpanahi-v0_8-instruct:Q6_K",
"mistral-nemo:12b-instruct-2407-q6_K",
"deepseek-coder-v2-lite-instruct:q6_k_l",
"codestral-22b_ef16:q6_k",
"llama3.1:8b-instruct-q6_K",
"llama3.1:70b-instruct-q4_K_M",
"qwen2-72b-maziyarpanahi-v0_1-instruct:IQ4_XS",
"mistral-large-instruct-2407:iq2_m",
]
def add_logo():
logo = Image.open("static/logo.png")
st.sidebar.image(logo, width=150)
def api_request_callback(request):
if st.session_state.log_api_requests:
st.write(f"API Request: {request}")
def fetch_ollama_models():
try:
ollama_host = st.session_state.main_api_base or os.getenv(
"OLLAMA_HOST", "http://localhost:11434"
)
response = requests.get(f"{ollama_host}/api/tags")
if response.status_code == 200:
data = response.json()
models = [model["name"] for model in data["models"]]
return models
else:
st.error(f"Failed to fetch models: HTTP {response.status_code}")
return None
except Exception as e:
st.error(f"Error fetching models: {str(e)}")
return None
def stream_response(messages: Iterable[ResponseChunk]):
layer_outputs = {i: [] for i in range(1, st.session_state.cycles + 1)}
main_output = []
for message in messages:
if message["response_type"] == "intermediate":
layer = message["metadata"]["layer"]
layer_outputs[layer].append(message["delta"])
else:
main_output.append(message["delta"])
# Display all layer outputs side by side
cols = st.columns(st.session_state.cycles)
for i, (layer, outputs) in enumerate(layer_outputs.items()):
with cols[i]:
st.write(f"Layer {layer}")
if outputs:
st.expander(label=f"Agent {layer}", expanded=False).write(
"".join(outputs)
)
else:
st.write("No output from this layer")
# Return the main output
return "".join(main_output)
def set_moa_agent(**kwargs):
for key, value in kwargs.items():
if value is not None:
setattr(st.session_state, key, value)
main_model_kwargs = {
"temperature": st.session_state.main_temperature,
# "max_tokens": st.session_state.main_max_tokens,
}
optional_params = [
("top_p", "main_top_p"),
("top_k", "main_top_k"),
# ("min_p", "main_min_p"),
# ("repetition_penalty", "main_repetition_penalty"),
("presence_penalty", "main_presence_penalty"),
("frequency_penalty", "main_frequency_penalty"),
]
for api_param, state_param in optional_params:
value = getattr(st.session_state, state_param)
if value is not None and value != 0: # Assume 0 means disabled for these params
main_model_kwargs[api_param] = value
if st.session_state.main_api_base:
main_model_kwargs["api_base"] = st.session_state.main_api_base
if st.session_state.main_api_key:
main_model_kwargs["api_key"] = st.session_state.main_api_key
if st.session_state.main_num_ctx and st.session_state.main_num_ctx > 0:
main_model_kwargs["num_ctx"] = st.session_state.main_num_ctx
if st.session_state.main_num_batch and st.session_state.main_num_batch > 0:
main_model_kwargs["num_batch"] = st.session_state.main_num_batch
st.session_state.moa_agent = MOAgent.from_config(
main_model=st.session_state.main_model,
main_system_prompt=st.session_state.main_system_prompt,
cycles=st.session_state.cycles,
layer_agent_config=copy.deepcopy(st.session_state.layer_agent_config),
**main_model_kwargs,
)
def initialize_session_state():
if "messages" not in st.session_state:
st.session_state.messages = []
default_values = {
"main_model": "rys-llama3.1:8b-instruct-Q8_0",
"main_system_prompt": "You are a helpful assistant. Written text should always use British English spelling.",
"cycles": 2,
"layer_agent_config": copy.deepcopy(layer_agent_config_def),
"main_temperature": 0.6,
"main_api_base": "",
"main_api_key": "",
"main_num_ctx": 2048,
"log_api_requests": False,
"available_models": default_model_names,
}
for key, value in default_values.items():
if key not in st.session_state:
setattr(st.session_state, key, value)
# Initialize optional parameters as None
optional_params = [
"main_top_p",
"main_top_k",
# "main_min_p",
# "main_repetition_penalty",
"main_presence_penalty",
"main_frequency_penalty",
"main_num_batch",
]
for param in optional_params:
if param not in st.session_state:
setattr(st.session_state, param, None)
def render_sidebar():
with st.sidebar:
st.title("Mixture of (Ollama) Agents")
with st.expander("Main Model Settings", expanded=False):
if st.button("Fetch Ollama Models"):
models = fetch_ollama_models()
if models:
st.session_state.available_models = models
st.success("Models fetched successfully!")
else:
st.warning("Failed to fetch models. Using default list.")
available_models = st.session_state.get(
"available_models", default_model_names
)
st.session_state.main_model = st.selectbox(
"Select Main Model",
options=available_models,
index=(
available_models.index(st.session_state.main_model)
if st.session_state.main_model in available_models
else 0
),
)
new_cycles = st.number_input(
"Number of Layers",
min_value=1,
max_value=10,
value=st.session_state.cycles,
key="cycles_input",
)
st.session_state.main_temperature = st.slider(
"Temperature",
min_value=0.0,
max_value=2.0,
value=st.session_state.main_temperature,
step=0.1,
)
# st.session_state.main_max_tokens = st.number_input(
# "Max Tokens",
# min_value=1,
# max_value=8192,
# value=st.session_state.main_max_tokens,
# )
with st.expander("Advanced Settings", expanded=False):
st.session_state.main_num_ctx = st.number_input(
"Context Size (num_ctx)",
min_value=1,
max_value=32768,
value=st.session_state.main_num_ctx,
help="Number of context tokens. Set to 0 to use model default.",
)
st.session_state.main_num_batch = st.number_input(
"Batch Size (num_batch)",
min_value=0,
max_value=4096,
value=(
st.session_state.main_num_batch
if st.session_state.main_num_batch is not None
else 0
),
help="Batch size. Set to 0 to use model default.",
)
st.session_state.main_top_p = st.slider(
"Top P",
min_value=0.0,
max_value=1.0,
value=(
st.session_state.main_top_p
if st.session_state.main_top_p is not None
else 1.0
),
step=0.01,
help="Set to None to disable",
)
st.session_state.main_top_k = st.number_input(
"Top K",
min_value=1,
max_value=100,
value=(
st.session_state.main_top_k
if st.session_state.main_top_k is not None
else 40
),
help="Set to 0 to disable",
)
# st.session_state.main_min_p = st.slider(
# "Min P",
# min_value=0.0,
# max_value=1.0,
# value=(
# st.session_state.main_min_p
# if st.session_state.main_min_p is not None
# else 0.05
# ),
# step=0.01,
# help="Set to 0 to disable",
# )
# st.session_state.main_repetition_penalty = st.slider(
# "Repetition Penalty",
# min_value=1.0,
# max_value=2.0,
# value=(
# st.session_state.main_repetition_penalty
# if st.session_state.main_repetition_penalty is not None
# else 1.1
# ),
# step=0.01,
# help="Set to 1 to disable",
# )
st.session_state.main_presence_penalty = st.slider(
"Presence Penalty",
min_value=0.0,
max_value=2.0,
value=(
st.session_state.main_presence_penalty
if st.session_state.main_presence_penalty is not None
else 0.0
),
step=0.01,
help="Set to 0 to disable",
)
st.session_state.main_frequency_penalty = st.slider(
"Frequency Penalty",
min_value=0.0,
max_value=2.0,
value=(
st.session_state.main_frequency_penalty
if st.session_state.main_frequency_penalty is not None
else 0.0
),
step=0.01,
help="Set to 0 to disable",
)
with st.expander("API Settings", expanded=False):
st.session_state.main_api_base = st.text_input(
"API Base URL", value=st.session_state.main_api_base
)
st.session_state.main_api_key = st.text_input(
"API Key", value=st.session_state.main_api_key, type="password"
)
with st.expander("System Prompt", expanded=False):
main_system_prompt = st.text_area(
"Main System Prompt",
value=st.session_state.main_system_prompt,
height=100,
)
log_api_requests = st.checkbox("Log API Requests", value=False)
if st.button("Update Configuration"):
try:
set_moa_agent(
main_system_prompt=main_system_prompt,
cycles=new_cycles,
layer_agent_config=st.session_state.layer_agent_config,
)
st.session_state.messages = []
st.session_state.log_api_requests = log_api_requests
st.success("Configuration updated successfully!")
except Exception as e:
st.error(f"Error updating configuration: {str(e)}")
if st.button("Use Recommended Config"):
try:
recommended_config = {
"main_model": "rys-llama3.1:8b-instruct-Q8_0",
"cycles": 2,
"layer_agent_config": {
"layer_agent_1": {
"system_prompt": "Written text should always use British English spelling. Think through your response step by step. {helper_response}",
"model_name": "rys-llama3.1:8b-instruct-Q8_0",
"temperature": 0.7,
},
"layer_agent_2": {
"system_prompt": "Written text should always use British English spelling. Respond with a thought and then your response to the question. {helper_response}",
"model_name": "qwen2-7b-maziyarpanahi-v0_8-instruct:Q6_K",
"temperature": 0.5,
},
},
}
set_moa_agent(**recommended_config)
st.session_state.messages = []
st.success("Configuration updated to recommended settings!")
except Exception as e:
st.error(f"Error updating to recommended configuration: {str(e)}")
# Add current configuration display
with st.expander("Current MOA Configuration", expanded=False):
st.markdown(f"**Main Model**: `{st.session_state.main_model}`")
st.markdown(f"**Layers**: `{st.session_state.cycles}`")
st.markdown(
f"**Main System Prompt**: `{st.session_state.main_system_prompt}`"
)
st.markdown(
f"**Main Model Temperature**: `{st.session_state.main_temperature:.1f}`"
)
# st.markdown(
# f"**Main Model Max Tokens**: `{st.session_state.main_max_tokens}`"
# )
st.markdown(f"**Layer Agents Config**:")
st.json(st.session_state.layer_agent_config)
def render_chat_interface():
st.markdown(
"<h4 style='text-align: left; font-size: 20px;'>Mixture Of Agents</h4>",
unsafe_allow_html=True,
)
st.image("./static/banner.png", caption="", width=200)
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if query := st.chat_input("Ask a question"):
st.session_state.messages.append({"role": "user", "content": query})
with st.chat_message("user"):
st.write(query)
moa_agent: MOAgent = st.session_state.moa_agent
with st.chat_message("assistant"):
response = stream_response(moa_agent.chat(query, output_format="json"))
st.write(response)
st.session_state.messages.append({"role": "assistant", "content": response})
def main():
st.set_page_config(
page_title="Mixture-Of-Agents",
page_icon="static/favicon.ico",
menu_items={"About": "## Ollama Mixture-Of-Agents"},
layout="wide",
)
add_logo()
initialize_session_state()
set_moa_agent()
render_sidebar()
render_chat_interface()
if __name__ == "__main__":
main()