[教學] 使用 LM Studio 大語言模型幫助 XCode 編碼工作

本帖最後由 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
  1. curl -X POST http://localhost:1234/v1/chat/completions \
  2. -H "Content-Type: application/json" \
  3. -d '{
  4.   "messages": [
  5.     { "role": "user", "content": "Write a hello world program in swift" }                        
  6.   ]
  7. }'
複製代碼
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.
  1. import XcodeKit

  2. class SourceEditorCommand: NSObject, XCSourceEditorCommand {
  3.     func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void) {
  4.         // Retrieve selected code
  5.         guard let selection = invocation.buffer.selections.firstObject as? XCSourceTextRange else {
  6.             completionHandler(nil)
  7.             return
  8.         }

  9.         let selectedLines = invocation.buffer.lines
  10.             .subarray(with: NSRange(location: selection.start.line, length: selection.end.line - selection.start.line + 1))
  11.             .compactMap { $0 as? String }
  12.             .joined(separator: "\n")

  13.         // Prepare the prompt for LM Studio
  14.         let prompt = "Analyze and optimize this Swift code:\n\n\(selectedLines)"

  15.         // Call LM Studio API
  16.         callLMStudioAPI(prompt: prompt) { response in
  17.             if let response = response {
  18.                 // Insert the response into the editor
  19.                 invocation.buffer.lines.add("\n// LLM Suggestion:\n\(response)")
  20.             }
  21.             completionHandler(nil)
  22.         }
  23.     }

  24.     private func callLMStudioAPI(prompt: String, completion: @escaping (String?) -> Void) {
  25.         let url = URL(string: "http://localhost:1234/v1/chat/completions")!
  26.         var request = URLRequest(url: url)
  27.         request.httpMethod = "POST"
  28.         request.addValue("application/json", forHTTPHeaderField: "Content-Type")

  29.         let body: [String: Any] = [
  30.             "messages": [["role": "user", "content": prompt]],
  31.             "temperature": 0.7
  32.         ]
  33.         request.httpBody = try? JSONSerialization.data(withJSONObject: body)

  34.         let task = URLSession.shared.dataTask(with: request) { data, _, _ in
  35.             if let data = data,
  36.                let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
  37.                let choices = json["choices"] as? [[String: Any]],
  38.                let message = choices.first?["message"] as? [String: Any],
  39.                let content = message["content"] as? String {
  40.                 completion(content)
  41.             } else {
  42.                 completion(nil)
  43.             }
  44.         }
  45.         task.resume()
  46.     }
  47. }
複製代碼
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.
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊