Elffuss BraidHub

kikocis/llama-stack public

29067f5f4b1c · 5.4 KiBRawPermalink
1import Foundation
2
3import LLaMARunner
4import LlamaStackClient
5
6class RunnerHolder: ObservableObject {
7 var runner: Runner?
8}
9
10public class LocalInference: Inference {
11 private var runnerHolder = RunnerHolder()
12 private let runnerQueue: DispatchQueue
13
14 public init (queue: DispatchQueue) {
15 runnerQueue = queue
16 }
17
18 public func loadModel(modelPath: String, tokenizerPath: String, completion: @escaping (Result<Void, Error>) -> Void) {
19 runnerHolder.runner = runnerHolder.runner ?? Runner(
20 modelPath: modelPath,
21 tokenizerPath: tokenizerPath
22 )
23
24
25 runnerQueue.async {
26 let runner = self.runnerHolder.runner
27 do {
28 try runner!.load()
29 completion(.success(()))
30 } catch let loadError {
31 print("error: " + loadError.localizedDescription)
32 completion(.failure(loadError))
33 }
34 }
35 }
36
37 public func chatCompletion(request: Components.Schemas.ChatCompletionRequest) -> AsyncStream<Components.Schemas.ChatCompletionResponseStreamChunk> {
38 return AsyncStream { continuation in
39 runnerQueue.async {
40 do {
41 var tokens: [String] = []
42
43 let prompt = try encodeDialogPrompt(messages: prepareMessages(request: request))
44 var stopReason: Components.Schemas.StopReason? = nil
45 var buffer = ""
46 var ipython = false
47 var echoDropped = false
48
49 try self.runnerHolder.runner?.generate(prompt, sequenceLength: 4096) { token in
50 buffer += token
51
52 // HACK: Workaround until LlamaRunner exposes echo param
53 if (!echoDropped) {
54 if (buffer.hasPrefix(prompt)) {
55 buffer = String(buffer.dropFirst(prompt.count))
56 echoDropped = true
57 }
58 return
59 }
60
61 tokens.append(token)
62
63 if !ipython && (buffer.starts(with: "<|python_tag|>") || buffer.starts(with: "[") ) {
64 ipython = true
65 continuation.yield(
66 Components.Schemas.ChatCompletionResponseStreamChunk(
67 event: Components.Schemas.ChatCompletionResponseEvent(
68 delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
69 content: .case1(""),
70 parse_status: Components.Schemas.ToolCallParseStatus.started
71 )
72 ),
73 event_type: .progress
74 )
75 )
76 )
77
78 if (buffer.starts(with: "<|python_tag|>")) {
79 buffer = String(buffer.dropFirst("<|python_tag|>".count))
80 }
81 }
82
83 // TODO: Non-streaming lobprobs
84
85 var text = ""
86 if token == "<|eot_id|>" {
87 stopReason = Components.Schemas.StopReason.end_of_turn
88 } else if token == "<|eom_id|>" {
89 stopReason = Components.Schemas.StopReason.end_of_message
90 } else {
91 text = token
92 }
93
94 var delta: Components.Schemas.ChatCompletionResponseEvent.deltaPayload
95 if ipython {
96 delta = .ToolCallDelta(Components.Schemas.ToolCallDelta(
97 content: .case1(text),
98 parse_status: .in_progress
99 ))
100 } else {
101 delta = .case1(text)
102 }
103
104 if stopReason == nil {
105 continuation.yield(
106 Components.Schemas.ChatCompletionResponseStreamChunk(
107 event: Components.Schemas.ChatCompletionResponseEvent(
108 delta: delta,
109 event_type: .progress
110 )
111 )
112 )
113 }
114 }
115
116 if stopReason == nil {
117 stopReason = Components.Schemas.StopReason.out_of_tokens
118 }
119
120 let message = decodeAssistantMessage(tokens: tokens.joined(), stopReason: stopReason!)
121 // TODO: non-streaming support
122
123 let didParseToolCalls = message.tool_calls.count > 0
124 if ipython && !didParseToolCalls {
125 continuation.yield(
126 Components.Schemas.ChatCompletionResponseStreamChunk(
127 event: Components.Schemas.ChatCompletionResponseEvent(
128 delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(content: .case1(""), parse_status: .failure)),
129 event_type: .progress
130 )
131 // TODO: stopReason
132 )
133 )
134 }
135
136 for toolCall in message.tool_calls {
137 continuation.yield(
138 Components.Schemas.ChatCompletionResponseStreamChunk(
139 event: Components.Schemas.ChatCompletionResponseEvent(
140 delta: .ToolCallDelta(Components.Schemas.ToolCallDelta(
141 content: .ToolCall(toolCall),
142 parse_status: .success
143 )),
144 event_type: .progress
145 )
146 // TODO: stopReason
147 )
148 )
149 }
150
151 continuation.yield(
152 Components.Schemas.ChatCompletionResponseStreamChunk(
153 event: Components.Schemas.ChatCompletionResponseEvent(
154 delta: .case1(""),
155 event_type: .complete
156 )
157 // TODO: stopReason
158 )
159 )
160 }
161 catch (let error) {
162 print("Inference error: " + error.localizedDescription)
163 }
164 }
165 }
166 }
167}