forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleAICompletionAPI.swift
More file actions
59 lines (54 loc) · 1.96 KB
/
GoogleAICompletionAPI.swift
File metadata and controls
59 lines (54 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import AIModel
import Foundation
import GoogleGenerativeAI
import Preferences
struct GoogleCompletionAPI: CompletionAPI {
let apiKey: String
let model: ChatModel
var requestBody: CompletionRequestBody
func callAsFunction() async throws -> CompletionResponseBody {
let aiModel = GenerativeModel(
name: model.name,
apiKey: apiKey,
generationConfig: .init(GenerationConfig(
temperature: requestBody.temperature.map(Float.init),
topP: requestBody.top_p.map(Float.init)
))
)
let history = requestBody.messages.map { message in
ModelContent(
ChatMessage(
role: message.role,
content: message.content,
name: message.name,
functionCall: message.function_call.map {
.init(name: $0.name, arguments: $0.arguments ?? "")
}
)
)
}
let response = try await aiModel.generateContent(history)
return .init(
object: "chat.completion",
model: model.name,
usage: .init(prompt_tokens: 0, completion_tokens: 0, total_tokens: 0),
choices: response.candidates.enumerated().map {
let (index, candidate) = $0
return .init(
message: .init(
role: .assistant,
content: candidate.content.parts.first(where: { part in
if let text = part.text {
return !text.isEmpty
} else {
return false
}
})?.text ?? ""
),
index: index,
finish_reason: candidate.finishReason?.rawValue ?? ""
)
}
)
}
}