本帖最後由 javacomhk 於 2025-2-9 05:01 編輯
1. 首先根據上一篇教學 看看所需硬件要及安裝 LM Studio and 大語言模型 例如 DeepSeek-R1
2. 在 LM Studio 將下載的模型 Load 入RAM 後及在第二個的 Developer Tab 開啟 server 如下
3. 開啟 Terminal 打入以下 code 以測試 LM Studio server- curl -X POST http://localhost:1234/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "messages": [
- { "role": "user", "content": "Write a hello world program in swift" }
- ]
- }'
複製代碼 4. 測試 server 成功後便可以在 Xcode 創建 Xcode Source Editor Extension 步驟如下 (reference from ChatGPT)
Develop an Xcode Source Editor Extension
a. Create a New Project:
Open Xcode and create a new macOS App project (e.g., XcodeLLMExtension).
b. Add a Source Editor Extension Target:
In your project, add a new target by selecting File > New > Target.
Choose Source Editor Extension under the macOS section and name it (e.g., LLMCodeAssistant).
c. Configure the Extension:
In the extension's Info.plist, set the following keys:
NSExtensionPointIdentifier to com.apple.xcode.source-editor
NSExtensionPrincipalClass to $(PRODUCT_MODULE_NAME).SourceEditorCommand
d. Implement the Command:
In SourceEditorCommand.swift, implement the perform function to interact with LM Studio's API.- import XcodeKit
- class SourceEditorCommand: NSObject, XCSourceEditorCommand {
- func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void) {
- // Retrieve selected code
- guard let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange else {
- completionHandler(nil)
- return
- }
- let selectedLines = invocation.buffer.lines
- .subarray(with: NSRange(location: selection.start.line, length: selection.end.line - selection.start.line + 1))
- .compactMap { $0 as? String }
- .joined(separator: "\n")
- // Prepare the prompt for LM Studio
- let prompt = "Analyze and optimize this Swift code:\n\n\(selectedLines)"
- // Call LM Studio API
- callLMStudioAPI(prompt: prompt) { response in
- if let response = response {
- // Insert the response into the editor
- invocation.buffer.lines.add("\n// LLM Suggestion:\n\(response)")
- }
- completionHandler(nil)
- }
- }
- private func callLMStudioAPI(prompt: String, completion: @escaping (String?) -> Void) {
- let url = URL(string: "http://localhost:1234/v1/chat/completions")!
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- let body: [String: Any] = [
- "messages": [["role": "user", "content": prompt]],
- "temperature": 0.7
- ]
- request.httpBody = try? JSONSerialization.data(withJSONObject: body)
- let task = URLSession.shared.dataTask(with: request) { data, _, _ in
- if let data = data,
- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let choices = json["choices"] as? [[String: Any]],
- let message = choices.first?["message"] as? [String: Any],
- let content = message["content"] as? String {
- completion(content)
- } else {
- completion(nil)
- }
- }
- task.resume()
- }
- }
複製代碼 Ensure that the callLMStudioAPI function matches the API specifications provided by LM Studio.
5. Enable and Test the Extension
a. Enable the Extension:
Build and run your macOS app.
Navigate to System Settings > Privacy & Security > Extensions and enable your Xcode extension.
b. Test in Xcode:
Open a Swift file in Xcode.
Select the code you want to analyze or refactor.
Go to Editor > LLMCodeAssistant to invoke the extension.
The AI-generated suggestions will appear as comments in your code.
By following these steps, you can harness the power of LM Studio within Xcode, enhancing your coding experience with AI-driven insights and assistance.
6 Possible Enhancements
Add different commands for:
Code explanation
Bug detection
Autocompletion
Use LLM fine-tuning for specific Swift best practices.
Implement a UI dialog for user input before sending a request. |