-
Notifications
You must be signed in to change notification settings - Fork 929
Expand file tree
/
Copy pathexamples.js
More file actions
91 lines (79 loc) · 3.02 KB
/
Copy pathexamples.js
File metadata and controls
91 lines (79 loc) · 3.02 KB
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
import { cosineSimilarity } from './math.js';
import { stringifyTurns, wordOverlapScore } from './text.js';
import { embedWithProgress } from './rate_limiter.js';
export class Examples {
constructor(model, select_num=2, cacheKey='examples') {
this.examples = [];
this.model = model;
this.select_num = select_num;
this.embeddings = {};
this.cacheKey = cacheKey;
}
turnsToText(turns) {
let messages = '';
for (let turn of turns) {
if (turn.role !== 'assistant')
messages += turn.content.substring(turn.content.indexOf(':')+1).trim() + '\n';
}
return messages.trim();
}
async load(examples) {
this.examples = examples;
if (!this.model) return; // Early return if no embedding model
if (this.select_num === 0)
return;
try {
const textsToEmbed = examples.map(example => this.turnsToText(example));
const modelName = this.model.model_name || this.model.constructor?.name || 'unknown';
const embeddings = await embedWithProgress(
textsToEmbed,
async (text) => await this.model.embed(text),
this.cacheKey,
{
cacheKey: this.cacheKey,
modelName: modelName,
getTextFn: (text) => text
}
);
for (const [text, embedding] of embeddings) {
this.embeddings[text] = embedding;
}
} catch (err) {
console.warn('Error with embedding model, using word-overlap instead.');
this.model = null;
}
}
async getRelevant(turns) {
if (this.select_num === 0)
return [];
let turn_text = this.turnsToText(turns);
if (this.model !== null) {
let embedding = await this.model.embed(turn_text);
this.examples.sort((a, b) =>
cosineSimilarity(embedding, this.embeddings[this.turnsToText(b)]) -
cosineSimilarity(embedding, this.embeddings[this.turnsToText(a)])
);
}
else {
this.examples.sort((a, b) =>
wordOverlapScore(turn_text, this.turnsToText(b)) -
wordOverlapScore(turn_text, this.turnsToText(a))
);
}
let selected = this.examples.slice(0, this.select_num);
return JSON.parse(JSON.stringify(selected)); // deep copy
}
async createExampleMessage(turns) {
let selected_examples = await this.getRelevant(turns);
console.log('selected examples:');
for (let example of selected_examples) {
console.log('Example:', example[0].content)
}
let msg = 'Examples of how to respond:\n';
for (let i=0; i<selected_examples.length; i++) {
let example = selected_examples[i];
msg += `Example ${i+1}:\n${stringifyTurns(example)}\n\n`;
}
return msg;
}
}