Spaces:
Sleeping
Sleeping
DrishtiShrrrma
commited on
Commit
β’
dda2773
1
Parent(s):
95df285
Added moa folder
Browse files- Mixture-of-Agents-running-on-Groq +1 -0
- moa/__init__.py +0 -0
- moa/agent/__init__.py +1 -0
- moa/agent/moa.py +181 -0
- moa/agent/prompts.py +15 -0
- moa/main.py +20 -0
Mixture-of-Agents-running-on-Groq
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 2a8a77223b8011554035137da207538f4683514c
|
moa/__init__.py
ADDED
File without changes
|
moa/agent/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .moa import MOAgent
|
moa/agent/moa.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Langchain agent
|
3 |
+
"""
|
4 |
+
from typing import Generator, Dict, Optional, Literal, TypedDict, List
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
|
7 |
+
from langchain_groq import ChatGroq
|
8 |
+
from langchain.memory import ConversationBufferMemory
|
9 |
+
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
|
10 |
+
from langchain_core.messages import BaseMessage
|
11 |
+
from langchain_core.runnables import RunnablePassthrough, RunnableLambda, RunnableSerializable
|
12 |
+
from langchain_core.output_parsers import StrOutputParser
|
13 |
+
|
14 |
+
from .prompts import SYSTEM_PROMPT, REFERENCE_SYSTEM_PROMPT
|
15 |
+
|
16 |
+
load_dotenv()
|
17 |
+
valid_model_names = Literal[
|
18 |
+
'llama3-70b-8192',
|
19 |
+
'llama3-8b-8192',
|
20 |
+
'gemma-7b-it',
|
21 |
+
'gemma2-9b-it',
|
22 |
+
'mixtral-8x7b-32768'
|
23 |
+
]
|
24 |
+
|
25 |
+
class ResponseChunk(TypedDict):
|
26 |
+
delta: str
|
27 |
+
response_type: Literal['intermediate', 'output']
|
28 |
+
metadata: Dict = {}
|
29 |
+
|
30 |
+
|
31 |
+
class MOAgent:
|
32 |
+
def __init__(
|
33 |
+
self,
|
34 |
+
main_agent: RunnableSerializable[Dict, str],
|
35 |
+
layer_agent: RunnableSerializable[Dict, Dict],
|
36 |
+
reference_system_prompt: Optional[str] = None,
|
37 |
+
cycles: Optional[int] = None,
|
38 |
+
chat_memory: Optional[ConversationBufferMemory] = None
|
39 |
+
) -> None:
|
40 |
+
self.reference_system_prompt = reference_system_prompt or REFERENCE_SYSTEM_PROMPT
|
41 |
+
self.main_agent = main_agent
|
42 |
+
self.layer_agent = layer_agent
|
43 |
+
self.cycles = cycles or 1
|
44 |
+
self.chat_memory = chat_memory or ConversationBufferMemory(
|
45 |
+
memory_key="messages",
|
46 |
+
return_messages=True
|
47 |
+
)
|
48 |
+
|
49 |
+
@staticmethod
|
50 |
+
def concat_response(
|
51 |
+
inputs: Dict[str, str],
|
52 |
+
reference_system_prompt: Optional[str] = None
|
53 |
+
):
|
54 |
+
reference_system_prompt = reference_system_prompt or REFERENCE_SYSTEM_PROMPT
|
55 |
+
|
56 |
+
responses = ""
|
57 |
+
res_list = []
|
58 |
+
for i, out in enumerate(inputs.values()):
|
59 |
+
responses += f"{i}. {out}\n"
|
60 |
+
res_list.append(out)
|
61 |
+
|
62 |
+
formatted_prompt = reference_system_prompt.format(responses=responses)
|
63 |
+
return {
|
64 |
+
'formatted_response': formatted_prompt,
|
65 |
+
'responses': res_list
|
66 |
+
}
|
67 |
+
|
68 |
+
@classmethod
|
69 |
+
def from_config(
|
70 |
+
cls,
|
71 |
+
main_model: Optional[valid_model_names] = 'llama3-70b-8192',
|
72 |
+
system_prompt: Optional[str] = None,
|
73 |
+
cycles: int = 1,
|
74 |
+
layer_agent_config: Optional[Dict] = None,
|
75 |
+
reference_system_prompt: Optional[str] = None,
|
76 |
+
**main_model_kwargs
|
77 |
+
):
|
78 |
+
reference_system_prompt = reference_system_prompt or REFERENCE_SYSTEM_PROMPT
|
79 |
+
system_prompt = system_prompt or SYSTEM_PROMPT
|
80 |
+
layer_agent = MOAgent._configure_layer_agent(layer_agent_config)
|
81 |
+
main_agent = MOAgent._create_agent_from_system_prompt(
|
82 |
+
system_prompt=system_prompt,
|
83 |
+
model_name=main_model,
|
84 |
+
**main_model_kwargs
|
85 |
+
)
|
86 |
+
return cls(
|
87 |
+
main_agent=main_agent,
|
88 |
+
layer_agent=layer_agent,
|
89 |
+
reference_system_prompt=reference_system_prompt,
|
90 |
+
cycles=cycles
|
91 |
+
)
|
92 |
+
|
93 |
+
@staticmethod
|
94 |
+
def _configure_layer_agent(
|
95 |
+
layer_agent_config: Optional[Dict] = None
|
96 |
+
) -> RunnableSerializable[Dict, Dict]:
|
97 |
+
if not layer_agent_config:
|
98 |
+
layer_agent_config = {
|
99 |
+
'layer_agent_1' : {'system_prompt': SYSTEM_PROMPT, 'model_name': 'llama3-8b-8192'},
|
100 |
+
'layer_agent_2' : {'system_prompt': SYSTEM_PROMPT, 'model_name': 'gemma-7b-it'},
|
101 |
+
'layer_agent_3' : {'system_prompt': SYSTEM_PROMPT, 'model_name': 'mixtral-8x7b-32768'}
|
102 |
+
}
|
103 |
+
|
104 |
+
parallel_chain_map = dict()
|
105 |
+
for key, value in layer_agent_config.items():
|
106 |
+
chain = MOAgent._create_agent_from_system_prompt(
|
107 |
+
system_prompt=value.pop("system_prompt", SYSTEM_PROMPT),
|
108 |
+
model_name=value.pop("model_name", 'llama3-8b-8192'),
|
109 |
+
**value
|
110 |
+
)
|
111 |
+
parallel_chain_map[key] = RunnablePassthrough() | chain
|
112 |
+
|
113 |
+
chain = parallel_chain_map | RunnableLambda(MOAgent.concat_response)
|
114 |
+
return chain
|
115 |
+
|
116 |
+
@staticmethod
|
117 |
+
def _create_agent_from_system_prompt(
|
118 |
+
system_prompt: str = SYSTEM_PROMPT,
|
119 |
+
model_name: str = "llama3-8b-8192",
|
120 |
+
**llm_kwargs
|
121 |
+
) -> RunnableSerializable[Dict, str]:
|
122 |
+
prompt = ChatPromptTemplate.from_messages([
|
123 |
+
("system", system_prompt),
|
124 |
+
MessagesPlaceholder(variable_name="messages", optional=True),
|
125 |
+
("human", "{input}")
|
126 |
+
])
|
127 |
+
|
128 |
+
assert 'helper_response' in prompt.input_variables
|
129 |
+
llm = ChatGroq(model=model_name, **llm_kwargs)
|
130 |
+
|
131 |
+
chain = prompt | llm | StrOutputParser()
|
132 |
+
return chain
|
133 |
+
|
134 |
+
def chat(
|
135 |
+
self,
|
136 |
+
input: str,
|
137 |
+
messages: Optional[List[BaseMessage]] = None,
|
138 |
+
cycles: Optional[int] = None,
|
139 |
+
save: bool = True,
|
140 |
+
output_format: Literal['string', 'json'] = 'string'
|
141 |
+
) -> Generator[str | ResponseChunk, None, None]:
|
142 |
+
cycles = cycles or self.cycles
|
143 |
+
llm_inp = {
|
144 |
+
'input': input,
|
145 |
+
'messages': messages or self.chat_memory.load_memory_variables({})['messages'],
|
146 |
+
'helper_response': ""
|
147 |
+
}
|
148 |
+
for cyc in range(cycles):
|
149 |
+
layer_output = self.layer_agent.invoke(llm_inp)
|
150 |
+
l_frm_resp = layer_output['formatted_response']
|
151 |
+
l_resps = layer_output['responses']
|
152 |
+
|
153 |
+
llm_inp = {
|
154 |
+
'input': input,
|
155 |
+
'messages': self.chat_memory.load_memory_variables({})['messages'],
|
156 |
+
'helper_response': l_frm_resp
|
157 |
+
}
|
158 |
+
|
159 |
+
if output_format == 'json':
|
160 |
+
for l_out in l_resps:
|
161 |
+
yield ResponseChunk(
|
162 |
+
delta=l_out,
|
163 |
+
response_type='intermediate',
|
164 |
+
metadata={'layer': cyc + 1}
|
165 |
+
)
|
166 |
+
|
167 |
+
stream = self.main_agent.stream(llm_inp)
|
168 |
+
response = ""
|
169 |
+
for chunk in stream:
|
170 |
+
if output_format == 'json':
|
171 |
+
yield ResponseChunk(
|
172 |
+
delta=chunk,
|
173 |
+
response_type='output',
|
174 |
+
metadata={}
|
175 |
+
)
|
176 |
+
else:
|
177 |
+
yield chunk
|
178 |
+
response += chunk
|
179 |
+
|
180 |
+
if save:
|
181 |
+
self.chat_memory.save_context({'input': input}, {'output': response})
|
moa/agent/prompts.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
SYSTEM_PROMPT = """\
|
2 |
+
You are a personal assistant that is helpful.
|
3 |
+
|
4 |
+
{helper_response}\
|
5 |
+
"""
|
6 |
+
|
7 |
+
REFERENCE_SYSTEM_PROMPT = """\
|
8 |
+
You have been provided with a set of responses from various open-source models to the latest user query.
|
9 |
+
Your task is to synthesize these responses into a single, high-quality response.
|
10 |
+
It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect.
|
11 |
+
Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction.
|
12 |
+
Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
|
13 |
+
Responses from models:
|
14 |
+
{responses}
|
15 |
+
"""
|
moa/main.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from agent import MOAgent
|
2 |
+
|
3 |
+
# Configure agent
|
4 |
+
layer_agent_config = {
|
5 |
+
'layer_agent_1' : {'system_prompt': "Think through your response with step by step {helper_response}", 'model_name': 'llama3-8b-8192'},
|
6 |
+
'layer_agent_2' : {'system_prompt': "Respond with a thought and then your response to the question {helper_response}", 'model_name': 'gemma-7b-it'},
|
7 |
+
'layer_agent_3' : {'model_name': 'llama3-8b-8192'},
|
8 |
+
'layer_agent_4' : {'model_name': 'gemma-7b-it'},
|
9 |
+
'layer_agent_5' : {'model_name': 'llama3-8b-8192'},
|
10 |
+
}
|
11 |
+
agent = MOAgent.from_config(
|
12 |
+
main_model='mixtral-8x7b-32768',
|
13 |
+
layer_agent_config=layer_agent_config
|
14 |
+
)
|
15 |
+
|
16 |
+
while True:
|
17 |
+
inp = input("\nAsk a question: ")
|
18 |
+
stream = agent.chat(inp, output_format='json')
|
19 |
+
for chunk in stream:
|
20 |
+
print(chunk)
|