Ollama 和 Continue.dev 构建 VS Code 本地代码 Copilot

Continue.dev 可以方便的【自动提示补全】,【选中代码再编辑】,【选中聊天】以及【错误信息自动提问】,是目前开源框架里面功能比较完善的。结合 Ollama 后端,再配合本地开源代码模型,比如排名比较靠前的 Deepseek。真正做到了 GitHub Copilot 的低配平替。另外可以通过 @/ 比较方便的自定义扩展功能。

安装插件

直接在 VS Code 的插件市场输入 continue 就可以看到,然后直接安装即可。

安装完后,可以在设置里面看到操作的一些快捷键。

修改配置文件

.config Windows 下的目录如下:C:\Users\mintisan\.continue\config.json,macOS 应该是 ~/.continue/config.json,最好备份一个然后再修改为如下:【注意我这里的apiBase!!!是部署在其他电脑上的,如果是本地就使用 localhost 即可。】

{
  "slashCommands":[
    {
      "name": "edit",
      "description": "Edit highlighted code"
    },
    {
      "name": "comment",
      "description": "Write comments for the highlighted code"
    },
    {
      "name": "share",
      "description": "Download and share this session"
    },
    {
      "name": "cmd",
      "description": "Generate a shell command"
    },
    {
      "name": "commit",
      "description": "Generate a commit message for the current changes"
    },
    {
      "name": "so",
      "description": "Reference StackOverflow to answer the question"
    }
  ],
  "contextProviders":[
    { "name": "code" },
    { "name": "open", "params": { "onlyPinned": false } },
    {
      "name": "codebase",
      "params": {
        "nRetrieve": 25,
        "nFinal": 5,
        "useReranking": true
      }
    },
    { "name": "folder" },
    { "name": "search" },
    { "name": "tree" },
    { "name": "outline" },
    { "name": "highlights" },
    { "name": "docs" },
    { "name": "terminal" },
    { "name": "diff" }
  ],
  "systemMessage": "你是一个嵌入式软件开发专家,供职于汇顶科技蓝牙部门,有丰富使用 ARM Cortex-M4 内核相关芯片的使用经验,也有着丰富的设计低功耗蓝牙 BLE 的经验,也擅长帮助客户解决使用 GR551x_SDK_V2.0.2 过程中出现的问题",
  "embeddingsProvider": {
    "provider": "ollama",
    "model": "nomic-embed-text",
    "apiBase": "http://100.122.227.134:11434"
  },
  "models": [
    {
      "title": "DeepSeek-33b",
      "provider": "ollama",
      "model": "deepseek-coder:33b",
      "apiBase": "http://100.122.227.134:11434"
    }
  ],
  "tabAutocompleteModel": {
    "title": "Tab Autocomplete Model",
    "provider": "ollama",
    "model": "deepseek-coder:33b-base-q4_K_S",
    "apiBase": "http://100.122.227.134:11434"
  }
}

注:一般的模型采用 chat 或者 instruct 模型;自动补全采用 base 模型,官方文档里面有提。

如果 Ollama 不是和 VS Code 在同一台电脑上,那么配置完后需要重启下,否则会出现如下错误。

使用场景

VS Code 的项目直接把文件夹 GR551x_SDK_V2.0.2 拖进来尽可以了,但是如果需要过滤掉不需要 embedding 的文件,可以在根目录新建 .continueignore,添加如下:

*.out
*.pdf
*.chm
*.a
*.dll
*.pyd
*.lib
*.exe
*.zip
*.hex
*.data
*.svg
*.bin
*.enc
*.doxyfile
*.function
*.uvoptx
*.sln
*.o
*.eps
*.tcl

注意,不能使用 *,然后 !*.c 这种反套路,会导致无法触发无法 embedding,,,

【自动提示补全】

Continue 会在后台默认查询你所在编辑内容的上下文,比如当你写完 ## write quick_sort in python 后,敲下回车,那么可能就会触发自动提示补全功能,如果你同意就可以按 tab 同意,相当于 Code Snippet 功能。

以上前台操作过程显示的后台 Prompt 如下。

==========================================================================
==========================================================================
Settings:
contextLength: 4096
model: deepseek-coder:33b-base-q4_K_S
maxTokens: 1024
stop: <|fim▁begin|>,<|fim▁hole|>,<|fim▁end|>,//,

,/src/,```,def,class
temperature: 0

############################################

<|fim▁begin|>"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""

# endregion

# region ———————————————————————————— Part 3: Debug automatically [⌘ ⇧ R] ————————————————————————————


"""Step 1: Run this Python file (it should error!)"""


def print_sum(list_to_print):
    total = 0
    for num in list_to_print:
        if isinstance(num, int):
            total += num
        else:
            raise ValueError("All elements in the list must be integers.")
    print(total)



"""Step 2: Use the keyboard shortcut [⌘ ⇧ R]
to automatically debug the error"""
print_sum(["a", "b", "c"])

# endregion

## write quick_sort in python
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[0]
    left = []
    right = []
    for i in range(1, len(arr)):
        if arr[i] < pivot:
            left.append(arr[i])
        else:
            right.append(arr[i])
    return quick_sort(left) + [pivot] + quick_sort(right)
<|fim▁hole|><|fim▁end|>==========================================================================
==========================================================================
Completion:


print(quick_sort([3, 2, 1]))

【选中代码再编辑】

此时,当我们写了一些代码后,我们需要对现有代码进行修改,比如添加注释,编写测试用例,,,

选中需要处理的代码片段,按压 CTRL + I 可以触发指令输入。

等待一会会出现如下修改后的对比,等待确认。

以上前台显示的后台 Prompt 如下。

==========================================================================
==========================================================================
Settings:
contextLength: 4096
model: deepseek-coder:33b
maxTokens: 1024

############################################

### System Prompt
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction:
Rewrite the code to satisfy this request: "add comment"

```python
## write quick_sort in python
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[0]
    left = []
    right = []
    for i in range(1, len(arr)):
        if arr[i] < pivot:
            left.append(arr[i])
        else:
            right.append(arr[i])
    return quick_sort(left) + [pivot] + quick_sort(right)

```<|EOT|>
### Response:
Sure! Here's the code you requested:

【选中聊天】

当我们选中需要了解的代码段后,快捷键 CTRL+L 按下后,代码会自动同步到左侧的聊天框中。

此时就可以输入你想要了解的指令说明即可。这里会返回比较快。

以上前台显示的后台 Prompt 如下。



==========================================================================
==========================================================================
Settings:
contextLength: 4096
model: deepseek-coder:33b
maxTokens: 1024

############################################

<user>
continue_tutorial.py (96-115)
## write quick_sort in python
# This function performs a Quick Sort on an input array. 
def quick_sort(arr):
  # Base case: if array has less than or equal to one element, it is already sorted
    if len(arr) <= 1:
        return arr
    pivot = arr[0]
    left = []
    right = []
    # Split the array into two parts based on a pivot
    for i in range(1, len(arr)):
        # If element is less than pivot, append it to left part. Else, append it to right part.
        if arr[i] < pivot:
            left.append(arr[i])
        else:
            right.append(arr[i])
    
    # Recursive calls for sorting the two parts and merging them with pivot.
    return quick_sort(left) + [pivot] + quick_sort(right)


这段代码有什么问题么

==========================================================================
==========================================================================
Completion:

这段代码的实现是正确的,它实现了Quick Sort算法。然而,它选择了数组的第一个元素作为枢轴,在处理已经排序或接近有序的大数据集时,这种方式可能会导致较差的性能。

一个更优化的方法是使用“三者中值”来选择枢轴,即从数组的第一个、中间和最后一个元素中选取中位数作为枢轴。这样可以更好地平衡分区,从而避免最坏情况(例如已经排序或接近有序的数据集)对性能的影响。

此外,这段代码并没有使用原地分区的方式来节省空间,如果输入数组非常大,可能会导致堆栈溢出或者内存问题。在Python中实现Quick Sort时,通常会选择原地分区的版本。

【错误信息自动提问】

Continue 除了以上 3 个主要的功能外,在应用上还做了一个比较好的功能,就是按压 CTRL+Shift + R 后,可以直接在工作流中抓取错误信息,向 LLM 提出问题,比较方便。

注:以上的所有过程都可以在 如下的输出窗口中得到确认。

@功能

@Open Files 相当于获取目前在 VS Code 中打印的文件对象内容,可以咨询打开的文件

@ File Tree 相当于得到了代码仓库的所有目录接口和文件名字,LLM 可以查询所有文件信息,以下就是通过目录名字得到 adc 例程的路径。

@Codebase 相当于代码仓库级别的 RAG,可以索所有代码,可以看到我们 config.json 查询到的片段还是基本都是相关的。

/ 功能

其实就是 CTRL+I 的另一种形式,可以先通过 CTRL+L将我们关注的代码片段先挪到聊天框,然后后续进一步编辑。这里以 /comment 为例进行演示,其他也类似。

注意事项

  1. 如果你切换了模型,那么第一次将会等待比较久的时间
  2. 更换了配置文件需要重启 vs code

参考链接

问题链接

同类竞品