DrishtiSharma commited on
Commit
e39f873
Β·
verified Β·
1 Parent(s): 90596c4

Create interim.py

Browse files
Files changed (1) hide show
  1. interim.py +267 -0
interim.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ref: https://github.com/kram254/Mixture-of-Agents-running-on-Groq/tree/main
2
+ import streamlit as st
3
+ import json
4
+ import asyncio
5
+ from typing import Union, Iterable, AsyncIterable
6
+ from moa.agent import MOAgent
7
+ from moa.agent.moa import ResponseChunk
8
+ from streamlit_ace import st_ace
9
+ import copy
10
+
11
+ # Default configuration
12
+ default_config = {
13
+ "main_model": "llama3-70b-8192",
14
+ "cycles": 3,
15
+ "layer_agent_config": {}
16
+ }
17
+
18
+ layer_agent_config_def = {
19
+ "layer_agent_1": {
20
+ "system_prompt": "Think through your response step by step. {helper_response}",
21
+ "model_name": "llama3-8b-8192"
22
+ },
23
+ "layer_agent_2": {
24
+ "system_prompt": "Respond with a thought and then your response to the question. {helper_response}",
25
+ "model_name": "gemma-7b-it",
26
+ "temperature": 0.7
27
+ },
28
+ "layer_agent_3": {
29
+ "system_prompt": "You are an expert at logic and reasoning. Always take a logical approach to the answer. {helper_response}",
30
+ "model_name": "llama3-8b-8192"
31
+ },
32
+ }
33
+
34
+ # Recommended configuration
35
+ rec_config = {
36
+ "main_model": "llama3-70b-8192",
37
+ "cycles": 2,
38
+ "layer_agent_config": {}
39
+ }
40
+
41
+ layer_agent_config_rec = {
42
+ "layer_agent_1": {
43
+ "system_prompt": "Think through your response step by step. {helper_response}",
44
+ "model_name": "llama3-8b-8192",
45
+ "temperature": 0.1
46
+ },
47
+ "layer_agent_2": {
48
+ "system_prompt": "Respond with a thought and then your response to the question. {helper_response}",
49
+ "model_name": "llama3-8b-8192",
50
+ "temperature": 0.2
51
+ },
52
+ "layer_agent_3": {
53
+ "system_prompt": "You are an expert at logic and reasoning. Always take a logical approach to the answer. {helper_response}",
54
+ "model_name": "llama3-8b-8192",
55
+ "temperature": 0.4
56
+ },
57
+ "layer_agent_4": {
58
+ "system_prompt": "You are an expert planner agent. Create a plan for how to answer the human's query. {helper_response}",
59
+ "model_name": "mixtral-8x7b-32768",
60
+ "temperature": 0.5
61
+ },
62
+ }
63
+
64
+ # Unified streaming function to handle async and sync responses
65
+ async def stream_or_async_response(messages: Union[Iterable[ResponseChunk], AsyncIterable[ResponseChunk]]):
66
+ layer_outputs = {}
67
+
68
+ async def process_message(message):
69
+ if message['response_type'] == 'intermediate':
70
+ layer = message['metadata']['layer']
71
+ if layer not in layer_outputs:
72
+ layer_outputs[layer] = []
73
+ layer_outputs[layer].append(message['delta'])
74
+ else:
75
+ for layer, outputs in layer_outputs.items():
76
+ st.write(f"Layer {layer}")
77
+ cols = st.columns(len(outputs))
78
+ for i, output in enumerate(outputs):
79
+ with cols[i]:
80
+ st.expander(label=f"Agent {i+1}", expanded=False).write(output)
81
+
82
+ layer_outputs.clear()
83
+ yield message['delta']
84
+
85
+ if isinstance(messages, AsyncIterable):
86
+ # Process asynchronous messages
87
+ async for message in messages:
88
+ await process_message(message)
89
+ else:
90
+ # Process synchronous messages
91
+ for message in messages:
92
+ await process_message(message)
93
+
94
+ # Set up the MOAgent
95
+ def set_moa_agent(
96
+ main_model: str = default_config['main_model'],
97
+ cycles: int = default_config['cycles'],
98
+ layer_agent_config: dict[dict[str, any]] = copy.deepcopy(layer_agent_config_def),
99
+ main_model_temperature: float = 0.1,
100
+ override: bool = False
101
+ ):
102
+ if override or ("main_model" not in st.session_state):
103
+ st.session_state.main_model = main_model
104
+
105
+ if override or ("cycles" not in st.session_state):
106
+ st.session_state.cycles = cycles
107
+
108
+ if override or ("layer_agent_config" not in st.session_state):
109
+ st.session_state.layer_agent_config = layer_agent_config
110
+
111
+ if override or ("main_temp" not in st.session_state):
112
+ st.session_state.main_temp = main_model_temperature
113
+
114
+ cls_ly_conf = copy.deepcopy(st.session_state.layer_agent_config)
115
+
116
+ if override or ("moa_agent" not in st.session_state):
117
+ st.session_state.moa_agent = MOAgent.from_config(
118
+ main_model=st.session_state.main_model,
119
+ cycles=st.session_state.cycles,
120
+ layer_agent_config=cls_ly_conf,
121
+ temperature=st.session_state.main_temp
122
+ )
123
+
124
+ del cls_ly_conf
125
+ del layer_agent_config
126
+
127
+ # Streamlit app layout
128
+ st.set_page_config(
129
+ page_title="Mixture of Agents",
130
+ menu_items={
131
+ 'About': "## Groq Mixture-Of-Agents \n Powered by [Groq](https://groq.com)"
132
+ },
133
+ layout="wide"
134
+ )
135
+ valid_model_names = [
136
+ 'llama3-70b-8192',
137
+ 'llama3-8b-8192',
138
+ 'gemma-7b-it',
139
+ 'gemma2-9b-it',
140
+ 'mixtral-8x7b-32768'
141
+ ]
142
+
143
+ st.markdown("<a href='https://groq.com'><img src='app/static/banner.png' width='500'></a>", unsafe_allow_html=True)
144
+ st.write("---")
145
+
146
+ # Initialize session state
147
+ if "messages" not in st.session_state:
148
+ st.session_state.messages = []
149
+
150
+ set_moa_agent()
151
+
152
+ # Sidebar for configuration
153
+ with st.sidebar:
154
+ st.title("MOA Configuration")
155
+ with st.form("Agent Configuration", border=False):
156
+ if st.form_submit_button("Use Recommended Config"):
157
+ try:
158
+ set_moa_agent(
159
+ main_model=rec_config['main_model'],
160
+ cycles=rec_config['cycles'],
161
+ layer_agent_config=layer_agent_config_rec,
162
+ override=True
163
+ )
164
+ st.session_state.messages = []
165
+ st.success("Configuration updated successfully!")
166
+ except Exception as e:
167
+ st.error(f"Error updating configuration: {str(e)}")
168
+
169
+ # Main model selection
170
+ new_main_model = st.selectbox(
171
+ "Select Main Model",
172
+ options=valid_model_names,
173
+ index=valid_model_names.index(st.session_state.main_model)
174
+ )
175
+
176
+ # Cycles input
177
+ new_cycles = st.number_input(
178
+ "Number of Layers",
179
+ min_value=1,
180
+ max_value=10,
181
+ value=st.session_state.cycles
182
+ )
183
+
184
+ # Main Model Temperature
185
+ main_temperature = st.number_input(
186
+ label="Main Model Temperature",
187
+ value=0.1,
188
+ min_value=0.0,
189
+ max_value=1.0,
190
+ step=0.1
191
+ )
192
+
193
+ # Layer agent configuration
194
+ new_layer_agent_config = st_ace(
195
+ value=json.dumps(st.session_state.layer_agent_config, indent=2),
196
+ language='json',
197
+ placeholder="Layer Agent Configuration (JSON)",
198
+ show_gutter=False,
199
+ wrap=True,
200
+ auto_update=True
201
+ )
202
+
203
+ if st.form_submit_button("Update Configuration"):
204
+ try:
205
+ new_layer_config = json.loads(new_layer_agent_config)
206
+ set_moa_agent(
207
+ main_model=new_main_model,
208
+ cycles=new_cycles,
209
+ layer_agent_config=new_layer_config,
210
+ main_model_temperature=main_temperature,
211
+ override=True
212
+ )
213
+ st.session_state.messages = []
214
+ st.success("Configuration updated successfully!")
215
+ except Exception as e:
216
+ st.error(f"Error updating configuration: {str(e)}")
217
+
218
+ # Main app layout
219
+ st.header("Mixture of Agents")
220
+ st.write("This project oversees implementation of Mixture of Agents architecture powered by Groq LLMs.")
221
+
222
+ # Display current configuration
223
+ with st.expander("Current MOA Configuration", expanded=False):
224
+ st.markdown(f"**Main Model**: `{st.session_state.main_model}`")
225
+ st.markdown(f"**Main Model Temperature**: `{st.session_state.main_temp:.1f}`")
226
+ st.markdown(f"**Layers**: `{st.session_state.cycles}`")
227
+ st.markdown("**Layer Agents Config:**")
228
+ st_ace(
229
+ value=json.dumps(st.session_state.layer_agent_config, indent=2),
230
+ language='json',
231
+ placeholder="Layer Agent Configuration (JSON)",
232
+ show_gutter=False,
233
+ wrap=True,
234
+ readonly=True,
235
+ auto_update=True
236
+ )
237
+
238
+ # Chat interface
239
+ for message in st.session_state.messages:
240
+ with st.chat_message(message["role"]):
241
+ st.markdown(message["content"])
242
+
243
+ if query := st.chat_input("Ask a question"):
244
+ async def handle_query():
245
+ st.session_state.messages.append({"role": "user", "content": query})
246
+ with st.chat_message("user"):
247
+ st.write(query)
248
+
249
+ moa_agent: MOAgent = st.session_state.moa_agent
250
+
251
+ with st.chat_message("assistant"):
252
+ message_placeholder = st.empty()
253
+ messages = moa_agent.chat(query, output_format='json')
254
+ async for response in stream_or_async_response(messages):
255
+ message_placeholder.markdown(response)
256
+
257
+ st.session_state.messages.append({"role": "assistant", "content": response})
258
+
259
+ asyncio.run(handle_query())
260
+
261
+
262
+ # Add acknowledgment at the bottom
263
+ st.markdown("---")
264
+ st.markdown("""
265
+ ###
266
+ This app is based on [Emmanuel M. Ndaliro's work](https://github.com/kram254/Mixture-of-Agents-running-on-Groq/tree/main).
267
+ """)