Skip to content

Commit

Permalink
feat: add ollama api
Browse files Browse the repository at this point in the history
  • Loading branch information
rhinoc committed Jul 20, 2024
1 parent 155b627 commit c50ad70
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 2 deletions.
4 changes: 4 additions & 0 deletions liltr.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
12F1730A2C4B9566009FD444 /* Ollama.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12F173092C4B9566009FD444 /* Ollama.swift */; };
2B0437D22B79D5D800792E8B /* AppleScript.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B0437D12B79D5D800792E8B /* AppleScript.swift */; };
2B0437D42B79E2F000792E8B /* Pasteboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B0437D32B79E2F000792E8B /* Pasteboard.swift */; };
2B0437D62B79E34900792E8B /* SelectedText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B0437D52B79E34900792E8B /* SelectedText.swift */; };
Expand Down Expand Up @@ -59,6 +60,7 @@
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
12F173092C4B9566009FD444 /* Ollama.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ollama.swift; sourceTree = "<group>"; };
2B0437D12B79D5D800792E8B /* AppleScript.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleScript.swift; sourceTree = "<group>"; };
2B0437D32B79E2F000792E8B /* Pasteboard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Pasteboard.swift; sourceTree = "<group>"; };
2B0437D52B79E34900792E8B /* SelectedText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SelectedText.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -228,6 +230,7 @@
2B7CF3002B75BCB400BFA0BA /* Volcengine.swift */,
2B7CF2FE2B75BCB400BFA0BA /* AppleDictionary.swift */,
2B7CF2FF2B75BCB400BFA0BA /* ProviderManager.swift */,
12F173092C4B9566009FD444 /* Ollama.swift */,
);
path = Provider;
sourceTree = "<group>";
Expand Down Expand Up @@ -415,6 +418,7 @@
2B0437D62B79E34900792E8B /* SelectedText.swift in Sources */,
2B7CF38E2B75C00400BFA0BA /* TranslateFieldView.swift in Sources */,
2B7CF31C2B75BCB400BFA0BA /* NiuTrans.swift in Sources */,
12F1730A2C4B9566009FD444 /* Ollama.swift in Sources */,
2B7CF31F2B75BCB400BFA0BA /* ProviderManager.swift in Sources */,
2B7CF31A2B75BCB400BFA0BA /* BigHugeThesaurus.swift in Sources */,
2B7CF3242B75BCB400BFA0BA /* extensions.swift in Sources */,
Expand Down
6 changes: 6 additions & 0 deletions liltr/Settings/ProvidersView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ struct ProvidersView: View {

@Default(\.BigHugeThesaurusSK) var bigHugeThesaurusSK

@Default(\.OllamaAPI) var ollamaApi
@Default(\.OllamaModel) var ollamaModel

@Default(\.dictionary) var dictionary

private let _gapSize: CGFloat = 8
Expand Down Expand Up @@ -102,6 +105,9 @@ struct ProvidersView: View {
ProviderKeyField(label: "Baidu", icon: "4.square", ak: $baiduAK, sk: $baiduSK)

ProviderKeyField(label: "BigHugeThesaurus", icon: "5.square", sk: $bigHugeThesaurusSK)

ProviderKeyField(label: "Ollama", icon: "6.square", ak: $ollamaApi, sk: $ollamaModel)

}).padding(EdgeInsets(top: 0, leading: _gapSize * 2, bottom: 0, trailing: _gapSize * 2))
}
.frame(width: 500, height: 220)
Expand Down
70 changes: 70 additions & 0 deletions liltr/Utils/Provider/Ollama.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import Alamofire
import Foundation

struct OllamaResult: Decodable {
let role: String
let content: String
}

struct OllamaResponse: BaseResponse {
let model: String
let created_at: String
let message: OllamaResult
let done: Bool

var target: String? {
return message.content
}

var errorMessage: String? {
return nil
}
}

let OllamaProviderName = "Ollama"

class OllamaProvider: BaseProvider {
static let shared = OllamaProvider()
let delay: DispatchTimeInterval = .seconds(1)
let name = OllamaProviderName

var apiUrl: String {
return Defaults.shared.OllamaAPI.isEmpty ? "http://localhost:11434/api/chat" : Defaults.shared.OllamaAPI
}

var model: String {
return Defaults.shared.OllamaModel.isEmpty ? "qwen2" : Defaults.shared.OllamaModel
}

func translate(source: String, from: Language, to: Language, cb: @escaping (_ target: String, _ _sourceLanguage: Language?, _ _targetLanguage: Language?) -> Void) {
let prompt = "Assuming you are a seasoned translator, please translate the following source text to \(to.name) as target language, ensuring accuracy while trying to retain emotion and natural flow. Your response should ONLY contain the translated result.\n The source text is: ```\(source)```"
let parameters: [String: Any] = [
"model": model,
"stream": false,
"messages": [
[
"role": "user",
"content": prompt
]
],
]

debugPrint("[OllamaProvider] parameters:", parameters)

AF.request(apiUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.cacheResponse(using: .cache)
.cURLDescription(calling: { curl in
print(curl)
})
.responseDecodable(of: OllamaResponse.self) { response in
if response.error != nil {
cb(response.error!.errorDescription!, nil, nil)
} else if response.value?.errorMessage != nil {
cb(response.value!.errorMessage!, nil, nil)
} else {
cb(response.value!.target!, from, to)
}
}
}

}
11 changes: 9 additions & 2 deletions liltr/Utils/Provider/ProviderManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ protocol BaseResponse: Decodable {
var errorMessage: String? { get }
}

let PROVIDER_ARRAY: [any BaseProvider] = [NiuTransProvider.shared, BaiduProvider.shared, VolcengineProvider.shared, AliProvider.shared, AppleDictionaryProvider.shared, BigHugeThesaurusProvider.shared]
let PROVIDER_ARRAY: [any BaseProvider] = [NiuTransProvider.shared, BaiduProvider.shared, VolcengineProvider.shared, AliProvider.shared, AppleDictionaryProvider.shared, BigHugeThesaurusProvider.shared, OllamaProvider.shared]
let PROVIDER_DICT: [String: any BaseProvider] = Dictionary(uniqueKeysWithValues: PROVIDER_ARRAY.map { ($0.name, $0) })

struct ProviderCallbackData {
Expand Down Expand Up @@ -70,7 +70,14 @@ class ProviderManager: ObservableObject {
if query == curQuery {
let data = ProviderCallbackData(target, source, sourceLanguage: _sourceLanguage, targetLanguage: _targetLanguage?.name == _sourceLanguage?.name ? nil : _targetLanguage, providerName: cur.name)
cb(data)
resultCache[query] = data

if _sourceLanguage == nil && _targetLanguage == nil {
// if is error
} else {
// if not error
resultCache[query] = data
}

isTranslating = false
curQuery = ""
}
Expand Down
3 changes: 3 additions & 0 deletions liltr/userDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ public class Defaults: ObservableObject {
@AppStorage("\(AliProviderName)SK") public var AliSK = ""
// big huge
@AppStorage("\(BigHugeThesaurusProviderName)SK") public var BigHugeThesaurusSK = ""
// ollama
@AppStorage("\(OllamaProviderName)API") public var OllamaAPI = ""
@AppStorage("\(OllamaProviderName)Model") public var OllamaModel = ""

// MARK: Dictionary
@AppStorage("dictionary") public var dictionary = DCSOxfordDictionaryOfEnglish
Expand Down

0 comments on commit c50ad70

Please sign in to comment.