🔍 Codebase Retrieval (#600)

* 💄 ui for codebase

* 🚧 meilisearch codebase index

* ♻️ refactor for second codebase index

* ✨ index and search from CLI

* ⚗️ experiments to improve f1 score

* ⚗️ HyDE and single token reranker

* 🐛 permit "no" and "yes" in reranker

* Update README.md

* Set CWD when running ui build prelaunch task (#588)

Fixes Server + Extension vscode launch configuration.

Then previous "npm" type task respected the cwd setting from launch.json. However, the new "shell" type task seems to require it be explicitly set in the task.

* add ref to what llm to use

* fixing broken link

* ci: 🏷 Update PyPI version [skip ci]

* Update running-continue-without-internet.md (#590)

* Fix URL for Together.ai models list in models.md (#593)

* Preview (#595)

* Strong typing (#533)

* refactor: ♻️ get rid of continuedev.src.continuedev structure

* refactor: ♻️ switching back to server folder

* feat: ✨ make config.py imports shorter

* feat: 🔖 publish as pre-release vscode extension

* refactor: ♻️ refactor and add more completion params to ui

* build: 🏗️ download from preview S3

* fix: 🐛 fix paths

* fix: 💚 package:pre-release

* ci: 💚 more time for tests

* fix: 💚 fix build scripts

* fix: 🐛 fix import in run.py

* fix: 🔖 update version to try again

* ci: 💚 Update package.json version [skip ci]

* refactor: 🔥 don't check for old extensions version

* fix: 🐛 small bug fixes

* fix: 🐛 fix config.py import paths

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 platform-specific builds test #1

* feat: 💚 ship with binary

* fix: 💚 fix copy statement to include.exe for windows

* fix: 💚 cd extension before packaging

* chore: 🔊 count tokens generated

* fix: 💚 remove npm_config_arch

* fix: 💚 publish as pre-release!

* chore: 🔖 update version

* perf: 💚 hardcode distro paths

* fix: 🐛 fix yaml syntax error

* chore: 🔖 update version

* fix: 💚 update permissions and version

* feat: 🐛 kill old server if needed

* feat: 💄 update marketplace icon for pre-release

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ auto-reload for config.py

* feat: 🔧 update default config.py imports

* feat: ✨ codelens in config.py

* feat: ✨ select model param count from UI

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ more model options, ollama error handling

* perf: ⚡ don't show server loading immediately

* fix: 🐛 fixing small UI details

* ci: 💚 Update package.json version [skip ci]

* feat: 🚀 headers param on LLM class

* fix: 🐛 fix headers for openai.;y

* feat: ✨ highlight code on cmd+shift+L

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 sticky top bar in gui.tsx

* fix: 🔊 websocket logging and horizontal scrollbar

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ allow AzureOpenAI Service through GGML

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix automigration

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 upload binaries in ci, download apple silicon

* chore: 🔥 remove notes

* fix: 💚 use curl to download binary

* fix: 💚 set permissions on apple silicon binary

* fix: 💚 testing

* fix: 💚 cleanup file

* fix: 💚 fix preview.yaml

* fix: 💚 only upload once per binary

* fix: 💚 install rosetta

* ci: 💚 download binary after tests

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 prepare ci for merge to main

* feat: ✨ improved edit prompts for OS models

* feat: ✨ add edit templates to model packages

* feat: 👔 allow timeout param for OpenAI LLM class

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 add textgenwebui as official option in Ui

* fix: 🐛 fix for --meilisearch-url flag

* fix: 🐛 meilisearch fixes

* feat: ✨ display model params for previous prompts

* fix: 🐛 fix overriding of system message

* ci: 💚 Update package.json version [skip ci]

* fix: ⚡ update count_tokens method

* feat: ⚡ reduce default max_tokens

* fix: 🐛 fix set_system_message

* ✨ Codebase Embeddings (#547)

* feat: ✨ basic codebase embeddings

* feat: 🚧 reranking after chroma retrieval

* refactor: 🚚 rename binary: run to continue_server

* ci: 💚 only do pypi step in github workflow

* ci: 🏷 Update PyPI version [skip ci]

* feat: 🐛 add openai_api_key param for chroma steps

* ci: 🏷 Update PyPI version [skip ci]

* build: 💚 update pypi package

* ci: 🏷 Update PyPI version [skip ci]

* fix: 🐛 rename run.spec

* ci: 🏷 Update PyPI version [skip ci]

* feat: ✨ params to control embeddings search

* ci: 🏷 Update PyPI version [skip ci]

* rename run.py

* feat: 🚧 improvements in progress for embeddings

* feat: 🎨 last bit of cleaning for chunked embeddings

* ci: 💚 add back pypi deployment in main.yam

* ci: 🏷 Update PyPI version [skip ci]

* fix: 🐛 error handling for chroma index in non-git folder

* ci: 🏷 Update PyPI version [skip ci]

* fix: 🐛 don't log reranking prompt

* ci: 🏷 Update PyPI version [skip ci]

* feat: ✨ add option to select embeddings model

* ci: 🏷 Update PyPI version [skip ci]

* move path decode/encode functions

* ci: 🏷 Update PyPI version [skip ci]

* update spec file

* Preview (#541)

* Strong typing (#533)

* refactor: ♻️ get rid of continuedev.src.continuedev structure

* refactor: ♻️ switching back to server folder

* feat: ✨ make config.py imports shorter

* feat: 🔖 publish as pre-release vscode extension

* refactor: ♻️ refactor and add more completion params to ui

* build: 🏗️ download from preview S3

* fix: 🐛 fix paths

* fix: 💚 package:pre-release

* ci: 💚 more time for tests

* fix: 💚 fix build scripts

* fix: 🐛 fix import in run.py

* fix: 🔖 update version to try again

* ci: 💚 Update package.json version [skip ci]

* refactor: 🔥 don't check for old extensions version

* fix: 🐛 small bug fixes

* fix: 🐛 fix config.py import paths

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 platform-specific builds test #1

* feat: 💚 ship with binary

* fix: 💚 fix copy statement to include.exe for windows

* fix: 💚 cd extension before packaging

* chore: 🔊 count tokens generated

* fix: 💚 remove npm_config_arch

* fix: 💚 publish as pre-release!

* chore: 🔖 update version

* perf: 💚 hardcode distro paths

* fix: 🐛 fix yaml syntax error

* chore: 🔖 update version

* fix: 💚 update permissions and version

* feat: 🐛 kill old server if needed

* feat: 💄 update marketplace icon for pre-release

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ auto-reload for config.py

* feat: 🔧 update default config.py imports

* feat: ✨ codelens in config.py

* feat: ✨ select model param count from UI

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ more model options, ollama error handling

* perf: ⚡ don't show server loading immediately

* fix: 🐛 fixing small UI details

* ci: 💚 Update package.json version [skip ci]

* feat: 🚀 headers param on LLM class

* fix: 🐛 fix headers for openai.;y

* feat: ✨ highlight code on cmd+shift+L

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 sticky top bar in gui.tsx

* fix: 🔊 websocket logging and horizontal scrollbar

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ allow AzureOpenAI Service through GGML

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix automigration

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 upload binaries in ci, download apple silicon

* chore: 🔥 remove notes

* fix: 💚 use curl to download binary

* fix: 💚 set permissions on apple silicon binary

* fix: 💚 testing

* fix: 💚 cleanup file

* fix: 💚 fix preview.yaml

* fix: 💚 only upload once per binary

* fix: 💚 install rosetta

* ci: 💚 download binary after tests

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 prepare ci for merge to main

---------

Co-authored-by: GitHub Action <action@github.com>

* fix: 📝 fix deployent readme

* chore: 🔖 update package.json version

* fix: 🐛 fix ci to only upload from linux x64, not alpine

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fixing up

* refactor: 🔥 remove sentence_transformers_model option

* ci: 💚 run preview.yaml

* refactor: ♻️ rename to continue_server

* ci: 💚 update python version in continue_server.spec

* ci: 💚 checking paths

* ci: 💚 find path of site-packages

* fix

* ci: 💚 deploy to pre-release

* ci: 💚 change branch to pull from in ci

* perf: 👷 build with tiktoken vocab

* chore: 🔖 upgrade version

* ci: 💚 Update package.json version [skip ci]

* fix: ⚡ update count_tokens method

* ci: 💚 download continue_server, not run

* ci: 💚 Update package.json version [skip ci]

* feat: ⚡ reduce default max_tokens

* fix: 🐛 fix set_system_message

* ci: 💚 update ci for preview branch

* build: 💚 update pypi package

---------

Co-authored-by: GitHub Action <action@github.com>

* ci: 💚 publish to pypi in seperate step

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* feat: 🎨 small changes to /codebase ui

* 📌 update pydantic version

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🐛 check for DISCONNECTED before closing ws

* 🐛 check for disconnected before sending ws msg

* 🚸 add python path to global vscode settings

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 💄 stop button

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🚑 solve ssl file not found error

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🔒️ trust_env=True for proxy env var

* ⚡️ always use custom aiohttp session for openai

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ⚡️ flatten messages

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🐛 migrate away from legacy completions endpoint

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🚑 fix delta undefined

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ⚡️ retry for readfile in index generation

* 💄 inserting at cursor above input box

* ⚡️ debouncing /edit streaming

* Initial intelliJ plugin changes to support webview (#457)

* Initial intelliJ plugin changes to support webview

* connect webview websockets

* Starting work on downloading server binary from S3

* fix color theme in intellij

* refactor name to continuedev

* correctly set important variables for onLoad

* highlighted code now working

* keyboard shortcuts (Actions)

* fix: 🐛 hf_tgi fix, proxy support for ggml

* fix: 🐛 remove unecessary logging

* Sync the changes

* Clean up code

* updating how continue works

* ci: 🏷 Update PyPI version [skip ci]

* docs: 📝 docs for customizing chat / edit templates

* docs: 📝 headless mode docs (start)

* docs: 📝 updated setup docs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 compatibility with python 3.8

* feat: ✨ verify_ssl option for all LLMs

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 verify_ssl and ssl_context mutual exclusivity

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* feat: 🩹 ca_bundle_path for maybeproxyopenai

* fix: 🐛 a few minor fixes

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 custom escaping instead of URI for diff paths

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix huggingface tgi

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* docs: 📝 small docs update on how continue works

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Clarifying `logs` instructions in troubleshooting.md (#476)

* fix: 🐛 fixes to templating messages

* fix: some typos (#478)

* fix: 🐛 fix for lmstudio defaults

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* Implement design patterns for better extensibility

* Fix: Ensure read operations in ContinuePluginSelectionListener are run within the correct context using runReadAction.

* feat: ✨ implement most other ideProtocolClient methods

* wait until server is running to connect

* remove unnecessary imports, update version

* reformat code and optimize the imports

* fix: 🐛 fix serialization bug

* fix: 🐛 attempt to fix error from jetbrains marketplace

* a few updates

* fix: 🐛 bringing jetbrains up to par

* feat: ✨ highlighted code updates in intellij

* fix: 🚑 fix freezing issue

* fix: 🐛 fix icons, bump version

* feat: ✨ /edit support, other fixes

* quick input, keyboard shortcuts

* fix: 🐛 fix /edit and keyboard shortcuts and lagging on scroll

* feat: 💄 welcome panel

* chore: 🔖 update version

* ide endpoint for websockets

* fix: 🚑 fix freezing problem

* quick input

* fix: 🐛 small jetbrains fixes

* fix: 💄 nicer dropdown that can "drop up"

* fix: 🐛 fix font size for dropdown

* fix: 💄 fix textarea for quickinput

* Preview (#541)

* Strong typing (#533)

* refactor: ♻️ get rid of continuedev.src.continuedev structure

* refactor: ♻️ switching back to server folder

* feat: ✨ make config.py imports shorter

* feat: 🔖 publish as pre-release vscode extension

* refactor: ♻️ refactor and add more completion params to ui

* build: 🏗️ download from preview S3

* fix: 🐛 fix paths

* fix: 💚 package:pre-release

* ci: 💚 more time for tests

* fix: 💚 fix build scripts

* fix: 🐛 fix import in run.py

* fix: 🔖 update version to try again

* ci: 💚 Update package.json version [skip ci]

* refactor: 🔥 don't check for old extensions version

* fix: 🐛 small bug fixes

* fix: 🐛 fix config.py import paths

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 platform-specific builds test #1

* feat: 💚 ship with binary

* fix: 💚 fix copy statement to include.exe for windows

* fix: 💚 cd extension before packaging

* chore: 🔊 count tokens generated

* fix: 💚 remove npm_config_arch

* fix: 💚 publish as pre-release!

* chore: 🔖 update version

* perf: 💚 hardcode distro paths

* fix: 🐛 fix yaml syntax error

* chore: 🔖 update version

* fix: 💚 update permissions and version

* feat: 🐛 kill old server if needed

* feat: 💄 update marketplace icon for pre-release

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ auto-reload for config.py

* feat: 🔧 update default config.py imports

* feat: ✨ codelens in config.py

* feat: ✨ select model param count from UI

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ more model options, ollama error handling

* perf: ⚡ don't show server loading immediately

* fix: 🐛 fixing small UI details

* ci: 💚 Update package.json version [skip ci]

* feat: 🚀 headers param on LLM class

* fix: 🐛 fix headers for openai.;y

* feat: ✨ highlight code on cmd+shift+L

* ci: 💚 Update package.json version [skip ci]

* feat: 💄 sticky top bar in gui.tsx

* fix: 🔊 websocket logging and horizontal scrollbar

* ci: 💚 Update package.json version [skip ci]

* feat: ✨ allow AzureOpenAI Service through GGML

* ci: 💚 Update package.json version [skip ci]

* fix: 🐛 fix automigration

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 upload binaries in ci, download apple silicon

* chore: 🔥 remove notes

* fix: 💚 use curl to download binary

* fix: 💚 set permissions on apple silicon binary

* fix: 💚 testing

* fix: 💚 cleanup file

* fix: 💚 fix preview.yaml

* fix: 💚 only upload once per binary

* fix: 💚 install rosetta

* ci: 💚 download binary after tests

* ci: 💚 Update package.json version [skip ci]

* ci: 💚 prepare ci for merge to main

---------

Co-authored-by: GitHub Action <action@github.com>

* fix: 📝 fix deployent readme

* fix: 🐛 do read operation in readAction

* chore: 🔖 update version

* 🐛 small jetbrains fixes

* ⚡️ exponential backoff jetbrains

* 🐛 fix history loading bug

* 💄 many small ui fixes

* 🐛 fixes freezing problem (actually)

* 🥅 catch errors, other stuff

* 🐛 many jetbrains fixes

* 💄 when no context items found, say in dropdown

* 🎉 VS Code tutorial

* ✨ jetbrains tutorial file

* ⚡️ exponential backoff for ide websockets

* 🎉 unused work on intellij editor inlay

* ✨ server loading progress messages

* ✨ additional progress update

* 💄 fix /edit flickering, keyboard interactions

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Aaron Mihalik <amihalik@users.noreply.github.com>
Co-authored-by: LangLangBart <92653266+LangLangBart@users.noreply.github.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>

* 💚 update binaries in preview workflow

* ci: 🏷 Update PyPI version [skip ci]

* 💚 log prepackaging error

* 💚 remove ci steps for testing

* 💚 make npm run build work on windows

* 🔥 remove codebase embeddings from default config

* 🐛 fix jetbrains input key handling

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🔊 add vscMachineId to user interest form

* 💄 focus continue input box after quick input

* ✨ Show VS Code Tutorial

* ✨ chatml template_messages

* 🐛 fix gh action s3 bucket name, handle ollama err

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* ✏️ automatically remove trailing / from serverUrl

* Nate/better embeddings (#564)

* ♻️ refactoring codebase index folder

* ➕ tree_sitter dependency

* 🐛 solve a few indexing bugs

* ⚡️ code chunker

* ✏️ automatically remove trailing / from serverUrl

* 🎨 introduce Chunk class

* 🎨 finish chunking refactor

* 🐛 call format_exception so that 3.8-compatible

* ci: 🏷 Update PyPI version [skip ci]

* register/unregister shortcuts instead of unregistering the commands themselves (#568)

* 💚 fix tree_sitter_languages build for windows

* 🚸 allow toggling telemetry from vscode settings

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🔊 update logging

* ♻️ refactor extension folders and react-app

* fix: hotkey for new session (#572)

* 💄 file icons, preview context items

* 💄 toggle to show context items

* 💄 nicer preview dropdown

* ci: 🏷 Update PyPI version [skip ci]

* 💚 fix path in yaml

* ci: 🏷 Update PyPI version [skip ci]

* 💚 one more path fix to GH workflows

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 💄 inline keyboard shortcut suggestions

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 👷 parameterize .spec file

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🐛 use platform-specific keyboard shortcut icons

* ci: 🏷 Update PyPI version [skip ci]

* ci: 💚 Update package.json version [skip ci]

* 🧑‍💻 refresh contents of highlighted ranges

* 🐛 stop description and title gen if step stopped

* 🐛 fix hidden items in dropdown by setting height

* 🔖 update compatibility for eap jetbrains

* ✨ continue ascii art

* ♻️ use message IDs

* 🚧 can at start the server

* ⚡️ switch to socket.io!

* 🚧 socket.io for GUI

* 🚧 working out proper object composition

* 🏷️ regenerate types

* 🚧 implement first version of SessionState reducer

* 🚧 Fixed all type errors in gui

* 🚧 basic chat is working!

* 🚧 prompt inspection

* 🚧 mostly fixed session loading/saving

* 🚧 slash commands and context providers

* 🚧 inspect prompt

* 🚧 highlighted code

* 🚧 preview context items

* ✨ state persistence

* 🚧 /edit

* 🚧 settings

* 🚧 change models

* 🚧 /share

* 🚧 fixed saving history

* 🚧 /clear

* undo reset

* 🐛 small fixes

* 🚧 intellij socket.io

* 🐛 refactor for Intellij

* 🐛 fix gui connection, ci

* 🐛 health endpoint

* 💚 give more time in ci

* 💚 health

* 💚 testing ci server start

* 🐛 don't ignore stdio

* 💚 pysqlite3-binary

* 💚 import new sqlite

* 👷 build sqlite from source

* 💡 ci

* 📌 try building with python3.11

* 👷 build sqlite, try again

* 💚 if ubuntu

* 💚 ubuntu latest

* ✅ don't call done in test

* 📌 use newer ubuntu

* ci: 💚 Update package.json version [skip ci]

* 🐛 uncomment testing tweaks

* ci: 💚 Update package.json version [skip ci]

* 🐛 small fixes

* ⚡️ limit to avoid max msg size with socketio

* 🐛 ignore other msg types in ide

* ci: 💚 Update package.json version [skip ci]

* ✨ debug terminal

* ci: 💚 Update package.json version [skip ci]

* 🐛 merge ranges

* 🐛 fix vscMediaUrl

* ci: 💚 Update package.json version [skip ci]

* ✨ Ask Continue

* ci: 💚 Update package.json version [skip ci]

* 👷 don't publish binaries from main

* 📝 fix docs

---------

Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: Bishwendu Kundu <bishwenduk029@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: Aaron Mihalik <amihalik@users.noreply.github.com>
Co-authored-by: LangLangBart <92653266+LangLangBart@users.noreply.github.com>
Co-authored-by: James Vogel <jim.m.vogel@gmail.com>

* 🔥 remove pypi publishing from preview.yaml

* ci: 🏷 Update PyPI version [skip ci]

* 💚 fix main ci by using pip, not poetry

* ci: 🏷 Update PyPI version [skip ci]

* 💚 Update package.json version [skip ci]

* Fix query strip problem (#594)

* add_func_remove_prefix_and_suffix_on_util

* fix_query_strip_with_added_func

* Prevent duplicate calls to keyDown events due to IME (#592)

When typing non-latin characters (such as Korean, Japanese or  Chinese) in the MainInputWindow, the KeyDown event is called duplicately due to IME. 
As a result, non-latin character input does not work properly.

* 🐛 solve minified react bug

* ci: 🏷 Update PyPI version [skip ci]

* 💚 Update package.json version [skip ci]

* 🐛 small bug fixes

* 💄 progress bar for embeddings indexing

* 🎨 small improvements

* 💄 icons for slash commands

* ⚡️ file links and custom codebase prompt

* ⚡️ many small /codebase improvements

* ✨ CLI index + search

* 💄 lock scroll on context item previews

* 🐛 meilisearch fixes, option to disable

* ⚡️ improvements to /codebase

---------

Co-authored-by: Mase Graye <mase.graye@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: jwalksir <35584631+jwalksir@users.noreply.github.com>
Co-authored-by: Peter Zaback <pzaback@gmail.com>
Co-authored-by: Bishwendu Kundu <bishwenduk029@gmail.com>
Co-authored-by: Aaron Mihalik <amihalik@users.noreply.github.com>
Co-authored-by: LangLangBart <92653266+LangLangBart@users.noreply.github.com>
Co-authored-by: James Vogel <jim.m.vogel@gmail.com>
Co-authored-by: 김보경/DAXTF <82003678+Bogyie@users.noreply.github.com>
Co-authored-by: Benedict Lee <benedict.lee@kakaocorp.com>
This commit is contained in:
Nate Sesti 2023-11-02 23:26:23 -07:00 • committed by GitHub
parent 7e6a054cee
commit bc8d7b2b45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
82 changed files with 5316 additions and 2074 deletions

View file

@ -286,7 +286,7 @@ jobs:
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git commit -am "ci: 🏷 Update PyPI version [skip ci]"
git commit -am "💚 Update package.json version [skip ci]"
- name: Push changes
uses: ad-m/github-push-action@master

View file

@ -6,48 +6,6 @@ on:
- preview
jobs:
# pypi-deployment:
# runs-on: ubuntu-latest
# permissions:
# contents: write
# steps:
# - name: Check out code
# uses: actions/checkout@v2
# - name: Set up Python
# uses: actions/setup-python@v4
# with:
# python-version: "3.10.8"
# - name: Install dependencies
# run: |
# python -m pip install --upgrade pip
# pip install poetry
# - name: Install project dependencies
# run: cd server && poetry install
# - name: Configure Poetry Token
# run: cd server && poetry config pypi-token.pypi ${{ secrets.PYPI_API_TOKEN }}
# - name: Bump the version
# run: cd server && poetry version patch
# - name: Build and publish the package
# run: cd server && poetry publish --build
# - name: Commit changes
# run: |
# git config --local user.email "action@github.com"
# git config --local user.name "GitHub Action"
# git commit -am "ci: 🏷 Update PyPI version [skip ci]"
# - name: Push changes
# uses: ad-m/github-push-action@master
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}
build:
strategy:
matrix:
@ -315,7 +273,7 @@ jobs:
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git commit -am "ci: 💚 Update package.json version [skip ci]"
git commit -am "💚 Update package.json version [skip ci]"
- name: Push changes
uses: ad-m/github-push-action@master

20
.vscode/launch.json vendored
View file

@ -76,6 +76,24 @@
"justMyCode": false,
"subProcess": false
},
{
"name": "Index",
"type": "python",
"request": "launch",
"module": "server.continuedev",
"args": ["index", "server/continuedev"],
"justMyCode": false,
"subProcess": false
},
{
"name": "Query",
"type": "python",
"request": "launch",
"module": "server.continuedev",
"args": ["search", "--directory", "server/continuedev", "Ollama"],
"justMyCode": false,
"subProcess": false
},
{
"name": "Extension (VSCode)",
"type": "extensionHost",
@ -83,7 +101,7 @@
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
"${workspaceFolder}/extensions/vscode",
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox/example.ts",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],

View file

@ -1,3 +1,4 @@
{
"python.defaultInterpreterPath": "${workspaceFolder}/server/.venv/bin/python3"
"python.defaultInterpreterPath": "${workspaceFolder}/server/.venv/bin/python3",
"continue.showInlineTip": false
}

3
.vscode/tasks.json vendored
View file

@ -60,6 +60,9 @@
"presentation": {
"revealProblems": "onProblem",
"clear": true
},
"options": {
"cwd": "${workspaceFolder}/extensions/vscode"
}
},
//

View file

@ -1,5 +1,7 @@
> 🎁 **New! [Try out the new JetBrains extension (Alpha)](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
> Interested in a 1-on-1, 15 minute introduction to Continue? Fill out [this form](https://forms.gle/H6U6rGDX55oWSWjC8) and we'll get in touch!
![Continue logo](media/c_d.png)
<h1 align="center">Continue</h1>
@ -62,7 +64,7 @@ Press `cmd+shift+r` (MacOS) / `ctrl+shift+r` (Windows) when you come across an e
### Download for [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)
By default, Continue uses `GPT-4` and `GPT-3.5-turbo` via the OpenAI API. You can adjust the config to use different Large Language Models (LLMs), including local, private models. Read more [here](https://continue.dev/docs/customization/models).
By default, Continue uses `GPT-4` and `GPT-3.5-turbo` via the OpenAI API. You can adjust the config to use different Large Language Models (LLMs) like [Code Llama, Claude 2, WizardCoder, PaLM 2, and more](https://github.com/continuedev/what-llm-to-use). Read more [here](https://continue.dev/docs/customization/models).
### [Run the server manually](https://continue.dev/docs/walkthroughs/manually-run-continue)

View file

@ -24,7 +24,7 @@ Local Models
Open-Source Models (not local)
- [TogetherLLM](../reference/Models/togetherllm.md) - Use any model from the [Together Models list](https://docs.together.ai/docs/models-inference) with your Together API key.
- [TogetherLLM](../reference/Models/togetherllm.md) - Use any model from the [Together Models list](https://docs.together.ai/docs/inference-models) with your Together API key.
- [ReplicateLLM](../reference/Models/replicatellm.md) - Use any open-source model from the [Replicate Streaming List](https://replicate.com/collections/streaming-language-models) with your Replicate API key.
- [HuggingFaceInferenceAPI](../reference/Models/huggingfaceinferenceapi.md) - Use any open-source model from the [Hugging Face Inference API](https://huggingface.co/inference-api) with your Hugging Face token.

View file

@ -9,7 +9,7 @@ keywords: [no internet, air-gapped, local model]
Continue can be run even on an air-gapped computer if you use a local model. You'll have to make a few adjustments for this to work.
1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extensions/vscode/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
2. In VS Code settings, search "continue" and check the box that says "Manually Running Server". This will stop Continue from trying to kill and redownload the server binary.
3. Follow instructions to [run Continue manually](./manually-run-continue.md).
4. Open `~/.continue/config.py` and set `allow_anonymous_telemetry=False`. This will stop Continue from attempting requests to PostHog.

View file

@ -36,7 +36,7 @@ fun getDiffDirectory(): File {
return diffDir
}
fun escapeFilepath(filepath: String): String {
return filepath.replace("/", "\$f\$").replace("\\", "\$b\$")
return filepath.replace("/", "_f_").replace("\\", "_b_")
}
interface DiffInfo {
@ -175,7 +175,7 @@ class DiffManager(private val project: Project): DumbAware {
override fun createActions(): Array<Action> {
val okAction = getOKAction()
val cmdCtrl = if (System.getProperty("os.name").toLowerCase().contains("mac")) "⌘" else "⌃"
okAction.putValue(Action.NAME, "Accept ($cmdCtrl ⇧ ↵)")
okAction.putValue(Action.NAME, "Accept ($cmdCtrl ⇧ ⏎)")
val cancelAction = getCancelAction()
cancelAction.putValue(Action.NAME, "Reject ($cmdCtrl ⇧ ⌫)")

View file

@ -62,6 +62,6 @@ select the code and toggle the /edit slash command"""
# e.g.) write comments
"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ↵] or reject [⌘ ⇧ ⌫] the edit"""
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
# endregion

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -64,7 +64,7 @@ select the code and toggle the /edit slash command"""
"""Step 3: Request an edit and press Enter"""
"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ↵] or reject [⌘ ⇧ ⌫] the edit"""
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
# endregion

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.1.40",
"version": "0.1.42",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.1.40",
"version": "0.1.42",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.1.40",
"version": "0.1.42",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -719,7 +719,7 @@ class IdeProtocolClient {
}
async debugTerminal() {
const contents = await this.getTerminalContents();
const contents = (await this.getTerminalContents()).trim();
this.send("debugTerminal", v4(), { contents });
}
}

View file

@ -63,7 +63,7 @@ class DiffManager {
}
private escapeFilepath(filepath: string): string {
return filepath.replace(/\//g, "$f$").replace(/\\/g, "$b$");
return filepath.replace(/\//g, "_f_").replace(/\\/g, "_b_");
}
private remoteTmpDir: string = "/tmp/continue";

View file

@ -0,0 +1,148 @@
import React from "react";
import { defaultBorderRadius, lightGray, secondaryDark } from ".";
import styled from "styled-components";
import { getFontSize, getMarkdownLanguageTagForFile } from "../util";
import FileIcon from "./FileIcon";
import HeaderButtonWithText from "./HeaderButtonWithText";
import { ContextItem } from "../schema/ContextItem";
import { postToIde } from "../vscode";
import {
ArrowUpLeftIcon,
ChevronDownIcon,
ChevronUpIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { deleteContextWithIds } from "../redux/slices/sessionStateReducer";
import { useDispatch } from "react-redux";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
const PreviewMarkdownDiv = styled.div<{ scroll: boolean }>`
padding: 0px;
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
margin: 8px;
overflow: hidden;
position: relative;
& div {
background-color: ${secondaryDark};
}
& code {
overflow: ${(props) => (props.scroll ? "scroll" : "hidden")} !important;
}
`;
const PreviewMarkdownHeader = styled.p`
margin: 0;
padding: 4px 8px;
border-bottom: 1px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize()}px;
display: flex;
align-items: center;
`;
interface CodeSnippetPreviewProps {
item: ContextItem;
index: number;
}
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const dispatch = useDispatch();
const [scrollLocked, setScrollLocked] = React.useState(true);
const [hovered, setHovered] = React.useState(false);
return (
<PreviewMarkdownDiv
scroll={!scrollLocked}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
<PreviewMarkdownHeader className="flex justify-between">
<div className="flex items-center">
<FileIcon
height="20px"
width="20px"
filename={props.item.description.name}
></FileIcon>
{props.item.description.name}
</div>
<div className="flex items-center">
<HeaderButtonWithText
text="View"
onClick={() => {
if (props.item.description.id.provider_title === "file") {
postToIde("showFile", {
filepath: props.item.description.description,
});
} else if (props.item.description.id.provider_title === "code") {
const lines = props.item.description.name
.split("(")[1]
.split(")")[0]
.split("-");
postToIde("showLines", {
filepath: props.item.description.description,
start: parseInt(lines[0]) - 1,
end: parseInt(lines[1]) - 1,
});
} else {
postToIde("showVirtualFile", {
name: props.item.description.name,
content: props.item.content,
});
}
}}
>
<ArrowUpLeftIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
<HeaderButtonWithText
text="Delete"
onClick={() => {
dispatch(
deleteContextWithIds({
ids: [props.item.description.id],
index: props.index,
})
);
}}
>
<TrashIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
</div>
</PreviewMarkdownHeader>
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
props.item.description.description
)}\n${props.item.content}\n\`\`\``}
maxHeight={200}
/>
</pre>
{hovered && (
<HeaderButtonWithText
className="bottom-1 right-1 absolute"
text={scrollLocked ? "Scroll" : "Lock Scroll"}
>
{scrollLocked ? (
<ChevronUpIcon
width="1.2em"
height="1.2em"
onClick={() => setScrollLocked(false)}
/>
) : (
<ChevronDownIcon
width="1.2em"
height="1.2em"
onClick={() => setScrollLocked(true)}
/>
)}
</HeaderButtonWithText>
)}
</PreviewMarkdownDiv>
);
}
export default CodeSnippetPreview;

View file

@ -22,8 +22,19 @@ import {
ArrowLeftIcon,
ArrowRightIcon,
ArrowUpLeftIcon,
ArrowUpOnSquareIcon,
BeakerIcon,
ChevronDownIcon,
ChevronRightIcon,
Cog6ToothIcon,
CommandLineIcon,
FolderIcon,
GlobeAltIcon,
HashtagIcon,
MagnifyingGlassIcon,
PaintBrushIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
@ -39,6 +50,7 @@ import {
getMarkdownLanguageTagForFile,
getMetaKeyLabel,
getPlatform,
isMetaEquivalentKeyPressed,
} from "../util";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
import { setTakenActionTrue } from "../redux/slices/miscSlice";
@ -55,9 +67,35 @@ import {
newSession,
setActive,
} from "../redux/slices/sessionStateReducer";
import RingLoader from "./RingLoader";
import CodeSnippetPreview from "./CodeSnippetPreview";
const SEARCH_INDEX_NAME = "continue_context_items";
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
file: FolderIcon,
terminal: CommandLineIcon,
diff: PlusIcon,
search: MagnifyingGlassIcon,
url: GlobeAltIcon,
"/edit": PaintBrushIcon,
"/clear": TrashIcon,
"/test": BeakerIcon,
"/config": Cog6ToothIcon,
"/comment": HashtagIcon,
"/share": ArrowUpOnSquareIcon,
"/cmd": CommandLineIcon,
"/codebase": SparklesIcon,
};
function DropdownIcon(props: { provider: string; className?: string }) {
const Icon = ICONS_FOR_DROPDOWN[props.provider];
if (!Icon) {
return null;
}
return <Icon className={props.className} height="1.2em" width="1.2em" />;
}
// #region styled components
const gradient = keyframes`
@ -100,8 +138,8 @@ const GradientBorder = styled.div<{
margin-top: 8px;
`;
const HiddenHeaderButtonWithText = styled.button`
opacity: 0;
const HiddenHeaderButtonWithText = styled.button<{ pinVisible: boolean }>`
opacity: ${({ pinVisible }) => (pinVisible ? 1 : 0)};
background-color: transparent;
border: none;
outline: none;
@ -128,28 +166,6 @@ const HiddenHeaderButtonWithText = styled.button`
const mainInputFontSize = getFontSize();
const PreviewMarkdownDiv = styled.div`
padding: 0px;
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
margin: 8px;
overflow: hidden;
& div {
background-color: ${secondaryDark};
}
`;
const PreviewMarkdownHeader = styled.p`
margin: 0;
padding: 4px 8px;
border-bottom: 1px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize()}px;
display: flex;
align-items: center;
`;
const MainTextInput = styled.textarea<{
inQueryForDynamicProvider: boolean;
fontSize?: number;
@ -224,7 +240,10 @@ const Ul = styled.ul<{
6
}px);`}
position: absolute;
background: ${vscBackground};
/* background: ${vscBackground}; */
background-color: transparent;
backdrop-filter: blur(12px);
color: ${vscForeground};
max-height: ${UlMaxHeight}px;
margin-left: 1px;
@ -253,7 +272,7 @@ const Li = styled.li<{
isLastItem: boolean;
}>`
background-color: ${({ highlighted }) =>
highlighted ? buttonColor + "66" : secondaryDark};
highlighted ? buttonColor + "66" : "transparent"};
${({ selected }) => selected && "font-weight: bold;"}
padding: 0.5rem 0.5rem;
display: flex;
@ -400,7 +419,13 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const selectContextItem = useCallback(
async (id: string, query: string) => {
const timeout = setTimeout(() => {
setWaitingForContextItem(true);
}, 0.1);
const contextItem = await client?.getContextItem(id, query);
clearTimeout(timeout);
setWaitingForContextItem(false);
if (!contextItem) return;
if (props.isMainInput) {
dispatch(addContextItem(contextItem));
} else if (typeof props.index !== "undefined") {
@ -552,6 +577,8 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
},
});
const [waitingForContextItem, setWaitingForContextItem] = useState(false);
useEffect(() => {
if (downshiftProps.highlightedIndex < 0) {
downshiftProps.setHighlightedIndex(0);
@ -817,10 +844,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
>
+ Add Context
</span>
{(downshiftProps.inputValue?.startsWith("/edit") ||
(inputFocused &&
metaKeyPressed &&
downshiftProps.inputValue?.length > 0)) && (
{downshiftProps.inputValue?.startsWith("/edit") && (
<span className="float-right">Inserting at cursor</span>
)}
</div>
@ -854,6 +878,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
)}
<HiddenHeaderButtonWithText
pinVisible={selectedContextItems.length >= 8}
className={
selectedContextItems.length > 0
? `pill-button-${props.index || "main"}`
@ -886,103 +911,143 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
}}
>
<TrashIcon width="1.4em" height="1.4em" />
<TrashIcon width="1.2em" height="1.2em" />
</HiddenHeaderButtonWithText>
{selectedContextItems.map((item, idx) => {
return (
<PillButton
inputIndex={props.index}
areMultipleItems={selectedContextItems.length > 1}
key={`${item.description.id.item_id}${idx}`}
item={item}
editing={
item.editing &&
(inputRef.current as any)?.value?.startsWith("/edit")
}
editingAny={(inputRef.current as any)?.value?.startsWith(
"/edit"
)}
stepIndex={props.index}
index={idx}
onDelete={() => {
dispatch(
deleteContextWithIds({
ids: [item.description.id],
index: props.index,
})
);
inputRef.current?.focus();
if (
(item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name) ||
(item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name)
) {
setPreviewingContextItem(undefined);
setFocusedContextItem(undefined);
}
}}
onClick={(e) => {
if (
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
) {
setFocusedContextItem(undefined);
} else {
setFocusedContextItem(item);
}
}}
onBlur={() => {
setFocusedContextItem(undefined);
}}
toggleViewContent={() => {
setPreviewingContextItem((prev) => {
if (!prev) return item;
if (
prev.description.id.item_id ===
item.description.id.item_id &&
prev.description.id.provider_name ===
item.description.id.provider_name
) {
return undefined;
} else {
return item;
{selectedContextItems.length < 8 ? (
<>
{selectedContextItems.map((item, idx) => {
return (
<PillButton
inputIndex={props.index}
areMultipleItems={selectedContextItems.length > 1}
key={`${item.description.id.item_id}${idx}`}
item={item}
editing={
item.editing &&
(inputRef.current as any)?.value?.startsWith("/edit")
}
});
}}
previewing={
item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
focusing={
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
prefixInputWithEdit={(should) => {
if (!should && inputRef.current?.value.startsWith("/edit")) {
downshiftProps.setInputValue(
inputRef.current?.value.replace("/edit ", "")
);
}
if (downshiftProps.inputValue.startsWith("/edit")) return;
downshiftProps.setInputValue(
`/edit ${downshiftProps.inputValue}`
);
editingAny={(inputRef.current as any)?.value?.startsWith(
"/edit"
)}
stepIndex={props.index}
index={idx}
onDelete={() => {
dispatch(
deleteContextWithIds({
ids: [item.description.id],
index: props.index,
})
);
inputRef.current?.focus();
if (
(item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name) ||
(item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id
.provider_name ===
item.description.id.provider_name)
) {
setPreviewingContextItem(undefined);
setFocusedContextItem(undefined);
}
}}
onClick={(e) => {
if (
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
) {
setFocusedContextItem(undefined);
} else {
setFocusedContextItem(item);
}
}}
onBlur={() => {
setFocusedContextItem(undefined);
}}
toggleViewContent={() => {
setPreviewingContextItem((prev) => {
if (!prev) return item;
if (
prev.description.id.item_id ===
item.description.id.item_id &&
prev.description.id.provider_name ===
item.description.id.provider_name
) {
return undefined;
} else {
return item;
}
});
}}
previewing={
item.description.id.item_id ===
previewingContextItem?.description.id.item_id &&
previewingContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
focusing={
item.description.id.item_id ===
focusedContextItem?.description.id.item_id &&
focusedContextItem?.description.id.provider_name ===
item.description.id.provider_name
}
prefixInputWithEdit={(should) => {
if (
!should &&
inputRef.current?.value.startsWith("/edit")
) {
downshiftProps.setInputValue(
inputRef.current?.value.replace("/edit ", "")
);
}
if (downshiftProps.inputValue.startsWith("/edit")) return;
downshiftProps.setInputValue(
`/edit ${downshiftProps.inputValue}`
);
inputRef.current?.focus();
}}
/>
);
})}
{waitingForContextItem && (
<RingLoader
period={1.5}
className="ml-0 mt-1 mb-0"
width="1.0em"
height="1.0em"
size={32}
wFull={false}
></RingLoader>
)}
</>
) : (
<div
onClick={() => {
if (props.isMainInput) {
setShowContextToggleOn((prev) => !prev);
} else {
inputRef.current?.focus();
}}
/>
);
})}
setShowContextItemsIfNotMain(true);
}
}}
style={{
color: lightGray,
backgroundColor: vscBackground,
fontSize: "12px",
alignItems: "center",
display: "flex",
height: "100%",
cursor: "pointer",
}}
>
{selectedContextItems.length} snippets selected
</div>
)}
{/* {selectedContextItems.length > 0 && (
<HeaderButtonWithText
onClick={() => {
@ -1030,24 +1095,10 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
{showContextToggleOn && (
<div>
{selectedContextItems.map((item) => (
<PreviewMarkdownDiv>
<PreviewMarkdownHeader>
<FileIcon
height="20px"
width="20px"
filename={item.description.name}
></FileIcon>
{item.description.name}
</PreviewMarkdownHeader>
<pre className="m-0">
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
item.description.description
)}\n${item.content}\n\`\`\``}
maxHeight={200}
/>
</pre>
</PreviewMarkdownDiv>
<CodeSnippetPreview
index={props.index}
item={item}
></CodeSnippetPreview>
))}
</div>
)}
@ -1107,6 +1158,11 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
setInputFocused(false);
},
onKeyDown: (event) => {
// Prevent duplicate calls to keyDown events due to IME.
if (isComposing) {
return;
}
dispatch(setBottomMessage(undefined));
if (event.key === "Enter" && event.shiftKey) {
// Prevent Downshift's default 'Enter' behavior.
@ -1375,15 +1431,18 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
filename={item.name}
></FileIcon>
)}
<DropdownIcon provider={item.name} className="mr-2" />
<DropdownIcon provider={item.id} className="mr-2" />
{item.name}
{" "}
</div>
<span
style={{
color: lightGray,
color: vscForeground,
float: "right",
textAlign: "right",
}}
hidden={downshiftProps.highlightedIndex !== index}
>
{item.description}
</span>
@ -1396,7 +1455,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
<ArrowRightIcon
width="1.2em"
height="1.2em"
color={lightGray}
color={vscForeground}
className="ml-2 flex-shrink-0"
/>
)}
@ -1426,6 +1485,41 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
</Ul>
</div>
{props.isMainInput && (
<>
<div
style={{
color: lightGray,
fontSize: "10px",
backgroundColor: vscBackground,
width: "calc(100% - 16px)",
height: "0",
marginTop: "4px",
}}
>
<span
onClick={() => {
const inputValue = downshiftProps.inputValue;
if (inputValue.startsWith("/codebase")) {
downshiftProps.setInputValue(
inputValue.replace("/codebase ", "")
);
} else {
downshiftProps.setInputValue("/codebase " + inputValue);
}
inputRef.current?.focus();
}}
className={"hover:underline cursor-pointer float-right"}
>
{downshiftProps.inputValue.startsWith("/codebase")
? "Using codebase"
: "⌘ ⏎ Use codebase"}
</span>
</div>
<br />
</>
)}
{props.isMainInput && (
<ContinueButton
disabled={

View file

@ -0,0 +1,64 @@
import React from "react";
import styled from "styled-components";
import { StyledTooltip, lightGray, vscForeground } from ".";
const ProgressBarWrapper = styled.div`
width: 100px;
height: 6px;
border-radius: 6px;
border: 0.5px solid ${lightGray};
margin-top: 6px;
`;
const ProgressBarFill = styled.div<{ completed: number; color?: string }>`
height: 100%;
background-color: ${(props) => props.color || vscForeground};
border-radius: inherit;
transition: width 0.2s ease-in-out;
width: ${(props) => props.completed}%;
`;
const GridDiv = styled.div`
display: grid;
grid-template-rows: 1fr auto;
align-items: center;
justify-items: center;
`;
const P = styled.p`
margin: 0;
margin-top: 2px;
font-size: 11.5px;
color: ${lightGray};
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
interface ProgressBarProps {
completed: number;
total: number;
}
const IndexingProgressBar = ({ completed, total }: ProgressBarProps) => {
const fillPercentage = Math.min(100, Math.max(0, (completed / total) * 100));
return (
<>
<GridDiv data-tooltip-id="usage_progress_bar">
<ProgressBarWrapper>
<ProgressBarFill completed={fillPercentage} />
</ProgressBarWrapper>
<P>Indexing ({Math.trunc((completed / total) * 100)}%)</P>
</GridDiv>
<StyledTooltip id="usage_progress_bar" place="bottom">
{
"Continue is indexing your codebase locally. You can find the index in ~/.continue/embeddings."
}
</StyledTooltip>
</>
);
};
export default IndexingProgressBar;

View file

@ -3,7 +3,7 @@ import { StyledTooltip } from ".";
import ReactDOM from "react-dom";
const InfoHover = ({ msg }: { msg: string }) => {
const id = "info-hover";
const id = `info-hover-${encodeURIComponent(msg)}`;
const tooltipPortalDiv = document.getElementById("tooltip-portal-div");

View file

@ -22,6 +22,7 @@ import ModelSelect from "./ModelSelect";
import ProgressBar from "./ProgressBar";
import { newSession } from "../redux/slices/sessionStateReducer";
import { getFontSize } from "../util";
import IndexingProgressBar from "./IndexingProgressBar";
// #region Styled Components
const FOOTER_HEIGHT = "1.8em";
@ -73,6 +74,8 @@ const Footer = styled.footer`
align-items: center;
width: calc(100% - 16px);
height: ${FOOTER_HEIGHT};
background-color: transparent;
backdrop-filter: blur(12px);
overflow: hidden;
`;
@ -105,6 +108,9 @@ const Layout = () => {
const showDialog = useSelector(
(state: RootStore) => state.uiState.showDialog
);
const indexingProgress = useSelector(
(state: RootStore) => state.serverState.indexingProgress
);
const defaultModel = useSelector(
(state: RootStore) => (state.serverState.config as any).models?.default
@ -217,7 +223,8 @@ const Layout = () => {
/>
)}
<ModelSelect />
{defaultModel?.class_name === "OpenAIFreeTrial" &&
{indexingProgress >= 1 && // Would take up too much space together with indexing progress
defaultModel?.class_name === "OpenAIFreeTrial" &&
defaultModel?.api_key === "" &&
(location.pathname === "/settings" ||
parseInt(localStorage.getItem("ftc") || "0") >= 125) && (
@ -226,6 +233,13 @@ const Layout = () => {
total={250}
/>
)}
{indexingProgress < 1 && (
<IndexingProgressBar
completed={indexingProgress * 100}
total={100}
/>
)}
</div>
<HeaderButtonWithText
text="Help"

View file

@ -0,0 +1,65 @@
import React, { useCallback, useEffect, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, secondaryDark } from ".";
import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../redux/store";
import { postToIde } from "../vscode";
const StyledCode = styled.code<{ link: boolean }>`
color: ${(props) => (props.link ? "#ff43433" : "#f78383")};
word-wrap: break-word;
border-radius: ${defaultBorderRadius};
background-color: ${secondaryDark};
${(props) => props.link && "cursor: pointer;"}
&:hover {
${(props) => props.link && "text-decoration: underline;"}
}
`;
function LinkableCode(props: any) {
const contextItems = useSelector(
(store: RootStore) => store.sessionState.context_items
);
const [linkingDone, setLinkingDone] = useState(false);
const [isLink, setIsLink] = useState(false);
const [filepath, setFilepath] = useState("");
useEffect(() => {
if (linkingDone) return;
// Get filename from props.children
let filename: string | undefined = undefined;
if (typeof props.children === "string") {
filename = props.children;
} else if (
Array.isArray(props.children) &&
props.children.length > 0 &&
typeof props.children[0] === "string"
) {
filename = props.children[0];
}
if (!filename) return;
// Check if matches any context item's filepath
let link = false;
for (let contextItem of contextItems) {
if (contextItem.description.description.endsWith(filename)) {
link = true;
setFilepath(contextItem.description.description);
break;
}
}
setIsLink(link);
setLinkingDone(true);
}, [linkingDone, contextItems]);
const onClick = () => {
postToIde("showFile", { filepath });
};
return <StyledCode {...props} onClick={onClick} link={isLink} />;
}
export default LinkableCode;

View file

@ -27,9 +27,9 @@ const Button = styled.button<{ fontSize?: number }>`
color: ${vscForeground};
background-color: ${secondaryDark};
border-radius: ${defaultBorderRadius};
padding: 4px;
padding-left: 8px;
padding-right: 8px;
padding: 3.5px;
padding-left: 3px;
padding-right: 5px;
overflow: hidden;
font-size: ${(props) => props.fontSize || getFontSize()}px;
@ -186,7 +186,7 @@ const PillButton = (props: PillButtonProps) => {
<div style={{ position: "relative" }}>
<Container previewing={props.previewing} ref={pillContainerRef}>
<StyledButton
fontSize={getFontSize()}
fontSize={getFontSize() - 1}
borderColor={
props.editing ? (warning ? "red" : undefined) : undefined
}

View file

@ -1,6 +1,6 @@
import React from "react";
import styled, { keyframes } from "styled-components";
import { buttonColor, vscBackground, vscForeground } from ".";
import { vscForeground } from ".";
const rotate = keyframes`
0% {
@ -11,10 +11,14 @@ const rotate = keyframes`
}
`;
const LoaderSvg = styled.svg`
const LoaderSvg = styled.svg<{
width?: string;
height?: string;
period?: number;
}>`
transform: rotate(-90deg);
width: 40px;
height: 40px;
width: ${(props) => props.width || "40px"};
height: ${(props) => props.height || "40px"};
opacity: 50%;
circle {
@ -23,17 +27,41 @@ const LoaderSvg = styled.svg`
stroke-width: 2;
stroke-dasharray: 100;
stroke-dashoffset: 0;
animation: ${rotate} 6s ease-out infinite;
animation: ${rotate} ${(props) => props.period || 6}s ease-out infinite;
stroke-linecap: round;
}
`;
const RingLoader = () => (
<div className="m-auto w-full text-center mt-2">
<LoaderSvg viewBox="0 0 32 32">
<circle cx="16" cy="16" r="14" />
</LoaderSvg>
</div>
);
const RingLoader = (props: {
size: number;
wFull?: boolean;
className?: string;
width?: string;
height?: string;
period?: number;
}) => {
const viewBox = `0 0 ${props.size} ${props.size}`;
const size = (props.size / 2).toString();
const r = "14"; //(props.size / 2 - 2).toString();
return (
<div
className={
"m-auto text-center mt-2" +
(props.wFull === false ? "" : " w-full") +
" " +
props.className
}
>
<LoaderSvg
period={props.period}
width={props.width}
height={props.height}
viewBox={viewBox}
>
<circle cx={size} cy={size} r={r} />
</LoaderSvg>
</div>
);
};
export default RingLoader;

View file

@ -8,6 +8,7 @@ import {
} from ".";
import MarkdownPreview from "@uiw/react-markdown-preview";
import { getFontSize } from "../util";
import LinkableCode from "./LinkableCode";
const StyledMarkdownPreviewComponent = styled(MarkdownPreview)<{
light?: boolean;
@ -71,6 +72,10 @@ function StyledMarkdownPreview(props: StyledMarkdownPreviewProps) {
</a>
);
},
code: ({ node, ...props }) => {
console.log(node, props);
return <LinkableCode {...props}></LinkableCode>;
},
}}
className={props.className}
maxHeight={props.maxHeight}

View file

@ -1,5 +1,5 @@
// Write a component that displays a dialog box with a text field and a button.
import React, { useEffect, useState } from "react";
import React, { isValidElement, useEffect, useState } from "react";
import styled from "styled-components";
import { Button, secondaryDark, vscBackground, vscForeground } from ".";
import { isMetaEquivalentKeyPressed } from "../util";
@ -71,6 +71,10 @@ const TextDialog = (props: {
};
}, [props]);
if (!isValidElement(props.message) && typeof props.message !== "string") {
return null;
}
return (
<ScreenCover
onClick={() => {
@ -86,7 +90,7 @@ const TextDialog = (props: {
<Dialog>
{typeof props.message === "string" ? (
<ReactMarkdown>{props.message || ""}</ReactMarkdown>
) : (
) : !React.isValidElement(props.message) ? null : (
props.message
)}
</Dialog>

View file

@ -71,8 +71,8 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
description: "Edit Highlighted Code",
},
{
mac: "⌘ ⇧ ↵",
windows: "⌃ ⇧ ↵",
mac: "⌘ ⇧ ⏎",
windows: "⌃ ⇧ ⏎",
description: "Accept Diff",
},
{
@ -105,6 +105,11 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
},
];
const jetbrainsShortcuts: KeyboardShortcutProps[] = [
@ -119,8 +124,8 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
description: "Edit Highlighted Code",
},
{
mac: "⌘ ⇧ ↵",
windows: "⌃ ⇧ ↵",
mac: "⌘ ⇧ ⏎",
windows: "⌃ ⇧ ⏎",
description: "Accept Diff",
},
{
@ -148,6 +153,11 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
windows: "⌃ ⌫",
description: "Stop Active Step",
},
{
mac: "Tab",
windows: "Tab",
description: "Toggle between context items",
},
];
function KeyboardShortcutsDialog() {

View file

@ -120,6 +120,12 @@ class ContinueGUIClientProtocol extends AbstractContinueGUIClientProtocol {
});
}
onIndexingProgress(callback: (progress: number) => void) {
this.messenger?.onMessageType("indexing_progress", (data: any) => {
callback(data.progress);
});
}
onConfigUpdate(callback: (config: ContinueConfig) => void) {
this.messenger?.onMessageType("config_update", (data: any) => {
callback(data);

View file

@ -15,6 +15,7 @@ import { RootStore } from "../redux/store";
import {
setConfig,
setContextProviders,
setIndexingProgress,
setSlashCommands,
} from "../redux/slices/serverStateReducer";
import {
@ -68,6 +69,10 @@ function useSetup(
dispatch(processSessionUpdate(update));
});
client.onIndexingProgress((progress) => {
dispatch(setIndexingProgress(progress));
});
client.onAddContextItem((item) => {
dispatch(addContextItem(item));
});

View file

@ -1,5 +1,5 @@
import { useDispatch } from "react-redux";
import { useRouteError } from "react-router-dom";
import { useNavigate, useRouteError } from "react-router-dom";
import { newSession } from "../redux/slices/sessionStateReducer";
import useContinueGUIProtocol from "../hooks/useContinueClient";
import ContinueButton from "../components/ContinueButton";
@ -10,6 +10,7 @@ export default function ErrorPage() {
console.error(error);
const dispatch = useDispatch();
const client = useContinueGUIProtocol(false);
const navigate = useNavigate();
return (
<div
@ -30,6 +31,8 @@ export default function ErrorPage() {
onClick={() => {
client?.stopSession();
dispatch(newSession());
localStorage.removeItem("persist:root");
navigate("/");
}}
></ContinueButton>
</div>

View file

@ -76,6 +76,7 @@ const TitleTextInput = styled(Input)`
margin-right: 8px;
padding-top: 6px;
padding-bottom: 6px;
background-color: transparent;
&:focus {
outline: none;
@ -120,7 +121,8 @@ const GUIHeaderDiv = styled.div`
position: sticky;
top: 0;
z-index: 100;
background-color: ${vscBackground};
background-color: transparent;
backdrop-filter: blur(12px);
`;
function fallbackRender({ error, resetErrorBoundary }) {
@ -398,7 +400,7 @@ function GUI(props: GUIProps) {
localStorage.setItem("mainTextEntryCounter", "1");
}
},
[client, sessionState.history, sessionState.context_items]
[client, sessionState.history, sessionState.context_items, defaultModel]
);
useEffect(() => {
@ -426,7 +428,7 @@ function GUI(props: GUIProps) {
// cmd+enter to /codebase
if (event && isMetaEquivalentKeyPressed(event)) {
input = `/edit ${input}`;
input = `/codebase ${input}`;
}
(mainTextInputRef.current as any).setInputValue("");
@ -591,7 +593,7 @@ function GUI(props: GUIProps) {
</GUIHeaderDiv>
{takenAction && showLoading && typeof client === "undefined" && (
<>
<RingLoader />
<RingLoader size={32} />
<p
style={{
textAlign: "center",

View file

@ -2,48 +2,6 @@ import { createSlice } from "@reduxjs/toolkit";
import { ContextItem } from "../../schema/ContextItem";
import { RootStore } from "../store";
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
},
{
description: "Now write it in Rust",
name: "User Input",
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
},
];
const TEST_SLASH_COMMANDS = [
{
name: "edit",
@ -59,31 +17,6 @@ const TEST_SLASH_COMMANDS = [
},
];
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: {
description: "test.py",
name: "test.py",
id: {
item_id: "test.py",
provider_title: "file",
},
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: {
description: "test.js",
name: "test.js",
id: {
item_id: "test.js",
provider_title: "file",
},
},
},
];
const initialState: RootStore["serverState"] = {
meilisearchUrl: undefined,
slashCommands: [],
@ -94,6 +27,7 @@ const initialState: RootStore["serverState"] = {
},
contextProviders: [],
savedContextGroups: [],
indexingProgress: 1.0,
};
export const serverStateSlice = createSlice({
@ -103,7 +37,10 @@ export const serverStateSlice = createSlice({
setSlashCommands: (state, action) => {
return {
...state,
slashCommands: action.payload,
slashCommands: [
...action.payload,
{ name: "codebase", description: "Retrieve codebase context" },
],
};
},
setContextProviders: (state, action) => {
@ -118,9 +55,19 @@ export const serverStateSlice = createSlice({
config: action.payload,
};
},
setIndexingProgress: (state, { payload }: { payload: number }) => {
return {
...state,
indexingProgress: payload,
};
},
},
});
export const { setContextProviders, setSlashCommands, setConfig } =
serverStateSlice.actions;
export const {
setContextProviders,
setSlashCommands,
setConfig,
setIndexingProgress,
} = serverStateSlice.actions;
export default serverStateSlice.reducer;

View file

@ -6,6 +6,73 @@ import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
import { v4 } from "uuid";
import { ContextItemId } from "../../schema/ContextItemId";
const TEST_TIMELINE = [
{
description: "Hi, please write bubble sort in python",
name: "User Input",
},
{
description: `\`\`\`python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
\`\`\``,
name: "Bubble Sort in Python",
},
{
description: "Now write it in Rust",
name: "User Input",
},
{
description: "Hello! This is a test...\n\n1, 2, 3, testing...",
name: "Testing",
},
{
description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
fn bubble_sort<T: Ord>(values: &mut[T]) {
let len = values.len();
for i in 0..len {
for j in 0..(len - i - 1) {
if values[j] > values[j + 1] {
values.swap(j, j + 1);
}
}
}
}
\`\`\`\nIs there anything else I can answer?`,
name: "Rust Bubble Sort",
},
];
const TEST_CONTEXT_ITEMS: ContextItem[] = [
{
content: "def add(a, b):\n return a + b",
description: {
description: "test.py",
name: "test.py",
id: {
item_id: "test.py",
provider_title: "file",
},
},
},
{
content: "function add(a, b) {\n return a + b\n}",
description: {
description: "test.js",
name: "test.js",
id: {
item_id: "test.js",
provider_title: "file",
},
},
},
];
export interface SessionFullState {
history: StepDescription[];
contextItemsAtIndex: { [index: number]: ContextItem[] };

View file

@ -45,6 +45,7 @@ export interface RootStore {
config: ContinueConfig;
contextProviders: ContextProviderDescription[];
savedContextGroups: any[]; // TODO: Context groups
indexingProgress: number;
};
}

View file

@ -461,7 +461,7 @@ export const MODEL_INFO: { [key: string]: ModelInfo } = {
icon: "ollama.png",
tags: [ModelProviderTag["Local"], ModelProviderTag["Open-Source"]],
packages: osModels,
collectInputFor: [...completionParamsInputs],
collectInputFor: [...completionParamsInputs, serverUrlInput],
},
together: {
title: "TogetherAI",
@ -745,7 +745,10 @@ After it's up and running, you can start using Continue.`,
'New users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `api_key=""` or select another model provider.',
icon: "openai.png",
tags: [ModelProviderTag.Free],
packages: [gpt4, gpt35turbo],
packages: [
{ ...gpt4, title: "GPT-4 (trial)" },
{ ...gpt35turbo, title: "GPT-3.5-Turbo (trial)" },
],
collectInputFor: [...completionParamsInputs],
},
};

View file

@ -1,11 +1,28 @@
import asyncio
import os
from typing import Optional
from tqdm import tqdm
from .core.config import ContinueConfig
from .headless.headless_ide import LocalIdeProtocol
from .libs.index.build_index import build_index
from .libs.util.ext_to_lang import ext_to_lang
from .libs.index.chunkers.chunk import Chunk
from dotenv import load_dotenv
from rich.console import Console
from rich.markdown import Markdown
import typer
from . import run
from .server.main import run_server
from .headless import get_headless_autopilot
from .libs.index.pipelines.main import main_retrieval_pipeline
app = typer.Typer()
load_dotenv()
app = typer.Typer(invoke_without_command=True)
console = Console()
CONTINUE_ASCII = r"""
@ -19,13 +36,15 @@ _ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
"""
@app.command()
def main(
def main_command(
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
@ -35,7 +54,119 @@ def main(
run(config)
else:
print(CONTINUE_ASCII)
run_server(port=port, host=host, meilisearch_url=meilisearch_url)
run_server(
port=port,
host=host,
meilisearch_url=meilisearch_url,
disable_meilisearch=disable_meilisearch,
)
@app.callback()
def main(
ctx: typer.Context,
port: int = typer.Option(65432, help="server port"),
host: str = typer.Option("127.0.0.1", help="server host"),
meilisearch_url: Optional[str] = typer.Option(
None, help="The URL of the MeiliSearch server if running manually"
),
disable_meilisearch: bool = typer.Option(
False, help="Disable the MeiliSearch server"
),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
headless: bool = typer.Option(False, help="Run in headless mode"),
):
if ctx.invoked_subcommand is None:
main_command(
port=port,
host=host,
meilisearch_url=meilisearch_url,
config=config,
headless=headless,
disable_meilisearch=disable_meilisearch,
)
def print_chunk(chunk: Chunk):
# A nice colored representation of the piece of the file
language = ext_to_lang(chunk.document_id.split(".")[-1])
console.print(
Markdown(
f"\n**{chunk.document_id}**\n\n```{language}\n{chunk.content}\n```\n---\n"
)
)
@app.command()
def search(
query: str = typer.Argument(..., help="The query to search for"),
config: Optional[str] = typer.Option(
None, "--config", help="The path to the configuration file"
),
directory: str = typer.Option(None, "--directory", help="The directory to index"),
):
if directory is None:
directory = "."
print(f"Searching {directory}...")
# Make absolute
directory = os.path.abspath(directory)
async def run():
autopilot = await get_headless_autopilot(config=config, directory=directory)
results = await main_retrieval_pipeline(
query,
autopilot.sdk,
openai_api_key=None, # os.environ.get("OPENAI_API_KEY"),
)
console.print(Markdown(f"## Results for `{query}`"))
for result in results:
print_chunk(result)
asyncio.run(run())
@app.command()
def index(
directory: str = typer.Argument(None, help="The directory to index"),
config: Optional[str] = typer.Option(
None, help="The path to the configuration file"
),
openai_api_key: Optional[str] = typer.Option(
None, help="The OpenAI API key to use for indexing"
),
):
if directory is None:
directory = "."
# Make absolute
directory = os.path.abspath(directory)
print(f"Indexing {directory}...")
async def run():
nonlocal config
if config is None:
config = ContinueConfig.load_default()
else:
config = ContinueConfig.from_filepath(config)
config.retrieval_settings.openai_api_key = openai_api_key
pbar = tqdm(total=100)
async for progress in build_index(
ide=LocalIdeProtocol(workspace_directory=directory), config=config
):
pbar.update(int(progress * 100) - pbar.n)
pbar.close()
print("Indexing complete")
asyncio.run(run())
if __name__ == "__main__":

View file

@ -50,6 +50,32 @@ class CustomCommand(BaseModel):
)
class RetrievalSettings(BaseModel):
n_retrieve: Optional[int] = Field(
50, description="Number of results to initially retrieve from vector database"
)
n_final: Optional[int] = Field(
10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
rerank_group_size: int = Field(
5,
description="Number of results to group together when re-ranking. Each group will be processed in parallel.",
)
ignore_files: List[str] = Field(
[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
openai_api_key: Optional[str] = Field(None, description="OpenAI API key")
api_base: Optional[str] = Field(None, description="OpenAI API base URL")
api_type: Optional[str] = Field(None, description="OpenAI API type")
api_version: Optional[str] = Field(None, description="OpenAI API version")
organization_id: Optional[str] = Field(None, description="OpenAI organization ID")
class ContinueConfig(BaseModel):
"""
Continue can be deeply customized by editing the `ContinueConfig` object in `~/.continue/config.py` (`%userprofile%\.continue\config.py` for Windows) on your machine. This class is instantiated from the config file for every new session.
@ -118,6 +144,10 @@ class ContinueConfig(BaseModel):
False,
description="If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.",
)
retrieval_settings: Optional[RetrievalSettings] = Field(
RetrievalSettings(),
description="Settings for the retrieval system. Read more about the retrieval system in the documentation.",
)
@classmethod
def schema(cls, *args, **kwargs):

View file

@ -1,7 +1,7 @@
import asyncio
import time
from abc import abstractmethod
from typing import Any, Awaitable, Callable, Dict, List, Optional
from typing import Any, Awaitable, Callable, List, Optional
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
@ -398,8 +398,8 @@ class ContextManager:
except Exception as e:
logger.debug(f"Error loading meilisearch index: {e}")
if should_retry:
await restart_meilisearch()
try:
await restart_meilisearch()
await asyncio.wait_for(poll_meilisearch_running(), timeout=20)
except asyncio.TimeoutError:
logger.warning(

View file

@ -200,6 +200,7 @@ class ContinueSDK:
)
async def add_context_item(self, item: ContextItem):
self.__autopilot.session_state.context_items.append(item)
await self.gui.add_context_item(item)
def set_loading_message(self, message: str):

View file

@ -0,0 +1,634 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/natesesti/Desktop/continue/server/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n",
"[2023-10-24 23:31:12,190] [DEBUG] New session: None\n",
"[2023-10-24 23:31:12,195] [DEBUG] Loaded Continue config file from /Users/natesesti/.continue/config.py\n",
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x127737d10>\n",
"[2023-10-24 23:31:12,266] [DEBUG] Starting context manager\n"
]
}
],
"source": [
"import json\n",
"import os\n",
"from typing import List\n",
"import asyncio\n",
"\n",
"from continuedev.core.sdk import ContinueSDK\n",
"from continuedev.libs.index.chunkers import Chunk\n",
"from continuedev.headless import start_headless_session\n",
"from continuedev.libs.index.pipelines.main import main_retrieval_pipeline, retrieval_step\n",
"from continuedev.libs.index.hyde import code_hyde\n",
"from continuedev.libs.index.rerankers.single_token import single_token_reranker_parallel\n",
"\n",
"session = await start_headless_session(directory=\"/Users/natesesti/Desktop/continue/server/continuedev\")\n",
"sdk: ContinueSDK = session.autopilot.continue_sdk"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"async def f(q: str):\n",
" return await main_retrieval_pipeline(q, sdk)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'basePath': '/Users/natesesti/Desktop/continue/server/continuedev', 'questions': [{'q': 'How does the Continue FastAPI server work?', 'files': ['server/main.py', 'server/gui.py', 'server/ide.py']}, {'q': 'Where is logic for pruning the prompt tokens?', 'files': ['libs/util/count_tokens.py', 'libs/llm/base.py']}, {'q': 'Where does codebase indexing happen?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/chroma_index.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py']}, {'q': 'How is meilisearch used?', 'files': ['plugins/steps/chroma.py', 'libs/index/indices/meilisearch_index.py', 'libs/index/indices/base.py', 'core/context.py', 'server/meilisearch_server.py']}, {'q': 'I want to update Ollama integration', 'files': ['libs/llm/ollama.py']}, {'q': 'How does Continue chunk code?', 'files': ['libs/index/chunkers/basic.py', 'libs/index/chunkers/chunk_directory.py', 'libs/index/chunkers/chunk.py', 'libs/index/chunkers/code.py']}]}\n"
]
}
],
"source": [
"with open(\"y.json\", \"r\") as file:\n",
" data = json.load(file)\n",
"\n",
"print(data)\n",
"questions = data[\"questions\"]\n",
"base_path = data[\"basePath\"]\n",
"\n",
"def abs_paths(question):\n",
" return list(map(\n",
" lambda x: os.path.join(base_path, x),\n",
" question[\"files\"]\n",
" ))\n",
"\n",
"def in_y(chunk: Chunk, question):\n",
" return chunk.document_id in abs_paths(question)\n",
"\n",
"def f1_score(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fp = len(chosen_files) - tp\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return 2 * tp / (2 * tp + fp + fn)\n",
"\n",
"def get_recall(chunks: List[Chunk], question) -> float:\n",
" chosen_files = list(set(map(lambda c: c.document_id, chunks)))\n",
" actual_files = abs_paths(question)\n",
" tp = len(list(filter(lambda x: x in actual_files, chosen_files)))\n",
" fn = len(actual_files) - tp\n",
" if tp == 0:\n",
" return 0\n",
"\n",
" return tp / (tp + fn)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# scores = []\n",
"# for question in questions:\n",
"# chunks = await f(question[\"q\"])\n",
"# score = f1_score(chunks, question)\n",
"# print(score)\n",
"# scores.append(score)\n",
"\n",
"# print(scores)\n",
"# print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[2023-10-24 23:31:12,418] [DEBUG] Loading Meilisearch index...\n",
"[2023-10-24 23:31:12,639] [DEBUG] Loaded 0 documents into meilisearch in 0.018690824508666992 seconds for context provider code\n",
"[2023-10-24 23:31:12,645] [DEBUG] Loaded 1 documents into meilisearch in 0.02457594871520996 seconds for context provider search\n",
"[2023-10-24 23:31:12,661] [DEBUG] Loaded 1 documents into meilisearch in 0.040534019470214844 seconds for context provider terminal\n",
"[2023-10-24 23:31:12,662] [DEBUG] Loaded 1 documents into meilisearch in 0.041803836822509766 seconds for context provider url\n",
"[2023-10-24 23:31:12,663] [DEBUG] Loaded 1 documents into meilisearch in 0.042099952697753906 seconds for context provider diff\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded 152 documents into meilisearch in 0.04308819770812988 seconds for context provider file\n",
"[2023-10-24 23:31:12,664] [DEBUG] Loaded Meilisearch index\n"
]
}
],
"source": [
"hyde_mapping = {}\n",
"hydes = await asyncio.gather(*[code_hyde(question[\"q\"], \"python\", sdk) for question in questions])\n",
"for i, hyde in enumerate(hydes):\n",
" hyde_mapping[questions[i][\"q\"]] = hyde"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Unclosed client session\n",
"client_session: <aiohttp.client.ClientSession object at 0x147c077d0>\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"1.0\n",
"1.0\n",
"1.0\n",
"0.6\n",
"1.0\n",
"0.8\n",
"[1.0, 1.0, 0.6, 0.8, 1.0, 1.0]\n",
"0.9\n"
]
}
],
"source": [
"async def get_score(question):\n",
" chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" score = get_recall(chunks, question)\n",
" print(score)\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"Scanning 50 files...\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"25\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.7499999999999999\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory,\n",
" openai_api_key=self.openai_api_key,\n",
" api_base=self.api_base,\n",
" api_type=self.api_type,\n",
" api_version=self.api_version,\n",
" organization_id=self.organization_id,\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" indices_to_build = 0\n",
" chroma_exists = await chroma_index.exists()\n",
" meilisearch_exists = await meilisearch_index.exists()\n",
" if not chroma_exists:\n",
" indices_to_build += 1\n",
" if not meilisearch_exists:\n",
" indices_to_build += 1\n",
"\n",
" if indices_to_build == 0:\n",
" return\n",
"\n",
" self.hide = False\n",
"\n",
" chunks = await chunk_directory(sdk, MAX_CHUNK_SIZE)\n",
"\n",
" total_progress = 0\n",
" if not chroma_exists:\n",
" async for progress in chroma_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" total_progress += 50\n",
"\n",
" if not meilisearch_exists:\n",
" async for progress in meilisearch_index.build(\n",
" sdk, ignore_files=self.ignore_files, chunks=chunks\n",
" ):\n",
" self.description = f\"Generating codebase embeddings... {int(progress*100 / indices_to_build + total_progress)}%\"\n",
" print(self.description, flush=True)\n",
" await sdk.update_ui()\n",
"\n",
" await asyncio.sleep(1)\n",
" self.hide = True\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"10\n",
"0.6666666666666667\n",
"MISSED BY RERANK: \n",
"\n",
"\n",
"/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class CreateCodebaseIndexChroma(Step):\n",
" name: str = \"Create Codebase Index\"\n",
" hide: bool = True\n",
" description: str = \"Generating codebase embeddings... 1%\"\n",
" openai_api_key: Optional[str] = Field(None, description=\"OpenAI API key\")\n",
" api_base: Optional[str] = Field(None, description=\"OpenAI API base URL\")\n",
" api_type: Optional[str] = Field(None, description=\"OpenAI API type\")\n",
" api_version: Optional[str] = Field(None, description=\"OpenAI API version\")\n",
" organization_id: Optional[str] = Field(None, description=\"OpenAI organization ID\")\n",
"\n",
" ignore_files: List[str] = Field(\n",
" [],\n",
" description=\"Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.\",\n",
" )\n",
"\n",
" async def describe(self, models) -> Coroutine[str, None, None]:\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" ...\n",
"\n",
"\n",
"-----------------------------\n",
"\n",
"\n",
"10\n",
"1.0\n",
"MISSED BY RERANK: \n",
"\n",
"\n"
]
}
],
"source": [
"async def get_rerank_score(question):\n",
" initial_chunks = await retrieval_step(hyde_mapping[question[\"q\"]], sdk, n_retrieve=50)\n",
" initial_recall = get_recall(initial_chunks, question)\n",
" print(len(initial_chunks))\n",
" chunks = await single_token_reranker_parallel(initial_chunks, question[\"q\"], 10, sdk)\n",
" print(len(chunks))\n",
" score = get_recall(chunks, question) / initial_recall\n",
" print(score)\n",
"\n",
" missed_by_rerank = [chunk for chunk in initial_chunks if in_y(chunk, question) and chunk.document_id not in [c.document_id for c in chunks]]\n",
" print(\"MISSED BY RERANK: \\n\\n\")\n",
" for chunk in missed_by_rerank:\n",
" print(chunk.document_id)\n",
" print(chunk.content)\n",
" print(\"\\n\\n-----------------------------\\n\\n\")\n",
"\n",
" return score\n",
"\n",
"scores = await asyncio.gather(*map(get_rerank_score, questions))\n",
"\n",
"print(scores)\n",
"print(sum(scores) / len(scores))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"PROMPT = \"\"\"\n",
"You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: \"Yes\" or \"No\" indicating the retrieved snippet is relevant to the query.\n",
"\n",
"Query: Where is the FastAPI server?\n",
"Snippet:\n",
"```/Users/andrew/Desktop/server/main.py\n",
"from fastapi import FastAPI\n",
"app = FastAPI()\n",
"@app.get(\"/\")\n",
"def read_root():\n",
" return {\"Hello\": \"World\"}\n",
"```\n",
"Relevant: Yes\n",
"\n",
"Query: Where in the documentation does it talk about the UI?\n",
"Snippet:\n",
"```/Users/andrew/Projects/bubble_sort/src/lib.rs\n",
"fn bubble_sort<T: Ord>(arr: &mut [T]) {\n",
" for i in 0..arr.len() {\n",
" for j in 1..arr.len() - i {\n",
" if arr[j - 1] > arr[j] {\n",
" arr.swap(j - 1, j);\n",
" }\n",
" }\n",
" }\n",
"}\n",
"```\n",
"Relevant: No\n",
"\n",
"Query: Where does codebase indexing happen?\n",
"Snippet:\n",
"```/Users/natesesti/Desktop/continue/server/continuedev/plugins/steps/chroma.py\n",
"class AnswerQuestionChroma(Step):\n",
" ...\n",
"\n",
" async def run(self, sdk: ContinueSDK) -> Coroutine[Observation, None, None]:\n",
" chroma_index = ChromaCodebaseIndex(\n",
" sdk.ide.workspace_directory, openai_api_key=self.openai_api_key\n",
" )\n",
" meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)\n",
"\n",
" self.hide = False\n",
" self.description = f\"Scanning {self.n_retrieve} files...\"\n",
" await sdk.update_ui()\n",
"\n",
" # Get top chunks from index\n",
" to_retrieve_from_each = (\n",
" self.n_retrieve if self.use_reranking else self.n_final\n",
" ) // 2\n",
" chroma_chunks = await chroma_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" meilisearch_chunks = await meilisearch_index.query(\n",
" self.user_input, n=to_retrieve_from_each\n",
" )\n",
" chunk_ids = set()\n",
" chunks = []\n",
" for chunk in chroma_chunks + meilisearch_chunks:\n",
" if chunk.id not in chunk_ids:\n",
" chunk_ids.add(chunk.id)\n",
" chunks.append(chunk)\n",
"\n",
" # Rerank to select top results\n",
" self.description = f\"Selecting most important files...\"\n",
" await sdk.update_ui()\n",
"\n",
" if self.use_reranking:\n",
" chunks = await default_reranker_parallel(\n",
" chunks,\n",
" self.user_input,\n",
" self.n_final,\n",
" sdk,\n",
" group_size=self.rerank_group_size,\n",
" )\n",
"\n",
" # Add context items\n",
" context_items: List[ContextItem] = []\n",
" for chunk in chunks:\n",
" # Can we select the context item through the normal means so that the name is disambiguated?\n",
" # Also so you don't have to understand the internals of the context provider\n",
" # OR have a chunk context provider??? Nice short-term, but I don't like it for long-term\n",
" ctx_item = ContextItem(\n",
" content=chunk.content,\n",
" description=ContextItemDescription(\n",
" name=f\"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})\",\n",
" description=chunk.document_id,\n",
" id=ContextItemId(\n",
" provider_title=\"file\",\n",
" item_id=remove_meilisearch_disallowed_chars(chunk.document_id),\n",
" ),\n",
" ),\n",
" ) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!\n",
"\n",
" context_items.append(ctx_item)\n",
" await sdk.add_context_item(ctx_item)\n",
"\n",
" self.hide = True\n",
" model = sdk.models.chat.model\n",
" # if model == \"gpt-4\":\n",
" # model = \"gpt-4-32k\" # Not publicly available yet?\n",
" if model == \"gpt-3.5-turbo\":\n",
" model = \"gpt-3.5-turbo-16k\"\n",
"\n",
" await sdk.run_step(\n",
" SimpleChatStep(\n",
" name=\"Answer Question\",\n",
" description=f\"Reading from {len(context_items)} files...\",\n",
" completion_options=CompletionOptions(model=model),\n",
" )\n",
" )\n",
"\n",
" # for ctx_item in context_items:\n",
" # await sdk.delete_context_item(ctx_item.description.id)\n",
"```\n",
"Relevant: \"\"\""
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<OpenAIObject at 0x11377c6b0> JSON: {\n",
" \"tokens\": [\n",
" \" No\"\n",
" ],\n",
" \"token_logprobs\": [\n",
" -0.0012104723\n",
" ],\n",
" \"top_logprobs\": [\n",
" {\n",
" \" No\": -0.0012104723,\n",
" \"\\n\": -6.8743377,\n",
" \"No\": -8.752341,\n",
" \"\\u00a0\": -11.196322,\n",
" \"<|endoftext|>\": -13.671831\n",
" }\n",
" ],\n",
" \"text_offset\": [\n",
" 4147\n",
" ]\n",
"}"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import openai\n",
"openai.api_key = \"\"\n",
"response = openai.Completion.create(\n",
" model=\"text-davinci-003\",\n",
" prompt=PROMPT,\n",
" max_tokens=1,\n",
" temperature=0.0,\n",
" stop=[\"```\"],\n",
" logit_bias={3363: 1, 1400: 1},\n",
" logprobs=10,\n",
")\n",
"response[\"choices\"][0][\"logprobs\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View file

@ -0,0 +1,46 @@
{
"basePath": "/Users/natesesti/Desktop/continue/server/continuedev",
"questions": [
{
"q": "How does the Continue FastAPI server work?",
"files": ["server/main.py", "server/gui.py", "server/ide.py"]
},
{
"q": "Where is logic for pruning the prompt tokens?",
"files": ["libs/util/count_tokens.py", "libs/llm/base.py"]
},
{
"q": "Where does codebase indexing happen?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/chroma_index.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py"
]
},
{
"q": "How is meilisearch used?",
"files": [
"plugins/steps/chroma.py",
"libs/index/indices/meilisearch_index.py",
"libs/index/indices/base.py",
"core/context.py",
"server/meilisearch_server.py"
]
},
{
"q": "I want to update Ollama integration",
"files": ["libs/llm/ollama.py"]
},
{
"q": "How does Continue chunk code?",
"files": [
"libs/index/chunkers/basic.py",
"libs/index/chunkers/chunk_directory.py",
"libs/index/chunkers/chunk.py",
"libs/index/chunkers/code.py"
]
}
]
}

View file

@ -1,21 +1,35 @@
from typing import Optional, Union
from typing import List, Optional, Union
import typer
from ..server.protocols.cli_gui import CommandLineGUI
from ..core.context import ContextManager, ContextProvider
from ..core.main import SessionState
from ..core.autopilot import Autopilot
from .headless_ide import LocalIdeProtocol
from ..core.config import ContinueConfig
# from ..server.session_manager import Session, session_manager
# from .headless_ide import LocalIdeProtocol
# app = typer.Typer()
async def get_headless_autopilot(
directory: Optional[str] = ".",
state: Optional[SessionState] = None,
config: Optional[Union[str, ContinueConfig]] = None,
context_providers: List[ContextProvider] = [],
) -> Autopilot:
if config is not None:
if isinstance(config, str):
config: ContinueConfig = ContinueConfig.from_filepath(config)
else:
config = ContinueConfig.load_default()
ide = LocalIdeProtocol(workspace_directory=directory)
context_manager = ContextManager()
# await context_manager.start(context_providers=context_providers, ide=ide)
await config.models.start("HEADLESS", config.system_message, config.temperature)
# async def start_headless_session(
# config: Optional[Union[str, ContinueConfig]] = None
# ) -> Session:
# if config is not None:
# if isinstance(config, str):
# config: ContinueConfig = ContinueConfig.from_filepath(config)
# ide = LocalIdeProtocol()
# return await session_manager.new_session(ide, config=config)
return Autopilot(
session_state=state,
ide=ide,
gui=CommandLineGUI(),
config=config,
context_manager=context_manager,
)

View file

@ -13,7 +13,7 @@ from ..models.filesystem import (
RealFileSystem,
)
from ..models.filesystem_edit import EditDiff, FileEdit, FileSystemEdit
from ..server.ide_protocol import AbstractIdeProtocolServer
from ..server.protocols.ide_protocol import AbstractIdeProtocolServer
load_dotenv()
@ -32,6 +32,10 @@ class LocalIdeProtocol(AbstractIdeProtocolServer):
filesystem: FileSystem = RealFileSystem()
def __init__(self, workspace_directory: str = None):
if workspace_directory:
self.workspace_directory = workspace_directory
async def handle_json(self, data: Any):
"""Handle a json message"""
pass
@ -90,7 +94,10 @@ class LocalIdeProtocol(AbstractIdeProtocolServer):
async def readFile(self, filepath: str) -> str:
"""Read a file"""
return self.filesystem.read(filepath)
try:
return self.filesystem.read(filepath)
except UnicodeDecodeError:
return ""
async def readRangeInFile(self, range_in_file: RangeInFile) -> str:
"""Read a range in a file"""

View file

@ -0,0 +1,51 @@
from typing import AsyncGenerator
from ...core.config import ContinueConfig
from ...server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...libs.index.chunkers.chunk_directory import chunk_directory
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...libs.index.indices.chroma_index import MAX_CHUNK_SIZE, ChromaCodebaseIndex
async def build_index(
ide: AbstractIdeProtocolServer, config: ContinueConfig
) -> AsyncGenerator[float, None]:
settings = config.retrieval_settings
chroma_index = ChromaCodebaseIndex(
ide.workspace_directory,
openai_api_key=settings.openai_api_key,
api_base=settings.api_base,
api_type=settings.api_type,
api_version=settings.api_version,
organization_id=settings.organization_id,
)
meilisearch_index = MeilisearchCodebaseIndex(ide.workspace_directory)
indices_to_build = 0
chroma_exists = await chroma_index.exists()
# meilisearch_exists = await meilisearch_index.exists()
meilisearch_exists = chroma_exists
if not chroma_exists:
indices_to_build += 1
if not meilisearch_exists:
indices_to_build += 1
if indices_to_build == 0:
yield 1
return
chunks = await chunk_directory(ide, MAX_CHUNK_SIZE)
total_progress = 0
if not chroma_exists:
async for progress in chroma_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build
total_progress += 50
if not meilisearch_exists:
async for progress in meilisearch_index.build(
ide, ignore_files=settings.ignore_files, chunks=chunks
):
yield progress / indices_to_build + total_progress / 100

View file

@ -0,0 +1,136 @@
import asyncio
import os
from typing import Dict, List
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
from .chunk import Chunk
from . import chunk_document
FILE_IGNORE_PATTERNS = [
# File Names
"**/.DS_Store",
"**/package-lock.json",
"**/yarn.lock",
# File Types
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
]
MAX_SIZE_IN_CHARS = 50_000
async def get_file_contents(filepath: str, ide: AbstractIdeProtocolServer) -> str:
try:
return (await ide.readFile(filepath))[:MAX_SIZE_IN_CHARS]
except Exception as _:
return None
async def get_contents_of_files(
files: List[str], ide: AbstractIdeProtocolServer, ignore_files: List[str] = []
) -> List[str]:
# Get file contents for all at once
return await asyncio.gather(*[ide.readFile(file) for file in files])
def gi_basename(path: str) -> str:
return path[: path.index(".gitignore")]
async def get_all_file_contents(
ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100
) -> Dict[str, str]:
# Get list of filenames to index
files = await ide.listDirectoryContents(ide.workspace_directory, True)
# Get all .gitignores first
gitignore_paths = list(
filter(
lambda file: file.endswith(".gitignore")
or file.endswith(".continueignore"),
files,
)
)
gitignore_contents = await get_contents_of_files(gitignore_paths, ide)
gitignores = {
path: content for path, content in zip(gitignore_paths, gitignore_contents)
}
def gitignore_patterns_for_file(filepath: str) -> List[str]:
paths = list(
filter(
lambda gitignore_path: filepath.startswith(gi_basename(gitignore_path)),
gitignore_paths,
)
)
patterns = []
for path in paths:
base = gi_basename(path)
for pattern in gitignores[path].split("\n"):
if pattern.strip() != "":
patterns.append(os.path.join(base, pattern.strip()))
return patterns
# Filter from ignore_directories
files = list(
filter(
lambda file: not should_filter_path(
file,
ignore_files
+ DEFAULT_IGNORE_PATTERNS
+ FILE_IGNORE_PATTERNS
+ gitignore_patterns_for_file(file),
),
files,
)
)
items = []
i = 0
# Don't want to flood with too many requests
while i < len(files):
items += await get_contents_of_files(files[i : i + group_size], ide)
i += group_size
await asyncio.sleep(0.1)
return dict(filter(lambda tup: tup[1] is not None, zip(files, items)))
async def chunk_directory(
ide: AbstractIdeProtocolServer, max_chunk_size: int
) -> List[Chunk]:
file_contents = await get_all_file_contents(ide)
chunks = []
for filepath, contents in file_contents.items():
chunks += chunk_document(filepath, contents, max_chunk_size)
return chunks

View file

@ -0,0 +1,50 @@
# Hypothetical Document Embeddings (HyDE) - Prompts
from ..llm.base import LLM
CODE_PROMPT = """\
Generate a hypothetical snippet of code that would be relevant in answering the user's question.
It can be either a function, a class, or more than one of these. It should be roughly 10-20 lines of code and must be valid {language} code.
User question: {user_input}
Write your code in the block below:
```{language}
"""
async def code_hyde(user_input, language: str, model: LLM):
prompt = CODE_PROMPT.format(user_input=user_input, language=language)
completion = await model.complete(
prompt, log=False, max_tokens=100, temperature=0.0, stop=["```"]
)
return completion
KEYWORDS_PROMPT = """\
For each user question, generate keywords or file names that would be useful to search for in the codebase. Don't repeat or include similar keywords more than once. Try to include specific keywords or snippets of code that might exist in a codebase, not just general terms. Separate the keywords with a comma.
User question: Where should I add unit tests for this Python project?
Keywords: import pytest, test, import unittest, pytest-cov, coverage, coverage.py, assert, fixture, pytest.mark.parametrize
User: How to add a new command to this VS Code extension?
Keywords: vscode, command, package.json, vscode.commands.registerCommand
User: How to add a new endpoint to this Spring Boot application?
Keywords: spring, boot, endpoint, controller, request mapping, mapping, requestbody, requestparam, pathvariable, req
User question: {user_input}
Keywords:
"""
async def generate_keywords(user_input, model: LLM):
completion = await model.complete(
KEYWORDS_PROMPT.format(user_input=user_input),
log=False,
max_tokens=80,
temperature=0.0,
stop=["\n"],
)
return completion.strip().replace("'", "").replace('"', "").split(", ")

View file

@ -0,0 +1,39 @@
from abc import ABC, abstractmethod
from typing import AsyncGenerator, List, Optional
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from ....core.sdk import ContinueSDK
from ..chunkers import Chunk
class CodebaseIndex(ABC):
directory: str
def __init__(self, directory: str):
self.directory = directory
@abstractmethod
async def exists(self) -> bool:
"""Returns whether the index exists (has been built)"""
raise NotImplementedError()
@abstractmethod
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1. Optionally takes a list of chunks, otherwise builds its own"""
raise NotImplementedError()
@abstractmethod
async def update(self) -> AsyncGenerator[float, None]:
"""Updates the index, yielding progress as a float between 0 and 1"""
raise NotImplementedError()
@abstractmethod
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
raise NotImplementedError()

View file

@ -8,54 +8,19 @@ from typing import AsyncGenerator, Dict, List, Literal, Optional
import chromadb
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from .base import CodebaseIndex
from dotenv import load_dotenv
from openai.error import RateLimitError
from pydantic import BaseModel
from .chunkers.chunk import Chunk
from ...libs.index.git import GitProject
from ...core.sdk import ContinueSDK
from ..util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path
from ..util.logging import logger
from ..util.paths import getEmbeddingsPathForBranch
from .chunkers import chunk_document
from ..chunkers.chunk import Chunk
from ..git import GitProject
from ...util.logging import logger
from ...util.paths import getEmbeddingsPathForBranch
load_dotenv()
IGNORE_PATTERNS_FOR_CHROMA = [
# File Names
"**/.DS_Store",
"**/package-lock.json",
"**/yarn.lock",
# File Types
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
]
# Mapping of workspace_dir to chromadb collection
collections = {}
@ -70,7 +35,7 @@ class CodebaseIndexMetadata(BaseModel):
chunks: Dict[str, int]
class ChromaCodebaseIndex:
class ChromaCodebaseIndex(CodebaseIndex):
directory: str
client: chromadb.Client
openai_api_key: str = None
@ -130,7 +95,7 @@ class ChromaCodebaseIndex:
def metadata_path(self) -> str:
return os.path.join(self.index_dir, "metadata.json")
def exists(self):
async def exists(self):
"""Check whether the codebase index has already been built and saved on disk"""
return os.path.exists(self.metadata_path)
@ -185,57 +150,32 @@ class ChromaCodebaseIndex:
return collection
async def build(
self, sdk: ContinueSDK, ignore_files: List[str] = []
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Create a new index for the current branch."""
if self.exists():
if await self.exists():
return
# Get list of filenames to index
files = await sdk.ide.listDirectoryContents(sdk.ide.workspace_directory, True)
if chunks is None:
raise Exception("Chunks must be passed in to build Chroma index")
# Filter from ignore_directories
files = list(
# Construct list of chunks for each file
chunks = list(
filter(
lambda file: not should_filter_path(
file,
ignore_files + DEFAULT_IGNORE_PATTERNS + IGNORE_PATTERNS_FOR_CHROMA,
),
files,
lambda c: len(c.content.strip()) > 0,
chunks,
)
)
# Get file contents for all at once
tasks = []
async def readFile(filepath: str) -> Optional[str]:
to = 0.1
while True:
try:
return await sdk.ide.readFile(filepath)
except Exception as e:
if to > 4:
return None
await asyncio.sleep(to)
to *= 2
for file in files:
tasks.append(readFile(file))
file_contents = await asyncio.gather(*tasks)
# Construct list of chunks for each file
chunks: List[Chunk] = []
num_chunks_per_file = {}
for i in range(len(files)):
document_chunks = [
c
for c in chunk_document(files[i], file_contents[i], MAX_CHUNK_SIZE)
if len(c.content.strip()) > 0
]
num_chunks_per_file[files[i]] = len(document_chunks)
chunks.extend(document_chunks)
for chunk in chunks:
num_chunks_per_file[chunk.document_id] = (
num_chunks_per_file.get(chunk.document_id, 0) + 1
)
# Flatten chunks, metadata, and ids for insertion to Chroma
documents = []
@ -285,12 +225,10 @@ class ChromaCodebaseIndex:
indent=4,
)
logger.debug("Codebase index created")
async def update(self):
"""Update the index with a list of files."""
if not self.exists():
if not await self.exists():
self.build()
else:
metadata = self.get_metadata()
@ -334,9 +272,9 @@ class ChromaCodebaseIndex:
logger.debug("Codebase index updated")
def query(self, query: str, n: int = 4) -> List[Chunk]:
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Query the codebase index for top n results"""
if not self.exists():
if not await self.exists():
logger.warning(f"No index found for the codebase at {self.index_dir}")
return []

View file

@ -0,0 +1,151 @@
import asyncio
from functools import cached_property
from ....server.protocols.ide_protocol import AbstractIdeProtocolServer
from meilisearch_python_async import Client
from meilisearch_python_async.errors import MeilisearchApiError
from ....server.meilisearch_server import get_meilisearch_url
from .base import CodebaseIndex
from ..chunkers import Chunk
from typing import Any, AsyncGenerator, Dict, List, Optional
from ....server.meilisearch_server import remove_meilisearch_disallowed_chars
from ...util.logging import logger
class MeilisearchCodebaseIndex(CodebaseIndex):
directory: str
def __init__(self, directory: str):
self.directory = directory
@cached_property
def index_name(self) -> str:
return remove_meilisearch_disallowed_chars(self.directory)
async def exists(self) -> bool:
"""Returns whether the index exists (has been built)"""
async with Client(get_meilisearch_url()) as search_client:
try:
index = await search_client.get_index(self.index_name)
return index is not None
except MeilisearchApiError as e:
return False
except Exception as e:
logger.warning(f"Error while checking if meilisearch index exists: {e}")
return False
def chunk_to_meilisearch_document(self, chunk: Chunk, index: int) -> Dict[str, Any]:
return {
"id": str(index),
"content": chunk.content,
"document_id": chunk.document_id,
**chunk.other_metadata,
"metadata": {
"start_line": chunk.start_line,
"end_line": chunk.end_line,
"index": chunk.index,
},
}
def meilisearch_document_to_chunk(self, document: Dict[str, Any]) -> Chunk:
other_metadata = document.copy()
del other_metadata["content"]
del other_metadata["metadata"]
del other_metadata["document_id"]
del other_metadata["id"]
return Chunk(
content=document["content"],
start_line=document["metadata"]["start_line"],
end_line=document["metadata"]["end_line"],
index=document["metadata"]["index"],
document_id=document["document_id"],
other_metadata=other_metadata,
)
async def build(
self,
ide: AbstractIdeProtocolServer,
ignore_files: List[str] = [],
chunks: Optional[List[Chunk]] = None,
) -> AsyncGenerator[float, None]:
"""Builds the index, yielding progress as a float between 0 and 1"""
if chunks is None:
logger.warning("Meilisearch index requires chunks to be passed in")
yield 1
async with Client(get_meilisearch_url()) as search_client:
try:
await search_client.create_index(self.index_name)
index = await search_client.get_index(self.index_name)
# await index.update_ranking_rules(
# ["attribute", "words", "typo", "proximity", "sort", "exactness"]
# )
await index.update_searchable_attributes(["content", "document_id"])
i = 0
GROUP_SIZE = 100
while i < len(chunks):
await index.add_documents(
[
self.chunk_to_meilisearch_document(chunk, j)
for j, chunk in enumerate(chunks[i : i + GROUP_SIZE])
]
)
i += GROUP_SIZE
yield i / len(chunks)
await asyncio.sleep(0.1)
except Exception as e:
logger.warning(f"Error while building meilisearch index: {e}")
yield 1
async def update(self) -> AsyncGenerator[float, None]:
"""Updates the index, yielding progress as a float between 0 and 1"""
raise NotImplementedError()
async def _query(self, query: str, n: int = 4) -> List[Chunk]:
async with Client(get_meilisearch_url()) as search_client:
try:
results = await search_client.index(self.index_name).search(
query, limit=n
)
return [
self.meilisearch_document_to_chunk(result)
for result in results.hits
]
except Exception as e:
logger.warning(f"Error while retrieving document from meilisearch: {e}")
return []
async def query(self, query: str, n: int = 4) -> List[Chunk]:
"""Queries the index, returning the top n results"""
return await self._query(query, n=n)
async def query_keywords(self, keywords: List[str], n: int = 4) -> List[Chunk]:
count_per_chunk = {}
id_to_chunk = {}
for keyword in keywords:
chunks = await self._query(keyword, n=n)
for chunk in chunks:
if chunk.id not in count_per_chunk:
count_per_chunk[chunk.id] = 0
id_to_chunk[chunk.id] = chunk
count_per_chunk[chunk.id] += 1
# Sort by count
sorted_chunks = sorted(
count_per_chunk.items(), key=lambda item: item[1], reverse=True
)
# Get top n
chunks = []
for chunk_id, count in sorted_chunks[:n]:
chunks.append(id_to_chunk[chunk_id])
return chunks

View file

@ -0,0 +1,56 @@
from meilisearch_python_async import Client
async def add_docs():
async with Client("http://localhost:7700") as search_client:
index = await search_client.create_index("UsersnatesestiDesktopcontinueguisrc")
await index.delete_all_documents()
return
await index.add_documents(
[
{
"id": 0,
"content": 'import GUI from "./pages/gui";\nimport History from "./pages/history";\nimport Help from "./pages/help";\nimport Layout from "./components/Layout";\nimport { createContext, useEffect } from "react";\nimport useContinueGUIProtocol from "./hooks/useWebsocket";\nimport ContinueGUIClientProtocol from "./hooks/ContinueGUIClientProtocol";\nimport { useDispatch } from "react-redux";\nimport {\n setApiUrl,\n setVscMachineId,\n setSessionId,\n setVscMediaUrl,\n setDataSwitchOn,\n setWorkspacePaths,\n} from "./redux/slices/configSlice";\nimport {\n setHighlightedCode,\n setServerStatusMessage,\n} from "./redux/slices/miscSlice";\nimport { postVscMessage } from "./vscode";\nimport { RouterProvider, createMemoryRouter } from "react-router-dom";\nimport ErrorPage from "./pages/error";\nimport SettingsPage from "./pages/settings";\nimport Models from "./pages/models";\nimport HelpPage from "./pages/help";\nimport ModelConfig from "./pages/modelconfig";\nimport { usePostHog } from "posthog-js/react";\n\nconst router = createMemoryRouter([\n {\n path: "/",\n element: <Layout />,\n errorElement: <ErrorPage />,\n children: [\n {\n path: "/index.html",\n element: <GUI />,\n },\n {\n path: "/",\n element: <GUI />,\n },\n {\n path: "/history",\n element: <History />,\n },\n {\n path: "/help",\n element: <Help />,\n },\n {\n path: "/settings",\n element: <SettingsPage />,\n },\n {\n path: "/models",\n element: <Models />,\n },\n {\n path: "/help",\n element: <HelpPage />,\n },\n {\n path: "/modelconfig/:modelName",\n element: <ModelConfig />,\n },\n ],\n },\n]);\n\nexport const GUIClientContext = createContext<\n ContinueGUIClientProtocol | undefined\n>(undefined);\n\nfunction App() {\n const client = useContinueGUIProtocol(false);\n const posthog = usePostHog();\n\n const dispatch = useDispatch();\n useEffect(() => {\n const eventListener = (event: any) => {\n switch (event.data.type) {\n case "onLoad":\n dispatch(setApiUrl(event.data.apiUrl));\n dispatch(setVscMachineId(event.data.vscMachineId));\n dispatch(setSessionId(event.data.sessionId));\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
"metadata": {"start_pos": 0, "end_pos": 10, "index": 0},
},
{
"id": 1,
"content": ' dispatch(setVscMediaUrl(event.data.vscMediaUrl));\n dispatch(setDataSwitchOn(event.data.dataSwitchOn));\n if (event.data.uniqueId) {\n posthog?.identify(event.data.vscMachineId);\n }\n dispatch(setWorkspacePaths(event.data.workspacePaths));\n break;\n case "highlightedCode":\n dispatch(setHighlightedCode(event.data.rangeInFile));\n break;\n case "serverStatus":\n dispatch(setServerStatusMessage(event.data.message));\n break;\n }\n };\n window.addEventListener("message", eventListener);\n postVscMessage("onLoad", {});\n return () => window.removeEventListener("message", eventListener);\n }, []);\n\n useEffect(() => {\n if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {\n localStorage.setItem(\n "--vscode-editor-foreground",\n document.body.style.getPropertyValue("--vscode-editor-foreground")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-editor-background")) {\n localStorage.setItem(\n "--vscode-editor-background",\n document.body.style.getPropertyValue("--vscode-editor-background")\n );\n }\n if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {\n localStorage.setItem(\n "--vscode-list-hoverBackground",\n document.body.style.getPropertyValue("--vscode-list-hoverBackground")\n );\n }\n }, []);\n\n return (\n <GUIClientContext.Provider value={client}>\n <RouterProvider router={router} />\n </GUIClientContext.Provider>\n );\n}\n\nexport default App;\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/App.tsx",
# "metadata": {...},
},
{
"id": 2,
"content": '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n --secondary-dark: rgb(37, 37, 38);\n --vsc-background: rgb(30, 30, 30);\n --button-color: rgb(113, 28, 59);\n --button-color-hover: rgba(113, 28, 59, 0.667);\n --def-border-radius: 5px;\n\n --vscode-editor-background: rgb(30, 30, 30);\n --vscode-editor-foreground: rgb(197, 200, 198);\n --vscode-textBlockQuote-background: rgba(255, 255, 255, 1);\n}\n\nhtml,\nbody,\n#root {\n height: 100%;\n background-color: var(--vscode-editor-background);\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,\n Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;\n}\n\nbody {\n padding: 0;\n color: var(--vscode-editor-foreground);\n padding: 0px;\n margin: 0px;\n height: 100%;\n}\n\n.press-start-2p {\n font-family: "Press Start 2P", sans-serif;\n}\n\na:focus {\n outline: none;\n}\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/index.css",
# "metadata": {...},
},
{
"id": 3,
"content": 'import React from "react";\nimport ReactDOM from "react-dom/client";\nimport App from "./App";\nimport { Provider } from "react-redux";\nimport store from "./redux/store";\nimport "./index.css";\n\nimport CustomPostHogProvider from "./hooks/CustomPostHogProvider";\n\nReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(\n <React.StrictMode>\n <Provider store={store}>\n <CustomPostHogProvider>\n <App />\n </CustomPostHogProvider>\n </Provider>\n </React.StrictMode>\n);\n\n',
"document_id": "/Users/natesesti/Desktop/continue/gui/src/main.tsx",
# "metadata": {...},
},
]
)
async def query(query: str):
async with Client("http://localhost:7700") as search_client:
results = await search_client.index(
"UsersnatesestiDesktopcontinueguisrc"
).search(query, limit=4)
return results
async def main():
await add_docs()
results = await query("import")
print(results)
if __name__ == "__main__":
import asyncio
asyncio.run(main())

View file

@ -0,0 +1,72 @@
from typing import List, Optional
from ..hyde import code_hyde
from ..rerankers.default import default_reranker_parallel
from ..rerankers.single_token import single_token_reranker_parallel
from ..indices.meilisearch_index import MeilisearchCodebaseIndex
from ....core.sdk import ContinueSDK
from ..indices.chroma_index import ChromaCodebaseIndex
from ..chunkers.chunk import Chunk
async def retrieval_step(
query: str,
sdk: ContinueSDK,
n_retrieve: int = 50,
n_final: int = 10,
use_reranking: bool = True,
openai_api_key: Optional[str] = None,
) -> List[Chunk]:
chroma_index = ChromaCodebaseIndex(
sdk.ide.workspace_directory, openai_api_key=openai_api_key
)
meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)
print(f"Scanning {n_retrieve} files...")
# Get top chunks from index
to_retrieve_from_each = (n_retrieve if use_reranking else n_final) // 2
hyde = await code_hyde(query, "", sdk)
chroma_chunks = await chroma_index.query(hyde, n=to_retrieve_from_each)
meilisearch_chunks = await meilisearch_index.query(query, n=to_retrieve_from_each)
# De-duplicate
chunk_ids = set()
chunks = []
for chunk in chroma_chunks + meilisearch_chunks:
if chunk.id not in chunk_ids:
chunk_ids.add(chunk.id)
chunks.append(chunk)
return chunks
async def main_retrieval_pipeline(
query: str,
sdk: ContinueSDK,
openai_api_key: Optional[str] = None,
n_retrieve: int = 50,
use_reranking: bool = True,
n_final: int = 10,
rerank_group_size: int = 5,
) -> List[Chunk]:
chunks = await retrieval_step(
query,
sdk,
n_retrieve=n_retrieve,
use_reranking=use_reranking,
openai_api_key=openai_api_key,
n_final=n_final,
)
# Rerank to select top results
if use_reranking:
print(f"Selecting most important files...")
chunks = await single_token_reranker_parallel(
chunks,
query,
n_final,
sdk,
)
return chunks

View file

@ -2,13 +2,12 @@ import asyncio
import os
from typing import Dict, List
from ...llm.base import LLM
from ..chunkers.chunk import Chunk
from continuedev.core.sdk import ContinueSDK
async def decide_include_remove(
chunks: List[Chunk], user_input: str, n: int, sdk: ContinueSDK
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> Dict[str, str]:
"""
Reranks the results from the codebase index based on the user input.
@ -88,15 +87,15 @@ Now for the real task, here are the top {len(chunks)} results from the codebase
List the results that are not useful in answering the request, using in the same format from the example. Only choose those that are completely unrelated, and no more than {n // 2}:"""
include = sdk.models.summarize.complete(include_prompt, log=False)
remove = sdk.models.summarize.complete(remove_prompt, log=False)
include = model.complete(include_prompt, log=False)
remove = model.complete(remove_prompt, log=False)
include_completion, remove_completion = await asyncio.gather(include, remove)
return include_completion.split("\n"), remove_completion.split("\n")
async def default_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, sdk: ContinueSDK
chunks: List[Chunk], user_input: str, n: int, model: LLM, group_size: int = 10
) -> List[Chunk]:
"""
A reranker, given a mapping from id to contents, returns the subset of the mapping that is most relevant to the user_input
@ -106,7 +105,7 @@ async def default_reranker_parallel(
group = []
for chunk in chunks:
group.append(chunk)
if len(group) == 10:
if len(group) == group_size:
groups.append(group)
group = []
@ -119,7 +118,7 @@ async def default_reranker_parallel(
tasks = []
for group in groups:
tasks.append(decide_include_remove(group, user_input, n, sdk))
tasks.append(decide_include_remove(group, user_input, n, model))
reranking_results = await asyncio.gather(*tasks)
for rr in reranking_results:

View file

@ -0,0 +1,91 @@
import asyncio
from typing import List
from ...llm.base import LLM
import openai
from ..chunkers.chunk import Chunk
from ...util.logging import logger
PROMPT = """
You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
Query: Where is the FastAPI server?
Snippet:
```/Users/andrew/Desktop/server/main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {{"Hello": "World"}}
```
Relevant: Yes
Query: Where in the documentation does it talk about the UI?
Snippet:
```/Users/andrew/Projects/bubble_sort/src/lib.rs
fn bubble_sort<T: Ord>(arr: &mut [T]) {{
for i in 0..arr.len() {{
for j in 1..arr.len() - i {{
if arr[j - 1] > arr[j] {{
arr.swap(j - 1, j);
}}
}}
}}
}}
```
Relevant: No
Query: {query}
Snippet:
```{document_id}
{document}
```
Relevant:
"""
async def single_token_reranker(chunk: Chunk, user_input: str, model: LLM) -> float:
compiled_prompt = PROMPT.format(
query=user_input, document=chunk.content, document_id=chunk.document_id
)
if False:
# TODO: Continuous ranking with logits
# openai.api_key = openai_api_key
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=compiled_prompt,
max_tokens=1,
temperature=0.0,
stop=["```"],
logit_bias={3363: 1, 1400: 1},
logprobs=1,
)
return response["choices"][0]["logprobs"]["token_logprobs"][0]
else:
try:
completion = await model.complete(
compiled_prompt, log=False, max_tokens=1, temperature=0.0
)
except Exception:
return 0.5
answer = completion.strip().lower().replace('"', "").replace("'", "")
if answer == "yes":
return 1.0
elif answer == "no":
return 0.0
else:
logger.warning(f"Unexpected response from single token reranker: {answer}")
return 0.0
async def single_token_reranker_parallel(
chunks: List[Chunk], user_input: str, n: int, model: LLM
) -> List[Chunk]:
tasks = [single_token_reranker(chunk, user_input, model) for chunk in chunks]
results = await asyncio.gather(*tasks)
# Sort by results, return top n
sorted_chunks = sorted(zip(chunks, results), key=lambda x: x[1], reverse=True)
return [chunk for chunk, _ in sorted_chunks[:n]]

View file

@ -1,9 +1,12 @@
from typing import Callable, List, Literal, Optional
import asyncio
from typing import List, Literal, Optional
import certifi
from ..util.count_tokens import MAX_TOKENS_FOR_MODEL
from ..util.logging import logger
from .prompts.chat import template_alpaca_messages
import openai
from openai.error import RateLimitError
from pydantic import Field
from ...core.main import ChatMessage
@ -160,6 +163,14 @@ class OpenAI(LLM):
):
if not hasattr(chunk, "choices") or len(chunk.choices) == 0:
continue
if self.api_type == "azure":
# To smooth out the response streaming, which typically comes in bursts
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
yield chunk.choices[0].delta
else:
async for chunk in await openai.Completion.acreate(
@ -181,12 +192,21 @@ class OpenAI(LLM):
args["model"] not in NON_CHAT_MODELS
and not self.use_legacy_completions_endpoint
):
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
)
return resp.choices[0].message.content
wait_time = 0.2
while True:
try:
resp = await openai.ChatCompletion.acreate(
messages=[{"role": "user", "content": prompt}],
**args,
headers=self.headers,
)
return resp.choices[0].message.content
except RateLimitError as e:
logger.debug(f"Rate limit exceeded, waiting {wait_time} seconds")
await asyncio.sleep(wait_time)
wait_time *= 2
if wait_time > 2**10:
raise e
else:
return (
(

View file

@ -1,3 +1,4 @@
import asyncio
import json
import traceback
from typing import List
@ -71,6 +72,11 @@ class ProxyServer(LLM):
loaded_chunk = json.loads(chunk)
yield loaded_chunk
if self.model == "gpt-4":
await asyncio.sleep(0.03)
else:
await asyncio.sleep(0.01)
except Exception as e:
posthog_logger.capture_event(
"proxy_server_parse_error",

View file

@ -0,0 +1,29 @@
ext_dict = {
"py": "python",
"js": "javascript",
"ts": "typescript",
"java": "java",
"go": "go",
"rb": "ruby",
"rs": "rust",
"c": "c",
"cpp": "cpp",
"cs": "csharp",
"php": "php",
"scala": "scala",
"swift": "swift",
"kt": "kotlin",
"md": "markdown",
"json": "json",
"html": "html",
"css": "css",
"sh": "shell",
"yaml": "yaml",
"toml": "toml",
"tex": "latex",
"sql": "sql",
}
def ext_to_lang(ext: str) -> str:
return ext_dict.get(ext, "plaintext")

View file

@ -1,5 +1,6 @@
import fnmatch
# import fnmatch
from typing import List
import pathspec
DEFAULT_IGNORE_DIRS = [
".git",
@ -30,4 +31,8 @@ def should_filter_path(
path: str, ignore_patterns: List[str] = DEFAULT_IGNORE_PATTERNS
) -> bool:
"""Returns whether a file should be filtered"""
return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)
spec = pathspec.PathSpec.from_lines(
pathspec.patterns.GitWildMatchPattern, ignore_patterns
)
return spec.match_file(path)
# return any(fnmatch.fnmatch(path, pattern) for pattern in ignore_patterns)

View file

@ -55,14 +55,14 @@ def decode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("$f$", "/").replace("$b$", "\\")
return path.replace("_f_", "/").replace("_b_", "\\")
def encode_escaped_path(path: str) -> str:
"""We use a custom escaping scheme to record the full path of a file as a
corresponding basename, but withut URL encoding, because then the URI just gets
interpreted as a full path again."""
return path.replace("/", "$f$").replace("\\", "$b$")
return path.replace("/", "_f_").replace("\\", "_b_")
def getEmbeddingsPathForBranch(workspace_dir: str, branch_name: str):
@ -114,6 +114,7 @@ def migrateConfigFile(existing: str) -> Optional[str]:
.replace("medium=", "summarize=")
.replace("TextGenUI", "TextGenWebUI")
.replace("text_gen_interface", "text_gen_webui")
.replace(".steps.chroma", ".steps.codebase")
)
if migrated != existing:
return migrated

View file

@ -4,6 +4,7 @@ from typing import Dict, List, Tuple
from pydantic import BaseModel
from ..libs.util.filter_files import should_filter_path
from ..models.main import AbstractModel, Position, Range
from .filesystem_edit import (
AddDirectory,
@ -332,6 +333,7 @@ class RealFileSystem(FileSystem):
# Walk
paths = []
for root, dirs, files in os.walk(path):
dirs[:] = list(filter(lambda p: not should_filter_path(p), dirs))
for f in files:
paths.append(os.path.join(root, f))

View file

@ -4,7 +4,7 @@ from typing import List
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from ...libs.util.create_async_task import create_async_task
from .util import remove_meilisearch_disallowed_chars
from .util import remove_meilisearch_disallowed_chars, remove_prefix
class DynamicProvider(ContextProvider, ABC):
@ -40,7 +40,7 @@ class DynamicProvider(ContextProvider, ABC):
if not id.provider_title == self.title:
raise Exception("Invalid provider title for item")
query = query.lstrip(self.title + " ")
query = remove_prefix(text=query, prefix=self.title).strip()
results = await self.get_content(query)
ctx_item = self.BASE_CONTEXT_ITEM.copy()

View file

@ -6,7 +6,7 @@ from pydantic import BaseModel
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from ...libs.index.codebase_index import ChromaIndexManager
from ...libs.index.indices.chroma_index import ChromaIndexManager
class EmbeddingResult(BaseModel):

View file

@ -8,7 +8,7 @@ from ...core.context import ContextProvider
from ...core.main import ChatMessage, ContextItem, ContextItemDescription, ContextItemId
from ...libs.util.filter_files import DEFAULT_IGNORE_PATTERNS
from ...libs.util.logging import logger
from .util import remove_meilisearch_disallowed_chars
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
MAX_SIZE_IN_CHARS = 50_000

View file

@ -6,7 +6,7 @@ from pydantic import Field
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from .util import remove_meilisearch_disallowed_chars
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
class GoogleContextProvider(ContextProvider):

View file

@ -7,7 +7,7 @@ from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from ...libs.util.logging import logger
from ...libs.util.ripgrep import get_rg_path
from .util import remove_meilisearch_disallowed_chars
from .util import remove_meilisearch_disallowed_chars, remove_prefix
class SearchContextProvider(ContextProvider):
@ -15,7 +15,7 @@ class SearchContextProvider(ContextProvider):
title = "search"
display_title = "Search"
description = "Search workspace for matches of an exact string"
description = "Search workspace for exact matches"
dynamic = True
requires_query = True
@ -80,7 +80,7 @@ class SearchContextProvider(ContextProvider):
if not id.provider_title == self.title:
raise Exception("Invalid provider title for item")
query = query.lstrip("search ")
query = remove_prefix(text=query, prefix="search").strip()
results = await self._search(query)
ctx_item = self.BASE_CONTEXT_ITEM.copy()

View file

@ -6,7 +6,7 @@ from pydantic import Field
from ...core.context import ContextProvider
from ...core.main import ContextItem, ContextItemDescription, ContextItemId
from .util import remove_meilisearch_disallowed_chars
from .util import remove_meilisearch_disallowed_chars, remove_prefix
class URLContextProvider(ContextProvider):
@ -92,7 +92,7 @@ class URLContextProvider(ContextProvider):
raise Exception("Invalid provider title for item")
# Generate the dynamic item
url = query.lstrip("url ").strip()
url = remove_prefix(text=query, prefix="url").strip()
if url is None or url == "":
return None
content, title = self._get_url_text_contents_and_title(url)

View file

@ -3,3 +3,15 @@ import re
def remove_meilisearch_disallowed_chars(id: str) -> str:
return re.sub(r"[^0-9a-zA-Z_-]", "", id)
def remove_prefix(text: str, prefix: str) -> str:
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text: str, suffix: str) -> str:
if text.endswith(suffix):
return text[:-len(suffix)]
return text

View file

@ -3,7 +3,7 @@ from typing import Type, Union
from ..steps.clear_history import ClearHistoryStep
from ..steps.comment_code import CommentCodeStep
from ..steps.share_session import ShareSessionStep
from ..steps.chroma import AnswerQuestionChroma
from ..steps.codebase import AnswerQuestionChroma
from ...core.config import ContinueConfig
from ...core.main import Policy, SessionState, Step
from ..steps.chat import SimpleChatStep
@ -100,4 +100,7 @@ class DefaultPolicy(Policy):
if user_input.startswith("/edit"):
return EditHighlightedCodeStep(user_input=user_input[5:])
if user_input.startswith("/codebase "):
return AnswerQuestionChroma(user_input=user_input[len("/codebase ") :])
return self.default_step(**self.default_params)

View file

@ -1,6 +1,5 @@
# from .chroma import (
# AnswerQuestionChroma, # noqa: F401
# CreateCodebaseIndexChroma, # noqa: F401
# EditFileChroma, # noqa: F401
# )
from .clear_history import ClearHistoryStep # noqa: F401

View file

@ -23,15 +23,11 @@ class SimpleChatStep(Step):
manage_own_chat_context: bool = True
description: str = ""
messages: List[ChatMessage] = None
prompt: Optional[str] = None
completion_options: Optional[CompletionOptions] = None
async def run(self, sdk: ContinueSDK):
messages = self.messages or await sdk.get_chat_context()
kwargs = self.completion_options.dict() if self.completion_options else {}
generator = sdk.models.chat.stream_chat(messages, **kwargs)
posthog_logger.capture_event(
"model_use",
{
@ -47,6 +43,15 @@ class SimpleChatStep(Step):
},
)
messages = self.messages or await sdk.get_chat_context()
if self.prompt and messages:
messages[-1].content = self.prompt
kwargs = self.completion_options.dict() if self.completion_options else {}
generator = sdk.models.chat.stream_chat(messages, **kwargs)
yield SetStep(description="")
async for chunk in generator:
if "content" in chunk:
yield chunk["content"]

View file

@ -1,161 +0,0 @@
import os
from typing import Coroutine, List, Optional, Union
from ...libs.llm.base import CompletionOptions
from ...libs.index.rerankers.default import default_reranker_parallel
from pydantic import Field
from ...core.main import (
ContextItem,
ContextItemDescription,
ContextItemId,
DeltaStep,
SetStep,
Step,
)
from ...core.sdk import ContinueSDK
from ...core.steps import EditFileStep
from ...libs.index.codebase_index import ChromaCodebaseIndex
from ..context_providers.util import remove_meilisearch_disallowed_chars
from .chat import SimpleChatStep
class CreateCodebaseIndexChroma(Step):
name: str = "Create Codebase Index"
hide: bool = True
description: str = "Generating codebase embeddings... 1%"
openai_api_key: Optional[str] = Field(None, description="OpenAI API key")
api_base: Optional[str] = Field(None, description="OpenAI API base URL")
api_type: Optional[str] = Field(None, description="OpenAI API type")
api_version: Optional[str] = Field(None, description="OpenAI API version")
organization_id: Optional[str] = Field(None, description="OpenAI organization ID")
ignore_files: List[str] = Field(
[],
description="Files to ignore when indexing the codebase. You can use glob patterns, such as **/*.py. This is useful for directories that contain generated code, or other directories that are not relevant to the codebase.",
)
async def describe(self, models) -> Coroutine[str, None, None]:
return "Generated codebase embeddings."
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(
sdk.ide.workspace_directory,
openai_api_key=self.openai_api_key,
api_base=self.api_base,
api_type=self.api_type,
api_version=self.api_version,
organization_id=self.organization_id,
)
if index.exists():
return
yield SetStep(hide=False)
async for progress in index.build(sdk, ignore_files=self.ignore_files):
yield SetStep(
description=f"Generating codebase embeddings... {int(progress*100)}%",
)
class AnswerQuestionChroma(Step):
user_input: str
_answer: Union[str, None] = None
name: str = "Answer Question"
n_retrieve: Optional[int] = Field(
20, description="Number of results to initially retrieve from vector database"
)
n_final: Optional[int] = Field(
10, description="Final number of results to use after re-ranking"
)
use_reranking: bool = Field(
True,
description="Whether to use re-ranking, which will allow initial selection of n_retrieve results, then will use an LLM to select the top n_final results",
)
hide: bool = True
async def describe(self, llm) -> Coroutine[str, None, None]:
if self._answer is None:
return f"Answering the question: {self.user_input}"
else:
return self._answer
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
yield SetStep(hide=False, description="Scanning codebase...")
# Get top chunks from index
chunks = index.query(
self.user_input, n=self.n_retrieve if self.use_reranking else self.n_final
)
# Rerank to select top results
yield SetStep(description="Selecting most important files...")
if self.use_reranking:
chunks = await default_reranker_parallel(
chunks, self.user_input, self.n_final, sdk
)
# Add context items
context_items: List[ContextItem] = []
for chunk in chunks:
# Can we select the context item through the normal means so that the name is disambiguated?
# Also so you don't have to understand the internals of the context provider
# OR have a chunk context provider??? Nice short-term, but I don't like it for long-term
ctx_item = ContextItem(
content=chunk.content,
description=ContextItemDescription(
name=f"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})",
description=chunk.document_id,
id=ContextItemId(
provider_title="file",
item_id=remove_meilisearch_disallowed_chars(chunk.document_id),
),
),
) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!
context_items.append(ctx_item)
await sdk.add_context_item(ctx_item)
yield SetStep(hide=True)
model = sdk.models.chat.model
# if model == "gpt-4":
# model = "gpt-4-32k" # Not publicly available yet?
if model == "gpt-3.5-turbo":
model = "gpt-3.5-turbo-16k"
await sdk.run_step(
SimpleChatStep(
name="Answer Question",
description=f"Reading from {len(context_items)} files...",
completion_options=CompletionOptions(model=model),
)
)
# for ctx_item in context_items:
# await sdk.delete_context_item(ctx_item.description.id)
class EditFileChroma(Step):
user_input: str
hide: bool = True
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
results = index.query_codebase_index(self.user_input)
resource_name = list(results.source_nodes[0].node.relationships.values())[0]
filepath = resource_name[: resource_name.index("::")]
await sdk.run_step(
EditFileStep(
filepath=filepath,
prompt=f"Here is the code:\n\n{{code}}\n\nHere is the user request:\n\n{self.user_input}\n\nHere is the code after making the requested changes:\n",
)
)

View file

@ -0,0 +1,196 @@
import asyncio
import os
from typing import Coroutine, List, Optional, Union
from ...libs.index.hyde import code_hyde, generate_keywords
from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex
from ...libs.llm.base import LLM, CompletionOptions
from ...libs.index.rerankers.single_token import single_token_reranker_parallel
from ...core.main import (
ContextItem,
ContextItemDescription,
ContextItemId,
SetStep,
Step,
)
from ...core.sdk import ContinueSDK
from ...core.steps import EditFileStep
from ...libs.index.indices.chroma_index import ChromaCodebaseIndex
from ...server.meilisearch_server import remove_meilisearch_disallowed_chars
from .chat import SimpleChatStep
PROMPT = """Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more. Here is the question: '{user_input}'. Response: """
async def get_faster_model(sdk: ContinueSDK) -> Optional[LLM]:
# First, check for GPT-3/3.5
models = sdk.config.models.all_models
if gpt3_model := next(filter(lambda m: "gpt-3" in m.model, models), None):
return gpt3_model
# Then, check for OpenAIFreeTrial
if openai_free_trial_model := next(
filter(lambda m: m.__class__.__name__ == "OpenAIFreeTrial", models), None
):
new_model = openai_free_trial_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Then, check for an API Key
if openai_model := next(
filter(
lambda m: hasattr(m, "api_key")
and m.api_key is not None
and m.api_key.startswith("sk-"),
models,
),
None,
):
new_model = openai_model.copy()
new_model.model = "gpt-3.5-turbo"
await new_model.start(sdk.ide.window_info.unique_id)
return new_model
# Return None, so re-ranking probably shouldn't happen
return None
class AnswerQuestionChroma(Step):
user_input: str
_answer: Union[str, None] = None
name: str = "Answer Question"
hide: bool = True
async def describe(self, llm) -> Coroutine[str, None, None]:
if self._answer is None:
return f"Answering the question: {self.user_input}"
else:
return self._answer
async def run(self, sdk: ContinueSDK):
settings = sdk.config.retrieval_settings
faster_model = await get_faster_model(sdk)
use_reranking = settings.use_reranking and faster_model is not None
chroma_index = ChromaCodebaseIndex(
sdk.ide.workspace_directory, openai_api_key=settings.openai_api_key
)
meilisearch_index = MeilisearchCodebaseIndex(sdk.ide.workspace_directory)
yield SetStep(hide=False, description="Scanning codebase...")
# Get top chunks from index
to_retrieve_from_each = (
settings.n_retrieve if use_reranking else settings.n_final
) // 2
# Use HyDE only if a faster model is available
query = self.user_input
keywords = None
if faster_model is not None:
resps = await asyncio.gather(
*[
code_hyde(self.user_input, "", faster_model),
generate_keywords(self.user_input, faster_model),
]
)
query = resps[0]
keywords = resps[1]
# Get meilisearch chunks first, fill in the rest with chroma
if keywords is None:
meilisearch_chunks = await meilisearch_index.query(
self.user_input, n=to_retrieve_from_each
)
else:
meilisearch_chunks = await meilisearch_index.query_keywords(
keywords, n=to_retrieve_from_each
)
chroma_chunks = await chroma_index.query(
query, n=2 * to_retrieve_from_each - len(meilisearch_chunks)
)
chunk_ids = set()
chunks = []
for chunk in chroma_chunks + meilisearch_chunks:
if chunk.id not in chunk_ids:
chunk_ids.add(chunk.id)
chunks.append(chunk)
# Rerank to select top results
yield SetStep(description="Selecting most important files...")
if use_reranking:
chunks = await single_token_reranker_parallel(
chunks,
self.user_input,
settings.n_final,
faster_model,
# group_size=settings.rerank_group_size,
)
# Add context items
context_items: List[ContextItem] = []
i = 0
for chunk in chunks:
# Can we select the context item through the normal means so that the name is disambiguated?
# Also so you don't have to understand the internals of the context provider
# OR have a chunk context provider??? Nice short-term, but I don't like it for long-term
ctx_item = ContextItem(
content=chunk.content,
description=ContextItemDescription(
name=f"{os.path.basename(chunk.document_id)} ({chunk.start_line}-{chunk.end_line})",
description=chunk.document_id,
id=ContextItemId(
provider_title="file",
item_id=remove_meilisearch_disallowed_chars(chunk.document_id),
),
),
) # Should be 'code' not file! And eventually should be able to embed all context providers automatically!
context_items.append(ctx_item)
await sdk.add_context_item(ctx_item)
if i < 8:
await asyncio.sleep(0.06)
i += 1
yield SetStep(hide=True)
model = sdk.models.chat.model
# if model == "gpt-4":
# model = "gpt-4-32k" # Not publicly available yet?
if model == "gpt-3.5-turbo":
model = "gpt-3.5-turbo-16k"
await sdk.run_step(
SimpleChatStep(
name="Answer Question",
description=f"Reading from {len(context_items)} files...",
completion_options=CompletionOptions(model=model),
prompt=PROMPT.format(user_input=self.user_input),
)
)
# for ctx_item in context_items:
# await sdk.delete_context_item(ctx_item.description.id)
class EditFileChroma(Step):
user_input: str
hide: bool = True
async def run(self, sdk: ContinueSDK):
index = ChromaCodebaseIndex(sdk.ide.workspace_directory)
results = index.query_codebase_index(self.user_input)
resource_name = list(results.source_nodes[0].node.relationships.values())[0]
filepath = resource_name[: resource_name.index("::")]
await sdk.run_step(
EditFileStep(
filepath=filepath,
prompt=f"Here is the code:\n\n{{code}}\n\nHere is the user request:\n\n{self.user_input}\n\nHere is the code after making the requested changes:\n",
)
)

View file

@ -4,5 +4,7 @@ from pydantic import BaseModel
class GlobalConfig(BaseModel):
meilisearch_url: Optional[str] = None
disable_meilisearch: bool = False
global_config = GlobalConfig()
global_config = GlobalConfig()

View file

@ -77,12 +77,29 @@ def health():
# endregion
async def cleanup_coroutine():
logger.debug("------ End logs ------")
def cleanup():
loop = asyncio.new_event_loop()
loop.run_until_complete(cleanup_coroutine())
loop.close()
def run_server(
port: int = 65432, host: str = "127.0.0.1", meilisearch_url: Optional[str] = None
port: int = 65432,
host: str = "127.0.0.1",
meilisearch_url: Optional[str] = None,
disable_meilisearch: bool = False,
):
try:
global global_config
global_config.meilisearch_url = meilisearch_url
global_config.disable_meilisearch = disable_meilisearch
logger.debug("------ Begin Logs ------")
atexit.register(cleanup)
config = uvicorn.Config(app, host=host, port=port)
server = uvicorn.Server(config)
@ -101,18 +118,6 @@ def run_server(
raise e
async def cleanup_coroutine():
logger.debug("------ End logs ------")
def cleanup():
loop = asyncio.new_event_loop()
loop.run_until_complete(cleanup_coroutine())
loop.close()
atexit.register(cleanup)
if __name__ == "__main__":
try:
# add cli arg for server port

View file

@ -1,6 +1,7 @@
import asyncio
import os
import shutil
import re
import subprocess
from typing import Optional
@ -82,7 +83,10 @@ async def ensure_meilisearch_installed() -> bool:
pass
existing_paths.remove(meilisearchPath)
await download_meilisearch()
try:
await asyncio.wait_for(download_meilisearch(), timeout=60)
except asyncio.TimeoutError:
logger.critical("Timed out trying to download MeiliSearch")
# Clear the existing directories
for p in existing_paths:
@ -141,6 +145,10 @@ async def start_meilisearch(url: Optional[str] = None):
meilisearch_url = url
return
if global_config.disable_meilisearch:
logger.debug("MeiliSearch disabled")
return
serverPath = getServerFolderPath()
# Check if MeiliSearch is installed, if not download
@ -195,3 +203,7 @@ async def restart_meilisearch():
stop_meilisearch()
kill_proc(7700)
await start_meilisearch(url=global_config.meilisearch_url)
def remove_meilisearch_disallowed_chars(id: str) -> str:
return re.sub(r"[^0-9a-zA-Z_-]", "", id)

View file

@ -0,0 +1,10 @@
from ...core.main import SessionUpdate
class CommandLineGUI:
async def send_session_update(self, session_update: SessionUpdate):
if hasattr(session_update.update, "description"):
print(session_update.update.description)
async def send_indexing_progress(self, progress: float):
print(f"Indexing... {int(progress*100)}%")

View file

@ -282,6 +282,21 @@ class GUIProtocolServer:
_running_autopilots: Dict[str, Autopilot] = {}
async def run_from_state(self, state: SessionState, step: Optional[Step] = None):
if step is not None or len(state.history) > 0:
step_to_log = step or state.history[-1]
posthog_logger.capture_event(
"step run",
{
"step_name": step_to_log.name,
"params": step_to_log.params if step is None else step.dict(),
"context": list(
map(
lambda item: item.dict(),
state.context_items,
)
),
},
)
autopilot = self.get_autopilot(state)
cancel_token = str(uuid.uuid4())
self._running_autopilots[cancel_token] = autopilot
@ -295,6 +310,9 @@ class GUIProtocolServer:
async def send_session_update(self, session_update: SessionUpdate):
await self.messenger.send("session_update", session_update.dict())
async def send_indexing_progress(self, progress: float):
await self.messenger.send("indexing_progress", {"progress": progress})
async def get_session_state(self) -> SessionState:
return await self.messenger.send_and_receive(
{}, SessionState, "get_session_state"

View file

@ -1,6 +1,10 @@
import traceback
from typing import Dict, Optional
from ..libs.util.create_async_task import create_async_task
from ..libs.index.build_index import build_index
from ..plugins.steps.on_traceback import DefaultOnTracebackStep
from ..core.context import ContextManager
@ -65,11 +69,12 @@ class Window:
async def reload_config(self):
self.config = self.load_config()
await self.config.models.start(
self.ide.window_info.unique_id,
self.config.system_message,
self.config.temperature,
)
if self.ide is not None:
await self.config.models.start(
self.ide.window_info.unique_id,
self.config.system_message,
self.config.temperature,
)
async def load(
self, config: Optional[ContinueConfig] = None, only_reloading: bool = False
@ -88,6 +93,12 @@ class Window:
if self._error_loading_config is not None:
await self.ide.setFileOpen(getConfigFilePath())
async def index():
async for progress in build_index(self.ide, self.config):
await self.gui.send_indexing_progress(progress)
create_async_task(index(), on_error=self.ide.on_error)
# Start models
await self.config.models.start(
self.ide.window_info.unique_id,

2707
server/poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[tool.poetry]
name = "continuedev"
version = "0.1.72"
version = "0.1.76"
description = ""
authors = ["Nate Sesti <sestinj@gmail.com>"]
readme = "README.md"
@ -37,7 +37,10 @@ chromadb = "^0.4.12"
fastapi = "0.95.2"
tree-sitter = "^0.20.2"
tree-sitter-languages = "^1.7.0"
rich = "^13.6.0"
python-socketio = "^5.10.0"
pathspec = "^0.11.2"
tqdm = "^4.66.1"
[tool.poetry.scripts]
typegen = "continuedev.models.generate_json_schema:main"
@ -45,6 +48,7 @@ typegen = "continuedev.models.generate_json_schema:main"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.1"
pytest-asyncio = "^0.21.1"
ipykernel = "^6.26.0"
[build-system]
requires = ["poetry-core"]