Skip to content

Commit 513468d

Browse files
committed
Add LangChainChatModel and ReadablePythonError
1 parent 651bf1b commit 513468d

3 files changed

Lines changed: 77 additions & 6 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import Foundation
2+
import Preferences
3+
import PythonKit
4+
5+
public enum LangChainChatModel {
6+
public static func DynamicChatOpenAI(
7+
temperature: Double
8+
) throws -> PythonObject {
9+
switch UserDefaults.shared.value(for: \.chatFeatureProvider) {
10+
case .openAI:
11+
let model = UserDefaults.shared.value(for: \.chatGPTModel)
12+
let apiBaseURL = UserDefaults.shared.value(for: \.openAIBaseURL)
13+
let apiKey = UserDefaults.shared.value(for: \.openAIAPIKey)
14+
return try withReadableThrowingPython {
15+
let chatModels = try Python.attemptImport("langchain.chat_models")
16+
let ChatOpenAI = chatModels.ChatOpenAI
17+
return ChatOpenAI(
18+
temperature: temperature,
19+
model: model,
20+
openai_api_base: "\(apiBaseURL)/v1",
21+
openai_api_key: apiKey
22+
)
23+
}
24+
case .azureOpenAI:
25+
let apiBaseURL = UserDefaults.shared.value(for: \.azureOpenAIBaseURL)
26+
let apiKey = UserDefaults.shared.value(for: \.azureOpenAIAPIKey)
27+
let deployment = UserDefaults.shared.value(for: \.azureChatGPTDeployment)
28+
return try withReadableThrowingPython {
29+
let chatModels = try Python.attemptImport("langchain.chat_models")
30+
let ChatOpenAI = chatModels.AzureChatOpenAI
31+
return ChatOpenAI(
32+
temperature: temperature,
33+
openai_api_type: "azure",
34+
openai_api_version: "2023-03-15-preview",
35+
deployment_name: deployment,
36+
openai_api_base: apiBaseURL,
37+
openai_api_key: apiKey
38+
)
39+
}
40+
}
41+
}
42+
}
43+
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import Foundation
2+
import PythonKit
3+
4+
public struct ReadablePythonError: Error, LocalizedError {
5+
public var error: PythonError
6+
7+
public init(_ error: PythonError) {
8+
self.error = error
9+
}
10+
11+
public var errorDescription: String? {
12+
switch error {
13+
case let .exception(object, _):
14+
return "\(object)"
15+
case let .invalidCall(object):
16+
return "Invalid call: \(object)"
17+
case let .invalidModule(module):
18+
return "Invalid module: \(module)"
19+
}
20+
}
21+
}
22+
23+
public func withReadableThrowingPython<T>(
24+
_ closure: () throws -> T
25+
) throws -> T {
26+
do {
27+
return try closure()
28+
} catch let error as PythonError {
29+
throw ReadablePythonError(error)
30+
} catch {
31+
throw error
32+
}
33+
}
34+

Tool/Sources/LangChainService/Schema.swift

Lines changed: 0 additions & 6 deletions
This file was deleted.

0 commit comments

Comments
 (0)