Support OpenAI-compatible inference endpoints
This commit is contained in:
+121
-1
@@ -109,7 +109,7 @@ struct Ollama: InferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private static let session: URLSession = {
|
||||
fileprivate static let session: URLSession = {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 120
|
||||
config.timeoutIntervalForResource = 7200
|
||||
@@ -225,3 +225,123 @@ struct Ollama: InferenceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CompatibleEndpoint: InferenceProvider {
|
||||
private let base: URL
|
||||
private let token: String
|
||||
|
||||
init(endpoint: String, token: String = "") throws {
|
||||
guard let components = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
|
||||
let host = components.host?.lowercased(), !host.isEmpty,
|
||||
components.user == nil, components.password == nil, components.query == nil,
|
||||
components.fragment == nil, let url = components.url else {
|
||||
throw StudioError("Enter a base URL including its API path, such as http://127.0.0.1:1234/v1.")
|
||||
}
|
||||
let local = ["localhost", "127.0.0.1", "::1", "[::1]"].contains(host)
|
||||
guard components.scheme?.lowercased() == "https" || (local && components.scheme?.lowercased() == "http") else {
|
||||
throw StudioError("Use HTTPS for a remote compatible endpoint.")
|
||||
}
|
||||
guard !token.contains(where: \.isNewline) else { throw StudioError("The token must be a single line.") }
|
||||
base = url
|
||||
self.token = token
|
||||
}
|
||||
|
||||
struct Body: Encodable {
|
||||
struct ResponseFormat: Encodable { let type = "json_object" }
|
||||
let model: String
|
||||
let messages: [Ollama.WireMessage]
|
||||
let stream = true
|
||||
let temperature: Double?
|
||||
let max_tokens: Int?
|
||||
let top_p: Double?
|
||||
let frequency_penalty: Double?
|
||||
let presence_penalty: Double?
|
||||
let stop: [String]?
|
||||
let response_format: ResponseFormat?
|
||||
|
||||
init(_ request: InferenceRequest) {
|
||||
model = request.model
|
||||
messages = request.messages.map { .init(role: $0.role, content: $0.content) }
|
||||
let options = request.parameters
|
||||
temperature = options.temperature
|
||||
max_tokens = options.maxTokens
|
||||
top_p = options.topP
|
||||
frequency_penalty = options.frequencyPenalty
|
||||
presence_penalty = options.presencePenalty
|
||||
stop = options.stop.isEmpty ? nil : options.stop
|
||||
response_format = options.json ? ResponseFormat() : nil
|
||||
}
|
||||
}
|
||||
|
||||
private struct Frame: Decodable {
|
||||
struct Failure: Decodable { let message: String }
|
||||
struct Choice: Decodable {
|
||||
struct Piece: Decodable {
|
||||
let content: String?
|
||||
let reasoning_content: String?
|
||||
let reasoning: String?
|
||||
let tool_calls: [Ollama.Frame.ToolCall]?
|
||||
}
|
||||
let delta: Piece?
|
||||
let finish_reason: String?
|
||||
}
|
||||
let error: Failure?
|
||||
let choices: [Choice]?
|
||||
}
|
||||
|
||||
func models() async throws -> [String] {
|
||||
struct Response: Decodable {
|
||||
struct Entry: Decodable { let id: String }
|
||||
let data: [Entry]
|
||||
}
|
||||
let (data, response) = try await Ollama.session.data(for: urlRequest("models"))
|
||||
try validate(response)
|
||||
return Array(Set(try JSONDecoder().decode(Response.self, from: data).data.map(\.id))).sorted()
|
||||
}
|
||||
|
||||
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
||||
streaming { continuation in
|
||||
var wire = urlRequest("chat/completions")
|
||||
wire.httpMethod = "POST"
|
||||
wire.httpBody = try JSONEncoder().encode(Body(request))
|
||||
wire.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
wire.setValue("text/event-stream", forHTTPHeaderField: "Accept")
|
||||
let (bytes, response) = try await Ollama.session.bytes(for: wire)
|
||||
try validate(response)
|
||||
continuation.yield(.backend("Compatible API · \(request.model)"))
|
||||
var terminal = false
|
||||
for try await line in bytes.lines where line.hasPrefix("data:") {
|
||||
try Task.checkCancellation()
|
||||
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if payload == "[DONE]" { return }
|
||||
if payload.isEmpty { continue }
|
||||
let frame = try JSONDecoder().decode(Frame.self, from: Data(payload.utf8))
|
||||
if let error = frame.error { throw StudioError(error.message) }
|
||||
guard let choice = frame.choices?.first else { continue }
|
||||
if choice.finish_reason == "tool_calls" || !(choice.delta?.tool_calls ?? []).isEmpty {
|
||||
continuation.yield(.committed)
|
||||
throw StudioError("The endpoint returned a tool call. Run tools from Settings.")
|
||||
}
|
||||
if let text = choice.delta?.reasoning_content ?? choice.delta?.reasoning, !text.isEmpty {
|
||||
continuation.yield(.thinking(text))
|
||||
}
|
||||
if let text = choice.delta?.content, !text.isEmpty { continuation.yield(.answer(text)) }
|
||||
terminal = terminal || choice.finish_reason != nil
|
||||
}
|
||||
if !terminal { throw StudioError("The compatible endpoint disconnected before completing the response.") }
|
||||
}
|
||||
}
|
||||
|
||||
private func urlRequest(_ path: String) -> URLRequest {
|
||||
var request = URLRequest(url: base.appending(path: path))
|
||||
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
||||
return request
|
||||
}
|
||||
|
||||
private func validate(_ response: URLResponse) throws {
|
||||
guard let http = response as? HTTPURLResponse else { throw StudioError("Invalid compatible endpoint response.") }
|
||||
guard (200..<300).contains(http.statusCode) else {
|
||||
throw StudioError("Compatible endpoint returned HTTP \(http.statusCode).")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user