-
Notifications
You must be signed in to change notification settings - Fork 7
/
Saddle.js
104 lines (91 loc) · 2.44 KB
/
Saddle.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
class Saddle {
constructor(config) {
this.service = config.service || "ollama"
this.model = config.model || "zephyr:latest"
this.port = config.port || "11434"
this.temperature = config.temperature || 0.5
this.maxTokens = config.maxTokens || 6000
this.sendMemory = config.sendMemory || true
this.context = null
this.stream = ""
}
api(action = "generate") {
return `http://localhost:${this.port}/api/${action}`
}
async streamer(prompt, cummilatorCallback, contextCallback = () => null) {
this.stream = ""
await this.send(prompt).then(r =>
this.handleStream(r, fragment => {
if (fragment.done) {
this.context = fragment.context
contextCallback(this.context)
} else {
this.stream += fragment.response
const formattedText = DOMPurify.sanitize(marked.parse(this.stream))
cummilatorCallback(formattedText)
}
})
)
}
async run(prompt) {
this.stream = ""
await this.send(prompt).then(r =>
this.handleStream(r, f => this.processFragment(f))
)
return this.stream
}
processFragment(fragment) {
if (fragment.done) {
this.context = fragment.context
} else {
this.stream += fragment.response
this.stream = DOMPurify.sanitize(marked.parse(this.stream))
return this.stream
}
}
async list() {
return (
await fetch(this.api("tags"), {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then(r => r.json())
.then(j => j["models"])
).map(i => i["name"])
}
send(prompt, signal = null) {
const data = {
model: this.model,
context: this.context,
prompt: prompt,
temperature: this.temperature,
max_tokens: this.maxTokens,
send_memory: this.sendMemory,
}
return fetch(this.api(), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
signal: signal,
})
}
async handleStream(stream, callback) {
const reader = stream.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
const text = new TextDecoder().decode(value)
text.split("\n").forEach(t => {
if (t.trim() !== "") {
const parsed = JSON.parse(t)
callback(parsed)
}
})
}
}
}
window.Saddle = Saddle