-
Notifications
You must be signed in to change notification settings - Fork 11
/
moa.js
268 lines (241 loc) · 9.17 KB
/
moa.js
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
/**
* @file examples/moa/moa.js
* @description Example showing use of Mixture of Agents (MoA) (https://www.together.ai/blog/together-moa) to improve response quality. In this example, three LLM providers are used. Gemini is used as the Proposer and the Aggregator. Gemini, Hugging Face, and Groq are used as the Agents. The Proposer attempts to break down a simplePrompt into supporting questions, then the Agents answer the questions, and the Aggregator synthesizes a final response. Upon completion of synthesis, a control response is requested from Gemini. Finally, Gemini is used to evaluate the differences between both responses and provide a report. The example can be run in two modes, 'fast' or 'comprehensive'; in 'fast' mode, the questions are spread across the LLM providers, in 'comprehensive' mode, every LLM provider must answer every question. The number of questions can vary, which may require multiple Agent requests.
*
* To run this example, you will need to install the required packages:
*
* npm install markdown-to-text readline dotenv
*/
const { LLMInterface } = require('../../src/index.js');
const {
startTimer,
endTimer,
compareSpeeds,
} = require('../../src/utils/timer.js');
const { getProposerResponse } = require('./utils/proposer');
const { compareResponses } = require('./utils/comparer');
const {
getMoaResponsesFast,
getMoaResponsesComprehensive,
} = require('./utils/moa');
const { getAggregatorResponse } = require('./utils/aggregator');
const { getControlResponse } = require('./utils/control');
const { removeMarkdownColor } = require('./utils/markdown');
const {
prettyHeader,
prettyText,
GREEN,
YELLOW,
RESET,
} = require('../../src/utils/utils.js');
const { getModelByAlias } = require('../../src/utils/config.js');
const readline = require('readline');
require('dotenv').config({ path: '../../.env' });
// Run modes
const runMode = ['Comprehensive', 'Fast'];
// Setup roles
const proposer = 'gemini';
const moas = ['huggingface', 'groq', 'gemini'];
const aggregator = 'gemini';
const control = 'gemini';
const comparer = 'gemini';
// Setup API keys
LLMInterface.setApiKey({
huggingface: process.env.HUGGINGFACE_API_KEY,
groq: process.env.GROQ_API_KEY,
gemini: process.env.GEMINI_API_KEY,
});
// Setup concurrency
const max_concurrent_moas = 2;
// Example description
const description = `Example showing use of Mixture of Agents (MoA) (https://www.together.ai/blog/together-moa) to improve response quality. The value of MoA increases significantly with the addition of more agents and responses.
Sure! Here’s a shortened version:
Leveraging diverse language models from multiple providers, each agent brings unique strengths, enhancing the quality and robustness of responses. Increasing the number of responses improves corpus comprehensiveness and coverage, ensuring diverse viewpoints and a more accurate, reliable synthesized output.
In this example, three LLM providers are used. Gemini is used as the Proposer and the Aggregator. Gemini, Hugging Face, and Groq are used as the Agents. The Proposer attempts to break down a simplePrompt into supporting questions, then the Agents answer the questions, and the Aggregator synthesizes a final MoA response. Upon completion of the MoA workflow, a control response is requested from Gemini, then Gemini is used again to evaluate the differences between both responses and provide a report.
The example can be run in two modes, 'fast' or 'comprehensive'; in 'fast' mode, the questions are spread across the LLM providers, in 'comprehensive' mode, every LLM provider must answer every question. Running the example in the two modes can highlight the value of increasing the number of providers and responses.
To run this example, you will need to install the required packages:
npm install markdown-to-text readline dotenv`;
/**
* Main exampleUsage() function.
* @param {string} [mode='Fast'] - The mode of execution, either 'fast' or 'comprehensive'.
* @returns {Promise<void>}
*/
async function exampleUsage(mode = 'Fast') {
console.time('Timer (All)');
prettyHeader(
`Mixture of Agents (MoA) in '${mode}' mode Example`,
description,
);
const aggStartTimer = startTimer();
console.time('Timer');
let questionsArray = [];
const proposerQuestions = await getProposerResponse(proposer);
if (proposerQuestions) {
questionsArray = proposerQuestions.map((q) => q.question);
const questionsString = questionsArray.join('\n');
console.log(`> ${questionsString.replaceAll('\n', '\n> ')}\n`);
} else {
console.error("Error: Can't get questions from Proposer");
return;
}
console.timeEnd('Timer');
// Get MoA responses (supports two modes: 'fast' and 'comprehensive')
console.time('Timer');
prettyText(`\n${GREEN}Get MoA responses using '${mode}' mode${RESET}\n`);
mode === 'Fast'
? prettyText(
`${YELLOW}In 'fast' mode, each question will be answered once.${RESET}\n\n`,
)
: prettyText(
`${YELLOW}In 'comprehensive' mode, each question will be answered N times, with N being the number of Agents.${RESET}\n\n`,
);
let moaResponses = [];
if (mode === 'Fast') {
moaResponses = await getMoaResponsesFast(
moas,
questionsArray,
max_concurrent_moas,
);
} else if (mode === 'Comprehensive') {
moaResponses = await getMoaResponsesComprehensive(
moas,
questionsArray,
max_concurrent_moas,
);
}
console.log();
console.timeEnd('Timer');
// Get Aggregator response
console.time('Timer');
prettyText(
`\n${GREEN}Get Aggregator response using ${aggregator} and ${getModelByAlias(
aggregator,
'large',
)}${RESET}\n`,
);
prettyText(`${YELLOW}Using small model aggregated MoA responses${RESET}\n\n`);
const aggregatedFinalResponse = await getAggregatorResponse(
moaResponses,
aggregator,
);
if (aggregatedFinalResponse) {
process.stdout.write(
`\n> ${removeMarkdownColor(aggregatedFinalResponse).replaceAll(
'\n',
'\n> ',
)}`,
);
} else {
console.log("Error: Can't get aggregator response");
}
console.log('\n');
console.timeEnd('Timer');
console.log();
const aggEndTimer = endTimer(aggStartTimer, 'Timer (MoAs)');
console.log(`${aggEndTimer[0]}`);
// Get the control response
const controlStartTimer = startTimer();
prettyText(
`\n${GREEN}Get Control response using ${control} and ${getModelByAlias(
control,
'large',
)}${RESET}\n`,
);
const controlResponse = await getControlResponse(control);
if (controlResponse) {
process.stdout.write(
`\n> ${removeMarkdownColor(controlResponse).replaceAll('\n', '\n> ')}`,
);
} else {
console.log("Error: Can't get control response");
}
const controlEndTimer = endTimer(
controlStartTimer,
'Timer (Control Response)',
);
console.log(`\n${controlEndTimer[0]}`);
// Compare the results
if (aggregatedFinalResponse && controlResponse) {
console.time('Timer');
prettyText(
`\n${GREEN}Compare responses using ${comparer} and ${getModelByAlias(
comparer,
'default',
)}${RESET}\n`,
);
prettyText(
`${YELLOW}We are comparing small model aggregated MoA responses against a ${control} and ${getModelByAlias(
control,
'default',
)} (which is the largest available model) based response${RESET}\n`,
);
const comparison = await compareResponses(
aggregatedFinalResponse,
controlResponse,
comparer,
control,
);
if (comparison) {
process.stdout.write(
`\n> ${removeMarkdownColor(comparison).replaceAll('\n', '\n> ')}`,
);
} else {
console.log("Error: Can't get comparison response");
}
console.log('\n');
console.log(
`${compareSpeeds(
['MoA', aggEndTimer[1]],
['Control', controlEndTimer[1]],
)}\n`,
);
console.timeEnd('Timer');
console.log();
console.timeEnd('Timer (All)');
console.log();
}
}
// Create an interface for reading input from the process.stdin
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Function to display choices and prompt for input
function promptUser(callback) {
prettyHeader(`Mixture of Agents (MoA) Example`, description);
console.log('\n');
prettyText(`\n${GREEN}Select Mode:${RESET}\n\n`);
runMode.forEach((choice, index) => {
if (choice === 'Fast') {
prettyText(
`${index + 1
}.) ${YELLOW}Fast${RESET} ---------- 1 Responses For Each Question\n`,
);
} else {
prettyText(
`${index + 1}.) ${YELLOW}Comprehensive${RESET} - ${moas.length
} Responses For Each Question\n`,
);
}
});
console.log();
rl.question('Enter the number of your choice: ', (answer) => {
const choiceIndex = parseInt(answer, 10) - 1;
if (choiceIndex >= 0 && choiceIndex < runMode.length) {
rl.close();
callback(null, runMode[choiceIndex]);
} else {
console.log('Invalid choice. Please try again.');
promptUser(callback);
}
});
}
// Using the promptUser function with a callback
promptUser((err, selectedChoice) => {
if (err) {
console.error('Error:', err);
} else {
console.log();
exampleUsage(selectedChoice);
}
});