forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAIPromptToCodeService.swift
More file actions
312 lines (283 loc) · 11.5 KB
/
OpenAIPromptToCodeService.swift
File metadata and controls
312 lines (283 loc) · 11.5 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import Foundation
import OpenAIService
import Preferences
import SuggestionModel
import XcodeInspector
public final class OpenAIPromptToCodeService: PromptToCodeServiceType {
var service: (any ChatGPTServiceType)?
public init() {}
public func stopResponding() {
Task { await service?.stopReceivingMessage() }
}
public func modifyCode(
code: String,
requirement: String,
source: PromptToCodeSource,
isDetached: Bool,
extraSystemPrompt: String?,
generateDescriptionRequirement: Bool?
) async throws -> AsyncThrowingStream<(code: String, description: String), Error> {
let userPreferredLanguage = UserDefaults.shared.value(for: \.chatGPTLanguage)
let textLanguage = {
if !UserDefaults.shared
.value(for: \.promptToCodeGenerateDescriptionInUserPreferredLanguage)
{
return ""
}
return userPreferredLanguage.isEmpty ? "" : " in \(userPreferredLanguage)"
}()
let editor: EditorInformation = await XcodeInspector.shared.getFocusedEditorContent()
?? .init(
editorContent: .init(
content: source.content,
lines: source.lines,
selections: [source.range],
cursorPosition: .outOfScope,
cursorOffset: -1,
lineAnnotations: []
),
selectedContent: code,
selectedLines: [],
documentURL: source.documentURL,
workspaceURL: source.projectRootURL,
projectRootURL: source.projectRootURL,
relativePath: "",
language: source.language
)
let rule: String = {
func generateDescription(index: Int) -> String {
let generateDescription = generateDescriptionRequirement ?? UserDefaults.shared
.value(for: \.promptToCodeGenerateDescription)
return generateDescription
? """
\(index). After the code block, write a clear and concise description \
in 1-3 sentences about what you did in step 1\(textLanguage).
\(index + 1). Reply with the result.
"""
: "\(index). Reply with the result."
}
switch editor.language {
case .builtIn(.markdown), .plaintext:
if code.isEmpty {
return """
1. Write the content that meets my requirements.
2. Embed the new content in a markdown code block.
\(generateDescription(index: 3))
"""
} else {
return """
1. Do what I required.
2. Format the updated content to use the original indentation. Especially the first line.
3. Embed the updated content in a markdown code block.
4. You MUST never translate the content in the code block if it's not requested in the requirements.
\(generateDescription(index: 5))
"""
}
default:
if code.isEmpty {
return """
1. Write the code that meets my requirements.
2. Embed the code in a markdown code block.
\(generateDescription(index: 3))
"""
} else {
return """
1. Do what I required.
2. Format the updated code to use the original indentation. Especially the first line.
3. Embed the updated code in a markdown code block.
\(generateDescription(index: 4))
"""
}
}
}()
let systemPrompt = {
switch editor.language {
case .builtIn(.markdown), .plaintext:
if code.isEmpty {
return """
You are good at writing in \(editor.language.rawValue).
The active file is: \(editor.documentURL.lastPathComponent).
\(extraSystemPrompt ?? "")
\(rule)
"""
} else {
return """
You are good at writing in \(editor.language.rawValue).
The active file is: \(editor.documentURL.lastPathComponent).
\(extraSystemPrompt ?? "")
\(rule)
"""
}
default:
if code.isEmpty {
return """
You are a senior programer in writing in \(editor.language.rawValue).
The active file is: \(editor.documentURL.lastPathComponent).
\(extraSystemPrompt ?? "")
\(rule)
"""
} else {
return """
You are a senior programer in writing in \(editor.language.rawValue).
The active file is: \(editor.documentURL.lastPathComponent).
\(extraSystemPrompt ?? "")
\(rule)
"""
}
}
}()
let annotations = isDetached
? ""
: extractAnnotations(editorInformation: editor, source: source)
let firstMessage: String? = {
if code.isEmpty { return nil }
switch editor.language {
case .builtIn(.markdown), .plaintext:
return """
```
\(code)
```
\(annotations)
"""
default:
return """
```
\(code)
```
\(annotations)
"""
}
}()
let indentation = getCommonLeadingSpaceCount(code)
let secondMessage = """
I will update the code you just provided.
Every line has an indentation of \(indentation) spaces, I will keep that.
What is your requirement?
"""
let configuration =
UserPreferenceChatGPTConfiguration(chatModelKey: \.promptToCodeChatModelId)
.overriding(.init(temperature: 0))
let memory = AutoManagedChatGPTMemory(
systemPrompt: systemPrompt,
configuration: configuration,
functionProvider: NoChatGPTFunctionProvider()
)
let chatGPTService = ChatGPTService(
memory: memory,
configuration: configuration
)
service = chatGPTService
if let firstMessage {
await memory.mutateHistory { history in
history.append(.init(role: .user, content: firstMessage))
history.append(.init(role: .assistant, content: secondMessage))
}
}
let stream = try await chatGPTService.send(content: requirement)
return .init { continuation in
Task {
var content = ""
var extracted = extractCodeAndDescription(from: content)
do {
for try await fragment in stream {
content.append(fragment)
extracted = extractCodeAndDescription(from: content)
if !content.isEmpty, extracted.code.isEmpty {
continuation.yield((code: content, description: ""))
} else {
continuation.yield(extracted)
}
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
}
}
// MAKR: - Internal
extension OpenAIPromptToCodeService {
func extractCodeAndDescription(from content: String)
-> (code: String, description: String)
{
func extractCodeFromMarkdown(
_ markdown: String
) -> (code: String, endIndex: String.Index)? {
let codeBlockRegex = try! NSRegularExpression(
pattern: #"```(?:\w+)?\R([\s\S]+?)\R```"#,
options: .dotMatchesLineSeparators
)
let range = NSRange(markdown.startIndex..<markdown.endIndex, in: markdown)
if let match = codeBlockRegex.firstMatch(in: markdown, options: [], range: range) {
guard let codeBlockRange = Range(match.range(at: 1), in: markdown),
let endIndex = Range(match.range(at: 0), in: markdown)?.upperBound
else { return nil }
return (String(markdown[codeBlockRange]), endIndex)
}
let incompleteCodeBlockRegex = try! NSRegularExpression(
pattern: #"```(?:\w+)?\R([\s\S]+?)$"#,
options: .dotMatchesLineSeparators
)
let range2 = NSRange(markdown.startIndex..<markdown.endIndex, in: markdown)
if let match = incompleteCodeBlockRegex.firstMatch(
in: markdown,
options: [],
range: range2
) {
guard let codeBlockRange = Range(match.range(at: 1), in: markdown),
let endIndex = Range(match.range(at: 0), in: markdown)?.upperBound
else { return nil }
return (String(markdown[codeBlockRange]), endIndex)
}
return nil
}
guard let (code, endIndex) = extractCodeFromMarkdown(content) else {
return ("", "")
}
func extractDescriptionFromMarkdown(
_ markdown: String,
startIndex: String.Index
) -> String {
guard startIndex < markdown.endIndex else { return "" }
let range = startIndex..<markdown.endIndex
let description = String(markdown[range])
.trimmingCharacters(in: .whitespacesAndNewlines)
return description
}
let description = extractDescriptionFromMarkdown(content, startIndex: endIndex)
return (code, description)
}
func getCommonLeadingSpaceCount(_ code: String) -> Int {
let lines = code.split(whereSeparator: \.isNewline)
guard !lines.isEmpty else { return 0 }
var commonCount = Int.max
for line in lines {
let count = line.prefix(while: { $0 == " " }).count
commonCount = min(commonCount, count)
if commonCount == 0 { break }
}
return commonCount
}
func extractAnnotations(
editorInformation: EditorInformation,
source: PromptToCodeSource
) -> String {
guard let annotations = editorInformation.editorContent?.lineAnnotations
else { return "" }
let all = annotations
.lazy
.filter { annotation in
annotation.line >= source.range.start.line + 1
&& annotation.line <= source.range.end.line + 1
}.map { annotation in
let relativeLine = annotation.line - source.range.start.line
return "line \(relativeLine): \(annotation.type) \(annotation.message)"
}
guard !all.isEmpty else { return "" }
return """
line annotations found:
\(annotations.map { "- \($0)" }.joined(separator: "\n"))
"""
}
}