-
Notifications
You must be signed in to change notification settings - Fork 2
/
llama2.ts
196 lines (165 loc) · 5.05 KB
/
llama2.ts
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
import { ReadableByteStreamController, ReadableStream, UnderlyingByteSource } from 'stream/web'
import { FastifyLoggerInstance } from 'fastify'
import {
LLamaChatPromptOptions,
LlamaChatSession,
LlamaContext,
LlamaModel
} from 'node-llama-cpp'
import { AiProvider, ChatHistory, StreamChunkCallback } from './provider.js'
import { AiStreamEvent, encodeEvent } from './event.js'
interface ChunkQueueNode {
chunk: number[]
next?: ChunkQueueNode
}
class ChunkQueue {
private size: number = 0
private head?: ChunkQueueNode
private tail?: ChunkQueueNode
getSize (): number {
return this.size
}
push (chunk: number[]): void {
this.size++
const node: ChunkQueueNode = { chunk }
if (this.head === undefined || this.tail === undefined) {
this.head = node
this.tail = node
} else {
this.tail.next = node
this.tail = node
}
}
pop (): number[] | undefined {
if (this.head === undefined) {
return undefined
}
this.size--
const chunk = this.head.chunk
this.head = this.head.next
if (this.size === 0) {
this.tail = undefined
}
return chunk
}
}
class Llama2ByteSource implements UnderlyingByteSource {
type: 'bytes' = 'bytes'
session: LlamaChatSession
chunkCallback?: StreamChunkCallback
backloggedChunks: ChunkQueue = new ChunkQueue()
finished: boolean = false
controller?: ReadableByteStreamController
abortController: AbortController
constructor (session: LlamaChatSession, prompt: string, logger: FastifyLoggerInstance, chunkCallback?: StreamChunkCallback) {
this.session = session
this.chunkCallback = chunkCallback
this.abortController = new AbortController()
session.prompt(prompt, {
onToken: this.onToken,
signal: this.abortController.signal
}).then(() => {
this.finished = true
// Don't close the stream if we still have chunks to send
if (this.backloggedChunks.getSize() === 0 && this.controller !== undefined) {
this.controller.close()
}
}).catch((err: any) => {
this.finished = true
logger.info({ err })
if (!this.abortController.signal.aborted && this.controller !== undefined) {
try {
this.controller.close()
} catch (err) {
logger.info({ err })
}
}
})
}
cancel (): void {
this.abortController.abort()
}
onToken: LLamaChatPromptOptions['onToken'] = async (chunk) => {
if (this.controller === undefined) {
// Stream hasn't started yet, added it to the backlog queue
this.backloggedChunks.push(chunk)
return
}
try {
await this.clearBacklog()
await this.enqueueChunk(chunk)
// Ignore all errors, we can't do anything about them
// TODO: Log these errors
} catch (err) {
console.error(err)
}
}
private async enqueueChunk (chunk: number[]): Promise<void> {
if (this.controller === undefined) {
throw new Error('tried enqueueing chunk before stream started')
}
let response = this.session.context.decode(chunk)
if (this.chunkCallback !== undefined) {
response = await this.chunkCallback(response)
}
if (response === '') {
response = '\n' // It seems empty chunks are newlines
}
const eventData: AiStreamEvent = {
event: 'content',
data: {
response
}
}
this.controller.enqueue(encodeEvent(eventData))
if (this.backloggedChunks.getSize() === 0 && this.finished) {
this.controller.close()
}
}
async clearBacklog (): Promise<void> {
if (this.backloggedChunks.getSize() === 0) {
return
}
let backloggedChunk = this.backloggedChunks.pop()
while (backloggedChunk !== undefined) {
// Each chunk needs to be sent in order, can't run all of these at once
await this.enqueueChunk(backloggedChunk)
backloggedChunk = this.backloggedChunks.pop()
}
}
start (controller: ReadableByteStreamController): void {
this.controller = controller
this.clearBacklog().catch(err => {
throw err
})
}
}
interface Llama2ProviderCtorOptions {
modelPath: string
logger: FastifyLoggerInstance
}
export class Llama2Provider implements AiProvider {
model: LlamaModel
logger: FastifyLoggerInstance
constructor ({ modelPath, logger }: Llama2ProviderCtorOptions) {
this.model = new LlamaModel({ modelPath })
this.logger = logger
}
async ask (prompt: string, chatHistory?: ChatHistory): Promise<string> {
const context = new LlamaContext({ model: this.model })
const session = new LlamaChatSession({
context,
conversationHistory: chatHistory
})
const response = await session.prompt(prompt)
return response
}
async askStream (prompt: string, chunkCallback?: StreamChunkCallback, chatHistory?: ChatHistory): Promise<ReadableStream> {
const context = new LlamaContext({ model: this.model })
const session = new LlamaChatSession({
context,
conversationHistory: chatHistory
})
return new ReadableStream(new Llama2ByteSource(session, prompt, this.logger, chunkCallback))
}
}