Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: enable to customize OpenAI models #493

Merged
merged 15 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions Easydict.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,20 @@
path = AppleScript;
sourceTree = "<group>";
};
03071E1B2BC03ADE0042CD38 /* TabView */ = {
isa = PBXGroup;
children = (
278540332B3DE04F004E9488 /* GeneralTab.swift */,
0A057D6C2B499A000025C51D /* ServiceTab.swift */,
0A8685C72B552A590022534F /* DisabledAppTab.swift */,
276742042B3DC230002A2C75 /* PrivacyTab.swift */,
276742052B3DC230002A2C75 /* AboutTab.swift */,
96099AE12B5D40330055C4DD /* ShortcutTab.swift */,
03832F532B5F6BE200D0DC64 /* AdvancedTab.swift */,
);
path = TabView;
sourceTree = "<group>";
};
0309E1EA292B437C00AFB76A /* TextView */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -2229,15 +2243,9 @@
27FE980C2B3DD749000AD654 /* Tabs */ = {
isa = PBXGroup;
children = (
03071E1B2BC03ADE0042CD38 /* TabView */,
9627F9332B59956800B1E999 /* View */,
EAED41EA2B54A4900005FE0A /* ServiceConfiguration */,
278540332B3DE04F004E9488 /* GeneralTab.swift */,
0A057D6C2B499A000025C51D /* ServiceTab.swift */,
0A8685C72B552A590022534F /* DisabledAppTab.swift */,
276742042B3DC230002A2C75 /* PrivacyTab.swift */,
276742052B3DC230002A2C75 /* AboutTab.swift */,
96099AE12B5D40330055C4DD /* ShortcutTab.swift */,
03832F532B5F6BE200D0DC64 /* AdvancedTab.swift */,
EAED41EA2B54A4900005FE0A /* ServiceConfigurationView */,
);
path = Tabs;
sourceTree = "<group>";
Expand Down Expand Up @@ -2471,7 +2479,6 @@
038F1F8D2BAD835500CD2F65 /* AppKit */,
EA1013412B5DBDA5005E43F9 /* Defaults */,
038A723E2B62C07B004995E3 /* String */,
EAED41F02B54B1A60005FE0A /* QueryService+ConfigurableService */,
EA9943E72B534D8900EE7B97 /* LanguageDetectOptimizeExtensions.swift */,
EA9943ED2B5353AB00EE7B97 /* WindowTypeExtensions.swift */,
EA9943EF2B5354C400EE7B97 /* ShowWindowPositionExtensions.swift */,
Expand All @@ -2480,15 +2487,16 @@
path = Extensions;
sourceTree = "<group>";
};
EAED41EA2B54A4900005FE0A /* ServiceConfiguration */ = {
EAED41EA2B54A4900005FE0A /* ServiceConfigurationView */ = {
isa = PBXGroup;
children = (
EAED41F02B54B1A60005FE0A /* QueryService+ConfigurableService */,
0AC8A83C2B6685EE006DA5CC /* SecureTextField.swift */,
EAED41EB2B54AA920005FE0A /* ServiceConfigurationSection.swift */,
0AC8A8462B6A4E3F006DA5CC /* ServiceConfigurationSecretSectionView.swift */,
0AC8A8442B6A4D97006DA5CC /* ServiceConfigurationCells.swift */,
);
path = ServiceConfiguration;
path = ServiceConfigurationView;
sourceTree = "<group>";
};
EAED41ED2B54B1390005FE0A /* Protocol */ = {
Expand All @@ -2504,14 +2512,14 @@
isa = PBXGroup;
children = (
EAED41F12B54B39D0005FE0A /* OpenAIService+ConfigurableService.swift */,
0A318F3A2B8CCCCD0005EF77 /* CustomOpenAIService+ConfigurableService.swift */,
0AC8A8402B695480006DA5CC /* DeepLTranslate+ConfigurableService.swift */,
0AC8A8342B6641A7006DA5CC /* TencentService+ConfigurableService.swift */,
0AC8A8362B6659A8006DA5CC /* NiuTransTranslate+ConfigurableService.swift */,
0AC8A8382B666F07006DA5CC /* CaiyunService+ConfigurableService.swift */,
0AC8A83A2B6682D4006DA5CC /* AliService+ConfigurableService.swift */,
0AC8A8422B6957B0006DA5CC /* BingService+ConfigurableService.swift */,
0AC8A84A2B6A629D006DA5CC /* GeminiService+ConfigurableService.swift */,
0A318F3A2B8CCCCD0005EF77 /* CustomOpenAIService+ConfigurableService.swift */,
);
path = "QueryService+ConfigurableService";
sourceTree = "<group>";
Expand Down
4 changes: 2 additions & 2 deletions Easydict/App/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -3000,13 +3000,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Model"
"value" : "Use Model"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "模型"
"value" : "使用模型"
}
}
}
Expand Down
17 changes: 13 additions & 4 deletions Easydict/Swift/Feature/Configuration/Configuration+Defaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,15 @@ extension Defaults.Keys {
default: OpenAIUsageStats.default
)
static let openAIEndPoint = Key<String?>(EZOpenAIEndPointKey)
static let openAIModel = Key<OpenAIModel>(EZOpenAIModelKey, default: .gpt3_5_turbo_0125)
static let openAIModel = Key<String>(EZOpenAIModelKey, default: OpenAIModel.gpt3_5_turbo.rawValue)
static let openAIAvailableModels = Key<String?>(
EZOpenAIAvailableModelsKey,
default: OpenAIModel.allCases.map { $0.rawValue }.joined(separator: ",")
)
static let openAIVaildModels = Key<Array>(
EZOpenAIValidModelsKey,
default: OpenAIModel.allCases.map { $0.rawValue }
)

// Custom OpenAI
static let customOpenAINameKey = Key<String?>(
Expand All @@ -218,9 +226,10 @@ extension Defaults.Keys {
)
static let customOpenAIEndPoint = Key<String?>(EZCustomOpenAIEndPointKey, default: "")
static let customOpenAIModel = Key<String>(EZCustomOpenAIModelKey, default: "")
static let customOpenAIModelsAvailable = Key<String?>(
EZCustomOpenAIModelssAvailableKey,
default: ""
static let customOpenAIAvailableModels = Key<String?>(EZCustomOpenAIAvailableModelsKey, default: "")
static let customOpenAIVaildModels = Key<Array>(
EZCustomOpenAIValidModelsKey,
default: [""]
)

// DeepL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ class CustomOpenAIService: BaseOpenAIService {
}

override var availableModels: [String] {
let models = Defaults[.customOpenAIModelsAvailable]
guard let models, !models.isEmpty else { return [] }
return models.components(separatedBy: ",").filter { !$0.isEmpty }
Defaults[.customOpenAIVaildModels]
}

override func serviceType() -> ServiceType {
Expand Down
17 changes: 6 additions & 11 deletions Easydict/Swift/Service/OpenAI/BaseOpenAIService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,20 +123,19 @@ public class BaseOpenAIService: QueryService {

// MARK: Internal

var availableModels: [String] {
Defaults[.openAIVaildModels]
}

var model: String {
get {
var model = Defaults[.openAIModel].rawValue
if model.isEmpty {
model = availableModels.first ?? OpenAIModel.gpt3_5_turbo_0125.rawValue
}
return model
Defaults[.openAIModel]
}

set {
// easydict://writeKeyValue?EZOpenAIModelKey=gpt-3.5-turbo

let mode = OpenAIModel(rawValue: newValue) ?? .gpt3_5_turbo_0125
Defaults[.openAIModel] = mode
Defaults[.openAIModel] = newValue
}
}

Expand Down Expand Up @@ -166,10 +165,6 @@ public class BaseOpenAIService: QueryService {
return endPoint
}

var availableModels: [String] {
OpenAIModel.allCases.map { $0.rawValue }
}

// MARK: Private

private func queryTextType(text: String, from: Language, to _: Language) -> EZQueryTextType {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ private struct CustomOpenAIServiceConfigurationView: View {
var body: some View {
ServiceConfigurationSecretSectionView(
service: service,
observeKeys: [.customOpenAIAPIKey, .customOpenAIEndPoint, .customOpenAIModelsAvailable]
observeKeys: [.customOpenAIAPIKey, .customOpenAIEndPoint, .customOpenAIAvailableModels]
) {
// title
ServiceConfigurationInputCell(
Expand All @@ -57,7 +57,8 @@ private struct CustomOpenAIServiceConfigurationView: View {
key: .customOpenAIEndPoint,
placeholder: "service.configuration.openai.endpoint.placeholder"
)
// model

// supported models
TextField(
"service.configuration.custom_openai.supported_models.title",
text: viewModel.$availableModels ?? "",
Expand Down Expand Up @@ -113,7 +114,7 @@ private class CustomOpenAIViewModel: ObservableObject {
Defaults.publisher(.customOpenAIModel, options: [])
.removeDuplicates()
.sink { _ in
self.serviceConfigChanged()
self.modelChanged()
}
)
cancellables.append(
Expand All @@ -124,7 +125,7 @@ private class CustomOpenAIViewModel: ObservableObject {
}
)
cancellables.append(
Defaults.publisher(.customOpenAIModelsAvailable)
Defaults.publisher(.customOpenAIAvailableModels)
.removeDuplicates()
.sink { _ in
self.modelsTextChanged()
Expand All @@ -137,7 +138,7 @@ private class CustomOpenAIViewModel: ObservableObject {
let service: CustomOpenAIService

@Default(.customOpenAIModel) var model
@Default(.customOpenAIModelsAvailable) var availableModels
@Default(.customOpenAIAvailableModels) var availableModels

@Published var validModels: [String] = []

Expand All @@ -150,23 +151,42 @@ private class CustomOpenAIViewModel: ObservableObject {

private var cancellables: [AnyCancellable] = []

private func modelChanged() {
if !validModels.contains(model) {
if model.isEmpty {
availableModels = ""
} else {
if availableModels?.isEmpty == true {
availableModels = model
} else {
availableModels = "\(model), " + (availableModels ?? "")
}
}
}

serviceConfigChanged()
}

private func modelsTextChanged() {
guard let availableModels else { return }
if availableModels.isEmpty {

validModels = availableModels.components(separatedBy: ",")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }

if validModels.isEmpty {
model = ""
validModels = []
return
}
validModels = availableModels.components(separatedBy: ",").filter { !$0.isEmpty }
if validModels.count == 1 || !validModels.contains(model) {
} else if !validModels.contains(model) {
model = validModels[0]
}

Defaults[.customOpenAIVaildModels] = validModels
}

private func serviceConfigChanged() {
// looks like Defaults changed but View not update in this case
objectWillChange.send()

let userInfo: [String: Any] = [
EZWindowTypeKey: service.windowType.rawValue,
EZServiceTypeKey: service.serviceType().rawValue,
]
let notification = Notification(name: .serviceHasUpdated, object: nil, userInfo: userInfo)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private struct OpenAIServiceConfigurationView: View {

var body: some View {
ServiceConfigurationSecretSectionView(
service: service, observeKeys: [.openAIAPIKey]
service: service, observeKeys: [.openAIAPIKey, .openAIEndPoint, .openAIAvailableModels]
) {
ServiceConfigurationSecureInputCell(
textFieldTitleKey: "service.configuration.openai.api_key.title",
Expand All @@ -50,12 +50,24 @@ private struct OpenAIServiceConfigurationView: View {
key: .openAIEndPoint,
placeholder: "service.configuration.openai.endpoint.placeholder"
)

// model
ServiceConfigurationPickerCell(
titleKey: "service.configuration.openai.model.title",
key: .openAIModel,
values: OpenAIModel.allCases
TextField(
"service.configuration.custom_openai.supported_models.title",
text: viewModel.$availableModels ?? "",
prompt: Text("service.configuration.custom_openai.model.placeholder")
)
.padding(10.0)
Picker(
"service.configuration.openai.model.title",
selection: viewModel.$model
) {
ForEach(viewModel.validModels, id: \.self) { value in
Text(value)
}
}
.padding(10.0)

ServiceConfigurationToggleCell(
titleKey: "service.configuration.openai.translation.title",
key: .openAITranslation
Expand Down Expand Up @@ -95,7 +107,14 @@ private class OpenAIServiceViewModel: ObservableObject {
Defaults.publisher(.openAIModel, options: [])
.removeDuplicates()
.sink { _ in
self.serviceConfigChanged()
self.modelChanged()
}
)
cancellables.append(
Defaults.publisher(.openAIAvailableModels)
.removeDuplicates()
.sink { _ in
self.modelsTextChanged()
}
)
}
Expand All @@ -105,6 +124,9 @@ private class OpenAIServiceViewModel: ObservableObject {
let service: OpenAIService

@Default(.openAIModel) var model
@Default(.openAIAvailableModels) var availableModels

@Published var validModels: [String] = []

func invalidate() {
cancellables.forEach { $0.cancel() }
Expand All @@ -115,7 +137,43 @@ private class OpenAIServiceViewModel: ObservableObject {

private var cancellables: [AnyCancellable] = []

private func modelChanged() {
// Currently, user of low os versions can change OpenAI model using URL scheme, like easydict://writeKeyValue?EZOpenAIModelKey=gpt-4
// In this case, model may not be included in validModels, we need to handle it.

if !validModels.contains(model) {
if model.isEmpty {
availableModels = ""
} else {
if availableModels?.isEmpty == true {
availableModels = model
} else {
availableModels = "\(model), " + (availableModels ?? "")
}
}
}

serviceConfigChanged()
}

private func modelsTextChanged() {
guard let availableModels else { return }

validModels = availableModels.components(separatedBy: ",")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }

if validModels.isEmpty {
model = ""
} else if !validModels.contains(model) {
model = validModels[0]
}

Defaults[.openAIVaildModels] = validModels
}

private func serviceConfigChanged() {
objectWillChange.send()

let userInfo: [String: Any] = [
EZWindowTypeKey: service.windowType.rawValue,
EZServiceTypeKey: service.serviceType().rawValue,
Expand All @@ -135,8 +193,10 @@ protocol EnumLocalizedStringConvertible {

// swiftlint:disable identifier_name
enum OpenAIModel: String, CaseIterable {
case gpt3_5_turbo_0125 = "gpt-3.5-turbo-0125"
case gpt4_0125_preview = "gpt-4-0125-preview"
// Docs: https://platform.openai.com/docs/models/gpt-3-5-turbo

case gpt3_5_turbo = "gpt-3.5-turbo" // Currently points to gpt-3.5-turbo-0125.
case gpt4_turbo_preview = "gpt-4-turbo-preview" // Currently points to gpt-4-0125-preview.
}

// MARK: EnumLocalizedStringConvertible
Expand Down
Loading