new features
This commit is contained in:
@@ -394,6 +394,103 @@ struct CompatibleEndpoint: InferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
static func pluginIDs(_ text: String) -> [String] {
|
||||
var seen = Set<String>()
|
||||
return text.split(whereSeparator: { $0 == "," || $0.isWhitespace })
|
||||
.map { $0.hasPrefix("mcp/") ? String($0) : "mcp/\($0)" }
|
||||
.filter { $0.count > 4 && seen.insert($0).inserted }
|
||||
}
|
||||
|
||||
func generateWithPlugins(_ request: InferenceRequest, plugins: [String]) -> AsyncThrowingStream<Delta, Error> {
|
||||
streaming { continuation in
|
||||
guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw StudioError("Enter an LM Studio API token in Settings → Models to use installed plugins.")
|
||||
}
|
||||
var server = base
|
||||
if server.lastPathComponent == "v1" {
|
||||
server.deleteLastPathComponent()
|
||||
}
|
||||
var wire = URLRequest(url: server.appending(path: "api/v1/chat"))
|
||||
wire.httpMethod = "POST"
|
||||
wire.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
|
||||
wire.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
wire.setValue("text/event-stream", forHTTPHeaderField: "Accept")
|
||||
wire.httpBody = try JSONEncoder().encode(PluginChatBody(request, plugins: plugins))
|
||||
let (bytes, response) = try await Ollama.session.bytes(for: wire)
|
||||
try validate(response)
|
||||
continuation.yield(.backend("LM Studio Plugins · \(request.model)"))
|
||||
for try await line in bytes.lines where line.hasPrefix("data:") {
|
||||
try Task.checkCancellation()
|
||||
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !payload.isEmpty else { continue }
|
||||
let event = try JSONDecoder().decode(PluginChatEvent.self, from: Data(payload.utf8))
|
||||
switch event.type {
|
||||
case "message.delta":
|
||||
if let content = event.content { continuation.yield(.answer(content)) }
|
||||
case "reasoning.delta":
|
||||
if let content = event.content { continuation.yield(.thinking(content)) }
|
||||
case "tool_call.start":
|
||||
continuation.yield(.committed)
|
||||
case "error":
|
||||
throw StudioError(event.error?.message ?? "LM Studio plugin chat failed.")
|
||||
case "chat.end":
|
||||
if let stats = event.result?.stats, stats.total_output_tokens >= 0 {
|
||||
continuation.yield(.metrics(ProviderMetrics(tokens: stats.total_output_tokens, seconds: 0)))
|
||||
}
|
||||
return
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
throw StudioError("LM Studio disconnected before completing the plugin response.")
|
||||
}
|
||||
}
|
||||
|
||||
private struct PluginChatBody: Encodable {
|
||||
let model: String
|
||||
let input: String
|
||||
let system_prompt: String?
|
||||
let integrations: [String]
|
||||
let stream = true
|
||||
let store = false
|
||||
let temperature: Double?
|
||||
let top_p: Double?
|
||||
let max_output_tokens: Int?
|
||||
let context_length: Int?
|
||||
|
||||
init(_ request: InferenceRequest, plugins: [String]) {
|
||||
model = request.model
|
||||
integrations = plugins
|
||||
let system = request.messages.filter { $0.role == .system }.map(\.content)
|
||||
system_prompt = system.isEmpty ? nil : system.joined(separator: "\n\n")
|
||||
// Native chat accepts user input and a system prompt. Preserve prepared history as reference text.
|
||||
let conversation = request.messages.filter { $0.role != .system }
|
||||
let history = conversation.dropLast()
|
||||
if history.isEmpty {
|
||||
input = conversation.last?.content ?? ""
|
||||
} else {
|
||||
let transcript = history.map { "\($0.role.rawValue): \($0.content)" }.joined(separator: "\n\n")
|
||||
input = "Previous conversation for reference:\n\(transcript)\n\nLatest message:\n\(conversation.last?.content ?? "")"
|
||||
}
|
||||
temperature = request.parameters.temperature
|
||||
top_p = request.parameters.topP
|
||||
max_output_tokens = request.parameters.maxTokens
|
||||
context_length = request.parameters.context
|
||||
}
|
||||
}
|
||||
|
||||
private struct PluginChatEvent: Decodable {
|
||||
struct Failure: Decodable { let message: String }
|
||||
struct Result: Decodable {
|
||||
struct Stats: Decodable { let total_output_tokens: Int }
|
||||
let stats: Stats?
|
||||
}
|
||||
let type: String
|
||||
let content: String?
|
||||
let error: Failure?
|
||||
let result: Result?
|
||||
}
|
||||
|
||||
private func urlRequest(_ path: String) -> URLRequest {
|
||||
var request = URLRequest(url: base.appending(path: path))
|
||||
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
||||
|
||||
Reference in New Issue
Block a user