diff --git a/archive/server/CHANGELOG.md b/archive/server/CHANGELOG.md deleted file mode 100644 index 9eec3b199..000000000 --- a/archive/server/CHANGELOG.md +++ /dev/null @@ -1,23 +0,0 @@ -# Changelog -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), -and is generated by [Changie](https://github.com/miniscruff/changie). - - -## v0.1.104 - 2023-12-25 - -### Added - -- Continuous and faster syncing of codebase index - -### Removed - -- No longer using Continue Python server - -## v0.1.99 - 2023-11-19 - -### Changed - -- migrated to .json config file format diff --git a/archive/server/Cargo.lock b/archive/server/Cargo.lock deleted file mode 100644 index 9ef0cf647..000000000 --- a/archive/server/Cargo.lock +++ /dev/null @@ -1,1078 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "aho-corasick" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" -dependencies = [ - "memchr", -] - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "542f33a8835a0884b006a0c3df3dadd99c0c3f296ed26c2fdc8028e01ad6230c" -dependencies = [ - "memchr", - "serde", -] - -[[package]] -name = "bumpalo" -version = "3.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" - -[[package]] -name = "cc" -version = "1.0.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "num-traits", - "serde", - "windows-targets 0.48.5", -] - -[[package]] -name = "continuedev" -version = "0.1.0" -dependencies = [ - "hex-literal", - "homedir", - "ignore", - "pyo3", - "serde", - "serde_json", - "sha1", - "tempfile", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" - -[[package]] -name = "cpufeatures" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fca89a0e215bab21874660c67903c5f143333cab1da83d041c7ded6053774751" -dependencies = [ - "cfg-if", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2fe95351b870527a5d09bf563ed3c97c0cffb87cf1c78a591bf48bb218d9aa" -dependencies = [ - "autocfg", - "cfg-if", - "crossbeam-utils", - "memoffset 0.9.0", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "errno" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "fastrand" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" - -[[package]] -name = "futures" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" - -[[package]] -name = "futures-executor" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" - -[[package]] -name = "futures-macro" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.41", -] - -[[package]] -name = "futures-sink" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" - -[[package]] -name = "futures-task" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" - -[[package]] -name = "futures-util" -version = "0.3.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "globset" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57da3b9b5b85bd66f31093f8c408b90a74431672542466497dcbdfdc02034be1" -dependencies = [ - "aho-corasick", - "bstr", - "log", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hex-literal" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" - -[[package]] -name = "homedir" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22074da8bba2ef26fc1737ae6c777b5baab5524c2dc403b5c6a76166766ccda5" -dependencies = [ - "cfg-if", - "nix", - "serde", - "widestring", - "windows-sys 0.48.0", - "wmi", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ignore" -version = "0.4.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "747ad1b4ae841a78e8aba0d63adbfbeaea26b517b63705d47856b73015d27060" -dependencies = [ - "crossbeam-deque", - "globset", - "log", - "memchr", - "regex-automata", - "same-file", - "walkdir", - "winapi-util", -] - -[[package]] -name = "indoc" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" - -[[package]] -name = "itoa" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" - -[[package]] -name = "js-sys" -version = "0.3.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "libc" -version = "0.2.151" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" - -[[package]] -name = "linux-raw-sys" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" - -[[package]] -name = "lock_api" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" - -[[package]] -name = "memchr" -version = "2.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" - -[[package]] -name = "memoffset" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" -dependencies = [ - "autocfg", -] - -[[package]] -name = "memoffset" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" -dependencies = [ - "autocfg", -] - -[[package]] -name = "nix" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" -dependencies = [ - "bitflags 1.3.2", - "cfg-if", - "libc", - "memoffset 0.7.1", - "pin-utils", -] - -[[package]] -name = "num-traits" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - -[[package]] -name = "parking_lot" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets 0.48.5", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "proc-macro2" -version = "1.0.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "pyo3" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04e8453b658fe480c3e70c8ed4e3d3ec33eb74988bd186561b0cc66b85c3bc4b" -dependencies = [ - "cfg-if", - "indoc", - "libc", - "memoffset 0.9.0", - "parking_lot", - "pyo3-build-config", - "pyo3-ffi", - "pyo3-macros", - "unindent", -] - -[[package]] -name = "pyo3-build-config" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a96fe70b176a89cff78f2fa7b3c930081e163d5379b4dcdf993e3ae29ca662e5" -dependencies = [ - "once_cell", - "target-lexicon", -] - -[[package]] -name = "pyo3-ffi" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214929900fd25e6604661ed9cf349727c8920d47deff196c4e28165a6ef2a96b" -dependencies = [ - "libc", - "pyo3-build-config", -] - -[[package]] -name = "pyo3-macros" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dac53072f717aa1bfa4db832b39de8c875b7c7af4f4a6fe93cdbf9264cf8383b" -dependencies = [ - "proc-macro2", - "pyo3-macros-backend", - "quote", - "syn 2.0.41", -] - -[[package]] -name = "pyo3-macros-backend" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7774b5a8282bd4f25f803b1f0d945120be959a36c72e08e7cd031c792fdfd424" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.41", -] - -[[package]] -name = "quote" -version = "1.0.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "regex-automata" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" - -[[package]] -name = "rustix" -version = "0.38.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" -dependencies = [ - "bitflags 2.4.1", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.52.0", -] - -[[package]] -name = "ryu" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "serde" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.41", -] - -[[package]] -name = "serde_json" -version = "1.0.108" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "target-lexicon" -version = "0.12.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c39fd04924ca3a864207c66fc2cd7d22d7c016007f9ce846cbb9326331930a" - -[[package]] -name = "tempfile" -version = "3.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" -dependencies = [ - "cfg-if", - "fastrand", - "redox_syscall", - "rustix", - "windows-sys 0.48.0", -] - -[[package]] -name = "thiserror" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.41", -] - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "unindent" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7de7d73e1754487cb58364ee906a499937a0dfabd86bcb980fa99ec8c8fa2ce" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "walkdir" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.41", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.41", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f" - -[[package]] -name = "widestring" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "653f141f39ec16bba3c5abe400a0c60da7468261cc2cbf36805022876bc721a8" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-core" -version = "0.51.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-implement" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e2ee588991b9e7e6c8338edf3333fbe4da35dc72092643958ebb43f0ab2c49c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "windows-interface" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6fb8df20c9bcaa8ad6ab513f7b40104840c8867d5751126e4df3b08388d0cc7" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.0", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" -dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" - -[[package]] -name = "wmi" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced703d10188571ce53582c2932ce640ed3c413cff7ee6e2d961f9abdb6a63d1" -dependencies = [ - "chrono", - "futures", - "log", - "serde", - "thiserror", - "windows", -] diff --git a/archive/server/Cargo.toml b/archive/server/Cargo.toml deleted file mode 100644 index 171bc2914..000000000 --- a/archive/server/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -# If you already have [package] information in `Cargo.toml`, you can ignore -# this section! -[package] -# `name` here is name of the package. -name = "continuedev" -# these are good defaults: -version = "0.1.0" -edition = "2021" -license = "Apache-2.0" - -[lib] -# The name of the native library. This is the name which will be used in Python to import the -# library (i.e. `import string_sum`). If you change this, you must also change the name of the -# `#[pymodule]` in `src/lib.rs`. -name = "continuedev" - -# "cdylib" is necessary to produce a shared library for Python to import from. -crate-type = ["cdylib"] - -[dependencies] -hex-literal = "0.4.1" -homedir = "0.2.1" -ignore = "0.4.20" -pyo3 = { version = "0.20.0", features = ["extension-module"] } -serde = { version = "1.0.192", features = ["derive"] } -serde_json = "1.0.108" -sha1 = "0.10.6" -tempfile = "3.8.1" - -[dev-dependencies] -tempfile = "3.8.1" diff --git a/archive/server/README.md b/archive/server/README.md deleted file mode 100644 index 15642f077..000000000 --- a/archive/server/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# Continue PyPI Package - -This package contains the [Continue](https://github.com/continuedev/continue) server and core classes needed to build your own recipes. - -Continue is a Python library for automating repetitive sequences of software development tasks using language models. Using our VS Code extension, you can build, run, and refine these recipes as they natively interact with your codebase. Read the docs [here](https://continue.dev/docs) or download the VS Code extension [here](https://marketplace.visualstudio.com/items?itemName=Continue.continue). - -## Continue Server - -The Continue server acts as a bridge between the Continue React app and your IDE, running your recipes and acting on the codebase. - -Start it by running the following commands: - -1. `cd server` -2. Make sure packages are installed with `poetry install` - - If poetry is not installed, you can install with - ```bash - curl -sSL https://install.python-poetry.org | python3 - - ``` - (official instructions [here](https://python-poetry.org/docs/#installing-with-the-official-installer)) -3. `poetry shell` to activate the virtual environment -4. `python3 -m continuedev.server.main` to start the server - -Once you've validated that this works, you'll often want to use a debugger, in which case we've provided a launch configuration for VS Code in `.vscode/launch.json`. To start the debugger in VS Code, ensure that the workspace directory is the root of the `continue` repo, then press F5. - -> [!NOTE] -> To start the debugger, you'll have to select the poetry Python interpreter -> (`/path-to-poetry-venv/bin/python3`) in the bottom right of the VS Code window. If you -> don't see this, you may have to install the [Python -> extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python). - -## Scripts - -`poetry run typegen` to generate JSONSchema .json files from the Pydantic types defined in the `models` directory. - -`poetry build` will output wheel and tarball files in `./dist`. - -## Writing Steps - -See the `continuedev/libs/steps` folder for examples of writing a Continue step. See our documentation for tutorials. - -## How to contribute - -Open a [new GitHub Issue](https://github.com/continuedev/continue/issues/new) or comment on [an existing one](https://github.com/continuedev/continue/issues). Let us know what you would like to contribute, and we will help you make it happen! - -For more a more detailed contributing guide, see [CONTRIBUTING.md](../CONTRIBUTING.md). - -## Install from source - -#### 1. Clone this repo - -Recommended: Run this command to use SSH - -```bash -git clone git@github.com:continuedev/continue.git -``` - -Alternative: Run this command to use HTTPS - -```bash -git clone https://github.com/continuedev/continue -``` - -#### 2. Install Continue - -Run this command to use the install script - -```bash -cd continue/extensions/vscode/scripts && python3 install_from_source.py -``` - -> [!IMPORTANT] -> Ensure you have a Java Runtime Environment (JRE) installed. Verify this by typing `java --version` in your command prompt or terminal. If a version number appears, you're set. -> If not, download and install a JRE from Oracle's website or through a package manager, -> for example Homebrew. -> -> ```sh -> brew install openjdk@11 -> ``` - -# Understanding the codebase - -- [Continue Server README](./README.md): learn about the core of Continue, which can be downloaded as a [PyPI package](https://pypi.org/project/continuedev/) -- [VS Code Extension README](../extensions/vscode/README.md): learn about the capabilities of our extension—the first implementation of Continue's IDE Protocol—which makes it possible to use use Continue in VS Code and GitHub Codespaces -- [Continue GUI README](../gui/): learn about the React app that lets users interact with the server and is placed adjacent to the text editor in any supported IDE -- [Schema README](../schema/README.md): learn about the JSON Schema types generated from Pydantic models, which we use across the `server/` and `extensions/vscode/` directories -- [Continue Docs README](../docs/README.md): learn how our [docs](https://continue.dev/docs) are written and built -- [How to debug the VS Code Extension README](../extensions/vscode/src/README.md): learn how to set up the VS Code extension, so you can debug it diff --git a/archive/server/config.json b/archive/server/config.json deleted file mode 100644 index da827df5f..000000000 --- a/archive/server/config.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "models": [ - { - "title": "GPT-4", - "provider": "free-trial", - "model": "gpt-4" - }, - { - "title": "GPT-3.5-Turbo", - "provider": "free-trial", - "model": "gpt-3.5-turbo" - } - ], - "model_roles": { - "default": "GPT-4", - "summarize": "GPT-3.5-Turbo" - }, - "slash_commands": [ - { - "name": "edit", - "description": "Edit highlighted code", - "step": "EditHighlightedCodeStep" - }, - { - "name": "config", - "description": "Customize Continue", - "step": "OpenConfigStep" - }, - { - "name": "comment", - "description": "Write comments for the highlighted code", - "step": "CommentCodeStep" - }, - { - "name": "share", - "description": "Download and share this session", - "step": "ShareSessionStep" - }, - { - "name": "cmd", - "description": "Generate a shell command", - "step": "GenerateShellCommandStep" - } - ], - "custom_commands": [ - { - "name": "test", - "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "Write unit tests for highlighted code" - } - ] -} diff --git a/archive/server/config.py b/archive/server/config.py deleted file mode 100644 index b9032bda5..000000000 --- a/archive/server/config.py +++ /dev/null @@ -1,13 +0,0 @@ -""" -config.py allows you to modify Continue programmatically instead of just using config.json. - -First, config.json is loaded. Then, if you have defined modify_config here, the function will be given the result of -loading config.json, and will return the final ContinueConfig to be used. -""" - -from continuedev.core.config import ContinueConfig - - -def modify_config(config: ContinueConfig) -> ContinueConfig: - config.completion_options.temperature = 0.5 - return config diff --git a/archive/server/continuedev/__init__.py b/archive/server/continuedev/__init__.py deleted file mode 100644 index bc8616662..000000000 --- a/archive/server/continuedev/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -import asyncio -from typing import Union - -from .core.config import ContinueConfig -from .core.main import Step - -# from .headless import start_headless_session - - -def run(step_or_config: Union[Step, ContinueConfig, str]): - if isinstance(step_or_config, ContinueConfig): - config = step_or_config - elif isinstance(step_or_config, str): - config = ContinueConfig.from_filepath(step_or_config) - else: - config = ContinueConfig() - config.steps_on_startup = [step_or_config] - - loop = asyncio.get_event_loop() - # loop.run_until_complete(start_headless_session(config=config)) - tasks = asyncio.all_tasks(loop) - loop.run_until_complete(asyncio.gather(*tasks)) diff --git a/archive/server/continuedev/__main__.py b/archive/server/continuedev/__main__.py deleted file mode 100644 index 5b44c0871..000000000 --- a/archive/server/continuedev/__main__.py +++ /dev/null @@ -1,176 +0,0 @@ -import asyncio -import os -from typing import Optional - -import typer -from dotenv import load_dotenv -from rich.console import Console -from rich.markdown import Markdown -from tqdm import tqdm - -from . import run -from .core.config import ContinueConfig, RetrievalSettings -from .headless import get_headless_autopilot -from .headless.headless_ide import LocalIdeProtocol -from .libs.index.build_index import build_index -from .libs.index.chunkers.chunk import Chunk -from .libs.index.pipelines.main import main_retrieval_pipeline -from .libs.util.ext_to_lang import ext_to_lang -from .libs.util.paths import getConfigFilePath -from .server.main import run_server - -load_dotenv() -app = typer.Typer(invoke_without_command=True) - -console = Console() - - -CONTINUE_ASCII = r""" - -_________ _____ _____ -__ ____/______ _______ __ /____(_)_______ ____ _______ -_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \ -/ /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/ -\____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/ - -""" - - -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" - ), - headless: bool = typer.Option(False, help="Run in headless mode"), -): - if headless: - run(config or getConfigFilePath()) - else: - print(CONTINUE_ASCII) - 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.digest.split(".")[-1]) - console.print( - Markdown(f"\n**{chunk.digest}**\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 - config_obj = None - if config is None: - config_obj = ContinueConfig.load_default() - else: - config_obj = ContinueConfig.from_filepath(config) - - if config_obj.retrieval_settings is None: - config_obj.retrieval_settings = RetrievalSettings() - - config_obj.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_obj - ): - pbar.update(int(progress * 100) - pbar.n) - - pbar.close() - print("Indexing complete") - - asyncio.run(run()) - - -if __name__ == "__main__": - app() diff --git a/archive/server/continuedev/continuedev.py b/archive/server/continuedev/continuedev.py deleted file mode 100644 index 9a26baeea..000000000 --- a/archive/server/continuedev/continuedev.py +++ /dev/null @@ -1,20 +0,0 @@ -import asyncio -from typing import Union - -from .core.config import ContinueConfig -from .core.main import Step - -# from .headless import start_headless_session - - -def run(step_or_config: Union[Step, ContinueConfig]): - if isinstance(step_or_config, ContinueConfig): - config = step_or_config - else: - config = ContinueConfig() - config.steps_on_startup = [step_or_config] - - loop = asyncio.get_event_loop() - # loop.run_until_complete(start_headless_session(config=config)) - tasks = asyncio.all_tasks(loop) - loop.run_until_complete(asyncio.gather(*tasks)) diff --git a/archive/server/continuedev/continuedev.pyi b/archive/server/continuedev/continuedev.pyi deleted file mode 100644 index e26793021..000000000 --- a/archive/server/continuedev/continuedev.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import List, Tuple - -def sync_results( - dir: str, branch: str -) -> Tuple[ - List[Tuple[str, str]], - List[Tuple[str, str]], - List[Tuple[str, str]], - List[Tuple[str, str]], -]: - """Returns lists of files that need (compute, delete, add label, remove label) with each item being a (path, hash) tuple""" - ... diff --git a/archive/server/continuedev/core/abstract_sdk.py b/archive/server/continuedev/core/abstract_sdk.py deleted file mode 100644 index 1c517207a..000000000 --- a/archive/server/continuedev/core/abstract_sdk.py +++ /dev/null @@ -1,120 +0,0 @@ -from abc import abstractmethod, abstractproperty -from typing import List, Optional, Union - -from ..models.filesystem import RangeInFileWithContents -from ..models.filesystem_edit import FileSystemEdit -from ..models.main import Range -from ..server.protocols.gui_protocol import AbstractGUIProtocolServer -from ..server.protocols.ide_protocol import AbstractIdeProtocolServer -from .config import ContinueConfig -from .lsp import ContinueLSPClient -from .main import ChatMessage, Context, ContextItem, Step, StepDescription -from .models import Models - - -class AbstractContinueSDK: - """The SDK provided as parameters to a step""" - - ide: AbstractIdeProtocolServer - gui: AbstractGUIProtocolServer - config: ContinueConfig - models: Models - - lsp: Optional[ContinueLSPClient] = None - context: Context = Context() - - @abstractproperty - def history(self) -> List[StepDescription]: - ... - - @abstractproperty - def context_items(self) -> List[ContextItem]: - ... - - @abstractmethod - async def _ensure_absolute_path(self, path: str) -> str: - ... - - @abstractmethod - async def run_step(self, step: Step): - ... - - @abstractmethod - async def apply_filesystem_edit( - self, - edit: FileSystemEdit, - name: str = "Filesystem Edit", - description: str = "Filesystem Edit", - ): - ... - - @abstractmethod - async def run( - self, - commands: Union[List[str], str], - cwd: Optional[str] = None, - name: str = "Run Command", - description: str = "Run Command", - handle_error: bool = True, - ) -> str: - ... - - @abstractmethod - async def edit_file( - self, - filename: str, - prompt: str, - name: str = "Edit File", - description: str = "", - range: Optional[Range] = None, - ): - ... - - @abstractmethod - async def append_to_file(self, filename: str, content: str): - ... - - @abstractmethod - async def add_file(self, filename: str, content: Union[str, None]): - ... - - @abstractmethod - async def delete_file(self, filename: str): - ... - - @abstractmethod - async def add_directory(self, path: str): - ... - - @abstractmethod - async def delete_directory(self, path: str): - ... - - @abstractmethod - async def get_code_context( - self, only_editing: bool = False - ) -> List[RangeInFileWithContents]: - ... - - @abstractmethod - async def add_context_item(self, item: ContextItem): - ... - - @abstractmethod - def set_loading_message(self, message: str): - ... - - @abstractmethod - def raise_exception( - self, message: str, title: str, with_step: Union[Step, None] = None - ): - ... - - async def get_chat_context(self) -> List[ChatMessage]: - ... - - @abstractmethod - async def get_context_item_chat_messages( - self, exclude: Optional[str] = None - ) -> List[ChatMessage]: - ... diff --git a/archive/server/continuedev/core/autopilot.py b/archive/server/continuedev/core/autopilot.py deleted file mode 100644 index 3d8f8f52e..000000000 --- a/archive/server/continuedev/core/autopilot.py +++ /dev/null @@ -1,349 +0,0 @@ -import inspect -import uuid -from typing import List, Optional, cast - -from aiohttp import ClientPayloadError -from openai import ( - APIConnectionError, - APIError, - BadRequestError, - RateLimitError, - Timeout, -) - -from ..libs.llm.prompts.chat import template_alpaca_messages -from ..libs.util.devdata import dev_data_logger -from ..libs.util.errors import format_exc -from ..libs.util.logging import logger -from ..libs.util.strings import remove_quotes_and_escapes -from ..libs.util.telemetry import posthog_logger -from ..plugins.policies.default import DefaultPolicy -from ..server.protocols.gui_protocol import AbstractGUIProtocolServer -from ..server.protocols.ide_protocol import AbstractIdeProtocolServer -from .config import ContinueConfig -from .context import ContextManager -from .main import ( - AutopilotGenerator, - AutopilotGeneratorOutput, - Context, - ContextItem, - ContinueCustomException, - ContinueError, - DeltaStep, - Policy, - SessionState, - SessionUpdate, - SetStep, - Step, - StepDescription, - UpdateStep, -) -from .models import Models -from .observation import Observation -from .sdk import ContinueSDK - - -def get_error_title(e: Exception) -> str: - if isinstance(e, APIError): - return "OpenAI is overloaded with requests. Please try again." - elif isinstance(e, RateLimitError): - return "This OpenAI API key has been rate limited. Please try again." - elif isinstance(e, Timeout): - return "OpenAI timed out. Please try again." - elif isinstance(e, BadRequestError) and e.code == "context_length_exceeded": - return e.message or e.__str__() - elif isinstance(e, ClientPayloadError): - return "The request failed. Please try again." - elif isinstance(e, APIConnectionError): - return 'The request failed. Please check your internet connection and try again. If this issue persists, you can use our API key for free by going to VS Code settings and changing the value of continue.OPENAI_API_KEY to ""' - elif isinstance(e, BadRequestError): - return "Invalid request sent to OpenAI. Please try again." - elif "rate_limit_ip_middleware" in e.__str__(): - return "You have reached your limit for free usage of our token. You can continue using Continue by entering your own OpenAI API key in VS Code settings." - elif e.__str__().startswith("Cannot connect to host"): - return ( - "The request failed. Please check your internet connection and try again." - ) - return e.__str__() or e.__repr__() - - -class Autopilot: - session_state: SessionState - ide: AbstractIdeProtocolServer - gui: AbstractGUIProtocolServer - config: ContinueConfig - context_manager: ContextManager - - context: Context = Context() - - def __init__( - self, - session_state: SessionState, - ide: AbstractIdeProtocolServer, - gui: AbstractGUIProtocolServer, - config: ContinueConfig, - context_manager: ContextManager, - models: Models, - ): - self.session_state = session_state - self.ide = ide - self.gui = gui - self.config = config - self.context_manager = context_manager - self.models = models - - @property - def policy(self) -> Policy: - return self.config.policy_override or DefaultPolicy() - - @property - def sdk(self) -> ContinueSDK: - return ContinueSDK(self.config, self.ide, self.gui, self, self.models) - - class Config: - arbitrary_types_allowed = True - - def handle_error(self, e: Exception, step: Step) -> ContinueCustomException: - is_continue_custom_exception = ( - issubclass(e.__class__, ContinueCustomException) - or e.__class__.__name__ == ContinueCustomException.__name__ - ) - - if is_continue_custom_exception: - e = cast(ContinueCustomException, e) - error_string = e.message - error_title = e.title - else: - error_string = format_exc(e) - error_title = get_error_title(e) - - # Attach an InternalErrorObservation to the step and unhide it. - logger.error(f"Error while running step: \n{error_string}\n{error_title}") - posthog_logger.capture_event( - "step error", - { - "error_message": error_string, - "error_title": error_title, - "step_name": step.name, - "params": step.dict(), - }, - ) - - if is_continue_custom_exception: - return cast(ContinueCustomException, e) - else: - return ContinueCustomException(title=error_title, message=error_string) - - def log_step(self, step: Step, context_used: List[ContextItem]): - posthog_logger.capture_event( - "step run", - { - "step_name": step.name, - "params": step.dict(), - "context": list( - map( - lambda item: item.dict(), - context_used, - ) - ), - }, - ) - step_id = uuid.uuid4().hex - dev_data_logger.capture( - "step_run", - {"step_name": step.name, "params": step.dict(), "step_id": step_id}, - ) - dev_data_logger.capture( - "context_used", - { - "context": list( - map( - lambda item: item.dict(), - context_used, - ) - ), - "step_id": step_id, - }, - ) - - _step_depth: int = 0 - stopped = False - - async def _run_singular_step(self, step: "Step") -> AutopilotGenerator: - # Allow config to set disallowed steps - if ( - self.sdk.config.disallowed_steps is not None - and step.__class__.__name__ in self.sdk.config.disallowed_steps - ): - return - - # Log the context and step to dev data - context_used = self.session_state.context_items - self.log_step(step, context_used) - - # Update history - do this first so we get top-first tree ordering - self._step_depth += 1 - index = len(self.session_state.history) - yield StepDescription( - step_type=step.__class__.__name__, - name=step.name, - description=step.description, - params=step.dict(), - hide=step.hide, - depth=self._step_depth, - ) - - def handle_step_update( - update: UpdateStep, - ) -> Optional[AutopilotGeneratorOutput]: - if update.__class__.__name__ == "SessionUpdate": - return update # type: ignore - elif isinstance(update, str): - return SessionUpdate(index=index, update=DeltaStep(description=update)) - elif update.__class__.__name__ == "Observation": - return SessionUpdate( - index=index, - update=DeltaStep(observations=[cast(Observation, update)]), - ) - elif ( - update.__class__.__name__ == "DeltaStep" - or update.__class__.__name__ == "SetStep" - ): - return SessionUpdate(index=index, update=update) - elif update is None: - return None - else: - logger.warning(f"Unknown type yielded from Step: {update}") - - # Try to run step and handle errors - try: - if inspect.iscoroutinefunction(step.run): - await step.run(self.sdk) - elif inspect.isasyncgenfunction(step.run): - async for update in step.run(self.sdk): - if self.stopped: - if on_stop_generator := step.on_stop(self.sdk): - for update in on_stop_generator: # type: ignore - if handled := handle_step_update(update): - yield handled - return - - if handled := handle_step_update(update): - yield handled - else: - logger.warning( - f"{step.__class__.__name__}.run is not a coroutine function or async generator" - ) - - except Exception as e: - continue_custom_exception = self.handle_error(e, step) - - yield SessionUpdate(index=index, update=SetStep(hide=False)) - while self.session_state.history[index].name != step.name: - yield SessionUpdate(index=index, update=SetStep(hide=True)) - index -= 1 - - # i is now the index of the step that we want to show/rerun - yield SessionUpdate( - index=index, - update=SetStep( - error=ContinueError( - title=continue_custom_exception.title or "Error", - message=continue_custom_exception.message or "Error", - ), - hide=False, - ), - ) - - # ContinueCustomException can optionally specify a step to run on the error - if after_err_step := continue_custom_exception.with_step: - await self.run_step(after_err_step) - - self._step_depth -= 1 - - # NOTE: index here doesn't matter, awkward - yield SessionUpdate(index=index, stop=True, update=DeltaStep()) - - # # Update its description - # async def update_description(): - # if ( - # self.continue_sdk.config.disable_summaries - # or self.history.timeline[index_of_history_node].deleted - # ): - # return - - # description = await step.describe(self.continue_sdk.models) - # if description is not None: - # step.description = description - # # Update subscribers with new description - # await self.update_subscribers() - - # create_async_task( - # update_description(), - # on_error=lambda e: self.continue_sdk.run_step( - # DisplayErrorStep.from_exception(e) - # ), - # ) - - async def run_step(self, step: Step): - async for update in self._run_singular_step(step): - await self.handle_session_update(update) - - async def handle_session_update(self, update: AutopilotGeneratorOutput): - if update is None: - return - - if isinstance(update, StepDescription): - index = len(self.session_state.history) - self.session_state.history.append(update) - set_step = SetStep(**update.dict()) - await self.sdk.gui.send_session_update( - SessionUpdate(index=index, update=set_step) - ) - return - - if update.index > len(self.session_state.history): - raise Exception( - f"History update index {update.index} is greater than history length {len(self.session_state.history)}" - ) - elif update.index == len(self.session_state.history): - raise Exception( - f"History update index {update.index} is equal to history length {len(self.session_state.history)}. Must yield a StepDescription to add a new step." - ) - - self.session_state.history[update.index].update(update.update) - await self.sdk.gui.send_session_update(update) - - async def run(self, step: Optional[Step] = None): - async def add_log(log: str): - await self.handle_session_update( - SessionUpdate( - index=len(self.session_state.history) - 1, - update=DeltaStep(logs=[log]), - ) - ) - - logger_id = self.sdk.models.add_logger(add_log) - - if step is not None: - await self.run_step(step) - while next_step := self.policy.next(self.sdk.config, self.session_state): - await self.run_step(next_step) - - self.sdk.models.remove_logger(logger_id) - - async def get_session_title(self) -> str: - if self.sdk.config.disable_summaries: - return "New Session" - else: - chat_history = await self.sdk.get_chat_context() - chat_history_str = template_alpaca_messages(chat_history) - if self.sdk.models.summarize is None: - return "New Session" - - title = await self.sdk.models.summarize.complete( - f"{chat_history_str}\n\nGive a short title to describe the above chat session. Do not put quotes around the title. Do not use more than 6 words. The title is: ", - max_tokens=20, - log=False, - ) - return remove_quotes_and_escapes(title) diff --git a/archive/server/continuedev/core/config.py b/archive/server/continuedev/core/config.py deleted file mode 100644 index 1e81938d5..000000000 --- a/archive/server/continuedev/core/config.py +++ /dev/null @@ -1,711 +0,0 @@ -import importlib.util -import json -import os -from contextlib import contextmanager -from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast - -from pydantic import BaseModel, Field, validator - -from ..libs.constants.default_config import default_config_json -from ..libs.llm.base import LLM -from ..libs.llm.openai_free_trial import OpenAIFreeTrial -from ..libs.util.logging import logger -from ..libs.util.paths import getConfigFilePath, getGlobalFolderPath, sync_migrate -from ..libs.util.telemetry import posthog_logger -from ..models.llm import BaseCompletionOptions, RequestOptions -from .config_utils.context import CONTEXT_PROVIDER_NAME_TO_CLASS, ContextProviderName -from .config_utils.shared import ( - MODEL_CLASS_TO_MODEL_PROVIDER, - MODEL_PROVIDER_TO_MODEL_CLASS, - STEP_NAMES, - ModelProvider, - StepName, - TemplateType, - autodetect_prompt_templates, - autodetect_template_function, - autodetect_template_type, -) -from .context import ContextProvider -from .main import ContextProviderDescription, Policy, SlashCommandDescription, Step -from .models import MODEL_CLASSES, Models - - -class StepWithParams(BaseModel): - name: StepName - params: Dict[str, Any] = {} - - -class ContextProviderWithParams(BaseModel): - name: ContextProviderName - params: Dict[str, Any] = {} - - -class SlashCommand(BaseModel): - name: str - description: str - step: Union[Type[Step], StepName, str] - params: Optional[Dict] = {} - - # Allow step class for the migration - @validator("step", pre=True, always=True) - def step_is_string(cls, v): - if isinstance(v, str): - return v - elif ( - isinstance(v, object) - and v.__class__.__name__ == "ModelMetaclass" - and v.__class__.__name__ in STEP_NAMES - ): - return str(v).split(".")[-1].split("'")[0] - else: - return v - - def dict(self, *args, **kwargs): - d = super().dict(*args, **kwargs) - if isinstance(d["step"], str): - d["step"] = d["step"].split(".")[-1] - else: - d["step"] = d["step"].__name__ - return d - - def slash_command_description(self) -> SlashCommandDescription: - return SlashCommandDescription( - name=self.name, - description=self.description, - ) - - -class CustomCommand(BaseModel): - name: str - prompt: str - description: str - - def slash_command_description(self) -> SlashCommandDescription: - return SlashCommandDescription( - name=self.name, - description=self.description, - ) - - -class RetrievalSettings(BaseModel): - n_retrieve: Optional[int] = Field( - default=50, - description="Number of results to initially retrieve from vector database", - ) - n_final: Optional[int] = Field( - default=10, description="Final number of results to use after re-ranking" - ) - use_reranking: bool = Field( - default=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( - default=5, - description="Number of results to group together when re-ranking. Each group will be processed in parallel.", - ) - ignore_files: List[str] = Field( - default=[], - 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(default=None, description="OpenAI API key") - api_base: Optional[str] = Field(default=None, description="OpenAI API base URL") - api_type: Optional[str] = Field(default=None, description="OpenAI API type") - api_version: Optional[str] = Field(default=None, description="OpenAI API version") - organization_id: Optional[str] = Field( - default=None, description="OpenAI organization ID" - ) - - -class ModelDescription(BaseModel): - class Config: - extra = "allow" - - title: str = Field( - default=..., - description="The title you wish to give your model.", - ) - - provider: ModelProvider = Field( - default=..., - description="The provider of the model. This is used to determine the type of model, and how to interact with it.", - ) - model: str = Field( - default=..., - description="The name of the model. Used to autodetect prompt template.", - ) - api_key: Optional[str] = Field( - default=None, description="OpenAI, Anthropic, Together, or other API key" - ) - api_base: Optional[str] = Field( - default=None, description="The base URL of the LLM API." - ) - - context_length: int = Field( - default=2048, - description="The maximum context length of the LLM in tokens, as counted by count_tokens.", - ) - template: Optional[TemplateType] = Field( - default=None, - description="The chat template used to format messages. This is auto-detected for most models, but can be overridden here.", - ) - completion_options: BaseCompletionOptions = Field( - default=BaseCompletionOptions(), - description="Options for the completion endpoint. Read more about the completion options in the documentation.", - ) - system_message: Optional[str] = Field( - default=None, - description="A system message that will always be followed by the LLM", - ) - - request_options: RequestOptions = Field( - default=RequestOptions(), - description="Options for the HTTP request to the LLM.", - ) - - -class ModelRoles(BaseModel): - default: str = Field( - default=..., - description="The default model. If other model roles are not set, they will fall back to default.", - ) - chat: Optional[str] = Field( - default=None, - description="The model to use for chat. If not set, will fall back to default.", - ) - edit: Optional[str] = Field( - default=None, - description="The model to use for editing. If not set, will fall back to default.", - ) - summarize: Optional[str] = Field( - default=None, - description="The model to use for summarization. If not set, will fall back to default.", - ) - - -CONFIG_JSON_PATH = getConfigFilePath(json=True) - - -class SerializedContinueConfig(BaseModel): - disallowed_steps: Optional[List[str]] = Field( - default=[], - description="Steps that are not allowed to be run, and will be skipped if attempted", - ) - allow_anonymous_telemetry: Optional[bool] = Field( - default=True, - description="If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.", - ) - models: List[ModelDescription] = Field( - default=[ - ModelDescription( - title="GPT-4 (trial)", - provider="free-trial", - model="gpt-4", - api_key="", - ) - ] - ) - model_roles: ModelRoles = Field( - default=ModelRoles(default="GPT-4 (trial)"), - description="Roles for models. Each entry should be the title of a model in the models array.", - ) - system_message: Optional[str] = Field( - default=None, - description="A system message that will always be followed by the LLM", - ) - completion_options: BaseCompletionOptions = Field( - default=BaseCompletionOptions(), - description="Default options for completion. These will be overriden by any options set for a specific model.", - ) - slash_commands: Optional[List[SlashCommand]] = Field( - default=[], - description="An array of slash commands that let you map custom Steps to a shortcut.", - ) - custom_commands: Optional[List[CustomCommand]] = Field( - default=[ - CustomCommand( - name="test", - description="This is an example custom command. Use /config to edit it and create more", - prompt="Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - ) - ], - description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt.", - ) - context_providers: List[ContextProviderWithParams] = Field( - default=[], - description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", - ) - user_token: Optional[str] = Field( - default=None, description="An optional token to identify the user." - ) - data_server_url: Optional[str] = Field( - default="https://us-west1-autodebug.cloudfunctions.net", - description="The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.", - ) - disable_summaries: Optional[bool] = Field( - default=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.", - ) - disable_indexing: Optional[bool] = Field( - default=False, - description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.", - ) - retrieval_settings: Optional[RetrievalSettings] = Field( - default=RetrievalSettings(), - description="Settings for the retrieval system. Read more about the retrieval system in the documentation.", - ) - - @staticmethod - @contextmanager - def edit_config(): - config = SerializedContinueConfig.parse_file(CONFIG_JSON_PATH) - yield config - with open(CONFIG_JSON_PATH, "w") as f: - f.write(config.json(exclude_none=True, exclude_defaults=True, indent=2)) - - @staticmethod - def set_temperature(temperature: float): - with SerializedContinueConfig.edit_config() as config: - config.completion_options.temperature = temperature - - posthog_logger.capture_event( - "set_temperature", {"temperature": temperature} - ) - - @staticmethod - def set_system_message(message: str): - with SerializedContinueConfig.edit_config() as config: - config.system_message = message - - posthog_logger.capture_event("set_system_message", {"message": message}) - - @staticmethod - def set_model_for_role(title: str, role: str): - with SerializedContinueConfig.edit_config() as config: - if role == "*": - config.model_roles.default = title - config.model_roles.chat = title - config.model_roles.edit = title - config.model_roles.summarize = title - else: - config.model_roles.__setattr__(role, title) - - def migrate_func(): - if role == "default" and config.model_roles.chat is not None: - config.model_roles.chat = None - - sync_migrate("select_default_model_001", migrate_func) - - @staticmethod - def add_model(model: ModelDescription): - with SerializedContinueConfig.edit_config() as config: - config.models.append(model) - - @staticmethod - def set_telemetry_enabled(enabled: bool): - with SerializedContinueConfig.edit_config() as config: - config.allow_anonymous_telemetry = enabled - - @staticmethod - def delete_model(title: str): - with SerializedContinueConfig.edit_config() as config: - config.models = [model for model in config.models if model.title != title] - if config.model_roles.default == title: - config.model_roles.default = config.models[0].title - if config.model_roles.chat == title: - config.model_roles.chat = None - if config.model_roles.edit == title: - config.model_roles.edit = None - if config.model_roles.summarize == title: - config.model_roles.summarize = None - - -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. - """ - - steps_on_startup: List[Step] = Field( - default=[], - description="Steps that will be automatically run at the beginning of a new session", - ) - disallowed_steps: Optional[List[str]] = Field( - default=[], - description="Steps that are not allowed to be run, and will be skipped if attempted", - ) - allow_anonymous_telemetry: bool = Field( - default=True, - description="If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.", - ) - models: List[LLM] = Field( - default=[ - OpenAIFreeTrial( - title="GPT-4 (trial)", - model="gpt-4", - api_key="", - ) - ] - ) - model_roles: ModelRoles = Field( - default=ModelRoles(default="GPT-4 (trial)"), - description="Roles for models. Each entry should be the title of a model in the models array.", - ) - system_message: Optional[str] = Field( - default=None, - description="A system message that will always be followed by the LLM", - ) - completion_options: BaseCompletionOptions = Field( - default=BaseCompletionOptions(), - description="Options for the completion endpoint. Read more about the completion options in the documentation.", - ) - custom_commands: Optional[List[CustomCommand]] = Field( - default=[ - CustomCommand( - name="test", - description="This is an example custom command. Use /config to edit it and create more", - prompt="Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - ) - ], - description="An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt.", - ) - slash_commands: Optional[List[SlashCommand]] = Field( - default=[], - description="An array of slash commands that let you map custom Steps to a shortcut.", - ) - on_traceback: Optional[Step] = Field( - default=None, - description="The step that will be run when a traceback is detected (when you use the shortcut cmd+shift+R)", - ) - policy_override: Optional[Policy] = Field( - default=None, - description="A Policy object that can be used to override the default behavior of Continue, for example in order to build custom agents that take multiple steps at a time.", - ) - context_providers: List[ContextProvider] = Field( - default=[], - description="A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", - ) - user_token: Optional[str] = Field( - default=None, description="An optional token to identify the user." - ) - data_server_url: Optional[str] = Field( - default="https://us-west1-autodebug.cloudfunctions.net", - description="The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.", - ) - disable_summaries: Optional[bool] = Field( - default=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.", - ) - disable_indexing: bool = Field( - default=False, - description="If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.", - ) - retrieval_settings: Optional[RetrievalSettings] = Field( - default=RetrievalSettings(), - description="Settings for the retrieval system. Read more about the retrieval system in the documentation.", - ) - llm_request_hook: Optional[Callable[[str, str], Any]] = Field( - default=None, - description="A function that will be called before every request to the LLM. It will be passed the model used (str) and the exact prompt that is sent to the LLM (str).", - ) - - def dict(self, *args, **kwargs): - original_dict = super().dict(*args, **kwargs) - if "llm_request_hook" in original_dict: - del original_dict["llm_request_hook"] - - return original_dict - - @staticmethod - def from_serialized_config(config: SerializedContinueConfig) -> "ContinueConfig": - context_providers = [ - CONTEXT_PROVIDER_NAME_TO_CLASS[provider.name](**provider.params) - for provider in config.context_providers - ] - return ContinueConfig( - disallowed_steps=config.disallowed_steps, - allow_anonymous_telemetry=config.allow_anonymous_telemetry - if config.allow_anonymous_telemetry is not None - else True, - models=[ - ContinueConfig.create_llm(config.completion_options, model) - for model in config.models - ], - model_roles=config.model_roles, - system_message=config.system_message, - completion_options=config.completion_options, - custom_commands=config.custom_commands, - slash_commands=config.slash_commands, - context_providers=context_providers, - user_token=config.user_token, - data_server_url=config.data_server_url, - disable_summaries=config.disable_summaries, - disable_indexing=config.disable_indexing or False, - retrieval_settings=config.retrieval_settings, - ) - - @staticmethod - def modifiers_from_filepath( - filepath: str, - ) -> Tuple[Optional[Callable], Optional[Callable]]: - if not os.path.exists(filepath): - return None, None - - try: - if spec := importlib.util.spec_from_file_location("config", filepath): - config = importlib.util.module_from_spec(spec) - - if spec.loader: - spec.loader.exec_module(config) - - modify_config = None - modify_json = None - if hasattr(config, "modify_config"): - modify_config = config.modify_config - - if hasattr(config, "modify_json"): - modify_json = config.modify_json - - return modify_config, modify_json - - except Exception as e: - logger.warning(f"Failed to load config modifier from {filepath}: {e}") - return None, None - - return None, None - - @staticmethod - def from_filepath(filepath: str, retry: bool = True) -> "ContinueConfig": - if filepath.endswith(".json"): - try: - contents = open(filepath).read() - if contents.strip() == "": - raise ValueError("Empty config file") - - serialized_config = json.loads(contents) - - except json.JSONDecodeError as e: - raise e - - except ValueError as e: - logger.warning(f"Found empty config.json at {filepath}: {e}") - with open(filepath, "w") as f: - f.write(default_config_json) - - serialized_config = json.load(open(filepath)) - - serialized = SerializedContinueConfig(**serialized_config) - - modify_config, modify_json = ContinueConfig.modifiers_from_filepath( - filepath[: -len(".json")] + ".py" - ) - - if modify_json: - try: - serialized = modify_json(serialized) - except Exception as e: - logger.warning(f"Failed to modify config: {e}") - - final_config = ContinueConfig.from_serialized_config(serialized) - if modify_config: - try: - final_config = modify_config(final_config) - except Exception as e: - logger.warning(f"Failed to modify config: {e}") - - return final_config - - # Use importlib to load the config file config.py at the given path - if spec := importlib.util.spec_from_file_location("config", filepath): - config = importlib.util.module_from_spec(spec) - if spec.loader: - spec.loader.exec_module(config) - - return config.config - - raise Exception(f"Failed to load config from {filepath}") - - @staticmethod - def load_default() -> "ContinueConfig": - json_path = os.path.join(getGlobalFolderPath(), "config.json") - if not os.path.exists(json_path): - # MIGRATE FROM OLD CONFIG FORMAT TO JSON - def move_config_to_old(): - old_path = py_path.replace(".py", ".py.old") - if os.path.exists(old_path): - os.remove(old_path) - os.rename(py_path, old_path) - - py_path = getConfigFilePath() - try: - # If they have pre-existing old config.py this will work - config = ContinueConfig.from_filepath(py_path) - if os.path.exists(json_path): - os.remove(json_path) - - with open(json_path, "w") as f: - json.dump( - config.to_serialized_continue_config().dict( - exclude_none=True, exclude_defaults=True - ), - f, - indent=2, - ) - - # Rename config.py to config.old.py - move_config_to_old() - - return config - except Exception as e: - logger.warning(f"Failed to load config from {py_path}: {e}") - with open(json_path, "w") as f: - f.write(default_config_json) - - # Rename config.py to config.old.py - move_config_to_old() - - return ContinueConfig.load_default() - - # The second time and thereafter, load from the json file - config = ContinueConfig.from_filepath(json_path) - return config - - def get_slash_command_descriptions(self) -> List[SlashCommandDescription]: - custom_commands = ( - list( - map( - lambda x: x.slash_command_description(), - self.custom_commands or [], - ) - ) - or [] - ) - slash_commands = ( - list( - map( - lambda x: x.slash_command_description(), - self.slash_commands or [], - ) - ) - or [] - ) - cmds = custom_commands + slash_commands - cmds.sort(key=lambda x: x.name == "edit", reverse=True) - return cmds - - def get_context_provider_descriptions(self) -> List[ContextProviderDescription]: - """ - Returns a list of ContextProviderDescriptions - """ - return [ - provider.get_description() - for provider in self.context_providers - if provider.title != "code" # Code isn't used with '@' - ] + [ - ContextProviderDescription( - title="file", - display_title="Files", - description="Type to search the workspace", - dynamic=False, - requires_query=False, - ) - ] - - def to_serialized_continue_config(self) -> SerializedContinueConfig: - # For migration purposes - - slash_commands = [] - for slash_command in self.slash_commands or []: - if not isinstance(slash_command.step, str): - slash_command.step = slash_command.step.__class__.__name__ - slash_commands.append(slash_command) - - return SerializedContinueConfig( - disallowed_steps=self.disallowed_steps, - allow_anonymous_telemetry=self.allow_anonymous_telemetry, - models=[ - ContinueConfig.model_description_from(model) for model in self.models - ], - model_roles=self.model_roles, - system_message=self.system_message, - completion_options=self.completion_options, - custom_commands=self.custom_commands, - slash_commands=slash_commands, - context_providers=[ - ContextProviderWithParams( - name=cast(ContextProviderName, provider.title), - params=provider.dict(exclude_none=True, exclude_defaults=True), - ) - for provider in self.context_providers - if provider.title in CONTEXT_PROVIDER_NAME_TO_CLASS - ], - user_token=self.user_token, - data_server_url=self.data_server_url, - disable_summaries=self.disable_summaries, - disable_indexing=self.disable_indexing, - retrieval_settings=self.retrieval_settings, - ) - - @staticmethod - def create_llm( - completion_options: BaseCompletionOptions, model: ModelDescription - ) -> LLM: - model_class = MODEL_CLASSES[MODEL_PROVIDER_TO_MODEL_CLASS[model.provider]] - options = completion_options.dict(exclude_none=True, exclude_defaults=True) - options.update( - model.completion_options.dict(exclude_none=True, exclude_defaults=True) - ) - - if "max_tokens" not in options: - options["max_tokens"] = min(2048, model.context_length // 2) - - # Allow extra fields to be passed through - kwargs = {**model.dict(exclude_none=True)} - kwargs["completion_options"] = options - kwargs["template_messages"] = autodetect_template_function( - model.model, model.template - ) - kwargs["prompt_templates"] = autodetect_prompt_templates( - model.model, model.template - ) - - return model_class(**kwargs) - - @staticmethod - def model_description_from(llm: LLM) -> ModelDescription: - return ModelDescription( - title=llm.title or "LLM", - provider=MODEL_CLASS_TO_MODEL_PROVIDER.get( - llm.__class__.__name__, "custom" # type: ignore - ), - model=llm.model, - api_key=llm.api_key, - api_base=llm.api_base, - context_length=llm.context_length, - template=autodetect_template_type(llm.model), - completion_options=llm.completion_options, - system_message=llm.system_message, - request_options=llm.request_options, - ) - - def construct_models(self) -> Models: - def model_with_title(title: Optional[str], fallback: LLM): - return next(filter(lambda x: x.title == title, self.models), fallback) - - default = model_with_title(self.model_roles.default, self.models[0]) - chat = model_with_title(self.model_roles.chat, default) - edit = model_with_title(self.model_roles.edit, default) - summarize = model_with_title(self.model_roles.summarize, default) - - saved = [ - model_with_title(model.title, default) - for model in self.models - if model.title - not in [default.title, chat.title, edit.title, summarize.title] - ] - - return Models( - default=default, - chat=chat, - edit=edit, - summarize=summarize, - saved=saved, - ) diff --git a/archive/server/continuedev/core/config_utils/context.py b/archive/server/continuedev/core/config_utils/context.py deleted file mode 100644 index 4305b69ed..000000000 --- a/archive/server/continuedev/core/config_utils/context.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import Dict, Literal - -from ...plugins.context_providers.diff import DiffContextProvider -from ...plugins.context_providers.filetree import FileTreeContextProvider -from ...plugins.context_providers.github import GitHubIssuesContextProvider -from ...plugins.context_providers.google import GoogleContextProvider -from ...plugins.context_providers.open_tabs import OpenTabsContextProvider -from ...plugins.context_providers.search import SearchContextProvider -from ...plugins.context_providers.terminal import TerminalContextProvider -from ...plugins.context_providers.url import URLContextProvider - -ContextProviderName = Literal[ - "diff", - "github", - "terminal", - "open", - "google", - "search", - "url", - "tree", -] - -CONTEXT_PROVIDER_NAME_TO_CLASS = { - "diff": DiffContextProvider, - "github": GitHubIssuesContextProvider, - "terminal": TerminalContextProvider, - "open": OpenTabsContextProvider, - "google": GoogleContextProvider, - "search": SearchContextProvider, - "url": URLContextProvider, - "tree": FileTreeContextProvider, -} - -CLASS_TO_CONTEXT_PROVIDER_NAME: Dict[str, ContextProviderName] = { - "DiffContextProvider": "diff", - "GitHubIssuesContextProvider": "github", - "TerminalContextProvider": "terminal", - "OpenTabsContextProvider": "open", - "GoogleContextProvider": "google", - "SearchContextProvider": "search", - "URLContextProvider": "url", - "FileTreeContextProvider": "tree", -} diff --git a/archive/server/continuedev/core/config_utils/shared.py b/archive/server/continuedev/core/config_utils/shared.py deleted file mode 100644 index 70a800f33..000000000 --- a/archive/server/continuedev/core/config_utils/shared.py +++ /dev/null @@ -1,241 +0,0 @@ -from typing import Any, Dict, Literal, Optional - -from ...libs.llm.prompts.chat import ( - anthropic_template_messages, - chatml_template_messages, - deepseek_template_messages, - llama2_template_messages, - phind_template_messages, - template_alpaca_messages, - zephyr_template_messages, - neuralchat_template_messages, -) -from ...libs.llm.prompts.edit import ( - alpaca_edit_prompt, - codellama_edit_prompt, - deepseek_edit_prompt, - phind_edit_prompt, - simplest_edit_prompt, - zephyr_edit_prompt, - neuralchat_edit_prompt, -) - -STEP_NAMES = [ - "AnswerQuestionChroma", - "GenerateShellCommandStep", - "EditHighlightedCodeStep", - "ShareSessionStep", - "CommentCodeStep", - "ClearHistoryStep", - "StackOverflowStep", - "OpenConfigStep", - "DraftIssueStep", -] - -StepName = Literal[ - "AnswerQuestionChroma", - "EditHighlightedCodeStep", - "ShareSessionStep", - "CommentCodeStep", - "ClearHistoryStep", - "StackOverflowStep", - "OpenConfigStep", - "GenerateShellCommandStep", - "DraftIssueStep", -] - -TemplateType = Literal[ - "llama2", "alpaca", "zephyr", "phind", "anthropic", "chatml", "deepseek", "neural-chat" -] - - -def autodetect_template_type(model: str) -> Optional[TemplateType]: - lower = model.lower() - if "gpt" in lower or "chat-bison" in lower or "pplx" in lower: - return None - - if "phind" in lower: - return "phind" - - if "llama" in lower: - return "llama2" - - if "zephyr" in lower: - return "zephyr" - - if "claude" in lower: - return "anthropic" - - if "alpaca" in lower or "wizard" in lower: - return "alpaca" - - if "mistral" in lower: - return "llama2" - - if "deepseek" in lower: - return "deepseek" - - if "neural-chat" in lower: - return "neural-chat" - - return "chatml" - - -def autodetect_template_function( - model: str, explicit_template: Optional[TemplateType] = None -): - if template_type := explicit_template or autodetect_template_type(model): - mapping: Dict[TemplateType, Any] = { - "llama2": llama2_template_messages, - "alpaca": template_alpaca_messages, - "phind": phind_template_messages, - "zephyr": zephyr_template_messages, - "anthropic": anthropic_template_messages, - "chatml": chatml_template_messages, - "deepseek": deepseek_template_messages, - "neural-chat": neuralchat_template_messages - } - return mapping[template_type] - return None - - -def autodetect_prompt_templates( - model: str, explicit_template: Optional[TemplateType] = None -): - template_type = explicit_template or autodetect_template_type(model) - - templates = {} - - edit_template = None - if template_type == "phind": - edit_template = phind_edit_prompt - elif template_type == "zephyr": - edit_template = zephyr_edit_prompt - elif template_type == "llama2": - edit_template = codellama_edit_prompt - elif template_type == "alpaca": - edit_template = alpaca_edit_prompt - elif template_type == "deepseek": - edit_template = deepseek_edit_prompt - elif template_type == "neural-chat": - edit_template = neuralchat_edit_prompt - elif template_type is not None: - edit_template = simplest_edit_prompt - - if edit_template is not None: - templates["edit"] = edit_template - - return templates - - -ModelProvider = Literal[ - "openai", - "free-trial", - "openai-aiohttp", - "anthropic", - "together", - "ollama", - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "replicate", - "text-gen-webui", - "google-palm", - "lmstudio", - "llamafile", -] - -MODEL_PROVIDER_TO_MODEL_CLASS = { - "openai": "OpenAI", - "free-trial": "OpenAIFreeTrial", - "openai-aiohttp": "GGML", - "anthropic": "AnthropicLLM", - "together": "TogetherLLM", - "ollama": "Ollama", - "huggingface-tgi": "HuggingFaceTGI", - "huggingface-inference-api": "HuggingFaceInferenceAPI", - "llama.cpp": "LlamaCpp", - "replicate": "ReplicateLLM", - "text-gen-webui": "TextGenWebUI", - "google-palm": "GooglePaLMAPI", - "lmstudio": "LMStudio", - "llamafile": "Llamafile", -} - -MODEL_CLASS_TO_MODEL_PROVIDER: Dict[str, ModelProvider] = { - "OpenAI": "openai", - "OpenAIFreeTrial": "free-trial", - "AnthropicLLM": "anthropic", - "TogetherLLM": "together", - "Ollama": "ollama", - "HuggingFaceTGI": "huggingface-tgi", - "HuggingFaceInferenceAPI": "huggingface-inference-api", - "LlamaCpp": "llama.cpp", - "ReplicateLLM": "replicate", - "TextGenWebUI": "text-gen-webui", - "GooglePaLMAPI": "google-palm", - "LMStudio": "lmstudio", - "Llamafile": "llamafile", -} - -MODELS = [ - # OpenAI - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-1106-preview", - # Open-Source - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-1b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b" - # Anthropic - "claude-2", - # Google PaLM - "chat-bison-001", -] - -ModelName = Literal[ - # OpenAI - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-1106-preview", - # Open-Source - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-1b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - # Anthropic - "claude-2", - # Google PaLM - "chat-bison-001", -] diff --git a/archive/server/continuedev/core/config_utils/step_name_to_class.py b/archive/server/continuedev/core/config_utils/step_name_to_class.py deleted file mode 100644 index 7f84ed9bc..000000000 --- a/archive/server/continuedev/core/config_utils/step_name_to_class.py +++ /dev/null @@ -1,23 +0,0 @@ -from ...plugins.steps.clear_history import ClearHistoryStep -from ...plugins.steps.cmd import GenerateShellCommandStep -from ...plugins.steps.codebase import AnswerQuestionChroma -from ...plugins.steps.comment_code import CommentCodeStep -from ...plugins.steps.draft_issue import DraftIssueStep -from ...plugins.steps.main import EditHighlightedCodeStep -from ...plugins.steps.on_traceback import DefaultOnTracebackStep -from ...plugins.steps.open_config import OpenConfigStep -from ...plugins.steps.share_session import ShareSessionStep -from ...plugins.steps.stack_overflow import StackOverflowStep - -step_name_to_step_class = { - "EditHighlightedCodeStep": EditHighlightedCodeStep, - "CommentCodeStep": CommentCodeStep, - "DefaultOnTracebackStep": DefaultOnTracebackStep, - "ClearHistoryStep": ClearHistoryStep, - "OpenConfigStep": OpenConfigStep, - "AnswerQuestionChroma": AnswerQuestionChroma, - "GenerateShellCommandStep": GenerateShellCommandStep, - "ShareSessionStep": ShareSessionStep, - "StackOverflowStep": StackOverflowStep, - "DraftIssueStep": DraftIssueStep, -} diff --git a/archive/server/continuedev/core/context.py b/archive/server/continuedev/core/context.py deleted file mode 100644 index 0b56db5d8..000000000 --- a/archive/server/continuedev/core/context.py +++ /dev/null @@ -1,487 +0,0 @@ -import asyncio -import time -from abc import abstractmethod -from typing import Any, Awaitable, Callable, List, Optional - -from meilisearch_python_async import Client -from pydantic import BaseModel, Field - -from ..libs.util.create_async_task import create_async_task -from ..libs.util.devdata import dev_data_logger -from ..libs.util.logging import logger -from ..libs.util.paths import migrate -from ..libs.util.telemetry import posthog_logger -from ..server.global_config import global_config -from ..server.meilisearch_server import ( - check_meilisearch_running, - get_meilisearch_url, - poll_meilisearch_running, - remove_meilisearch_disallowed_chars, - restart_meilisearch, - start_meilisearch, -) -from ..server.protocols.ide_protocol import AbstractIdeProtocolServer -from .main import ( - ChatMessage, - ContextItem, - ContextItemDescription, - ContextItemId, - ContextProviderDescription, -) - - -class ContinueSDK(BaseModel): - """To avoid circular imports""" - - ... - - -SEARCH_INDEX_NAME = "continue_context_items" - - -class ContextProvider(BaseModel): - """ - The ContextProvider class is a plugin that lets you provide new information to the LLM by typing '@'. - When you type '@', the context provider will be asked to populate a list of options. - These options will be updated on each keystroke. - When you hit enter on an option, the context provider will add that item to the autopilot's list of context (which is all stored in the ContextManager object). - """ - - title: str = Field( - ..., - description="The title of the ContextProvider. This is what must be typed in the input to trigger the ContextProvider.", - ) - ide: Any = None - - delete_documents: Callable[[List[str]], Awaitable] | None = Field( - None, description="Function to delete documents" - ) - update_documents: Callable[[List[ContextItem], str], Awaitable] | None = Field( - None, description="Function to update documents" - ) - - display_title: str = Field( - ..., - description="The display title of the ContextProvider shown in the dropdown menu", - ) - description: str = Field( - ..., - description="A description of the ContextProvider displayed in the dropdown menu", - ) - dynamic: bool = Field( - ..., description="Indicates whether the ContextProvider is dynamic" - ) - requires_query: bool = Field( - False, - description="Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search '. This will change the behavior of the UI so that it can indicate the expectation for a query.", - ) - - selected_items: List[ContextItem] = Field( - [], description="List of selected items in the ContextProvider" - ) - - class Config: - arbitrary_types_allowed = True - exclude = {"ide", "delete_documents", "update_documents"} - - def get_description(self) -> ContextProviderDescription: - return ContextProviderDescription( - title=self.title, - display_title=self.display_title, - description=self.description, - dynamic=self.dynamic, - requires_query=self.requires_query, - ) - - def dict(self, *args, **kwargs): - original_dict = super().dict(*args, **kwargs) - original_dict.pop("ide", None) - original_dict.pop("delete_documents", None) - original_dict.pop("update_documents", None) - return original_dict - - async def start( - self, ide: AbstractIdeProtocolServer, delete_documents, update_documents - ): - """ - Starts the context provider. - - Default implementation sets the sdk. - """ - self.ide = ide - self.delete_documents = delete_documents - self.update_documents = update_documents - - async def get_selected_items(self) -> List[ContextItem]: - """ - Returns all of the selected ContextItems. - - Default implementation simply returns self.selected_items. - - Other implementations may add an async processing step. - """ - return self.selected_items - - @abstractmethod - async def provide_context_items(self, workspace_dir: str) -> List[ContextItem]: - """ - Provide documents for search index. This is run on startup. - - This is the only method that must be implemented. - """ - - async def get_chat_message(self, item: ContextItem) -> ChatMessage: - """Returns the ChatMessage for the given ContextItem.""" - return ChatMessage( - role="user", - content=f"{item.description.name}: {item.description.description}\n\n{item.content}", - summary=item.description.description, - ) - - async def get_item(self, id: ContextItemId, query: str) -> Optional[ContextItem]: - """ - Returns the ContextItem with the given id. - - Default implementation uses the search index to get the item. - """ - async with Client(get_meilisearch_url()) as search_client: - try: - result = await search_client.index(SEARCH_INDEX_NAME).get_document( - id.to_string() - ) - return ContextItem( - description=ContextItemDescription( - name=result["name"], description=result["description"], id=id - ), - content=result["content"], - ) - except Exception as e: - logger.warning(f"Error while retrieving document from meilisearch: {e}") - - return None - - async def clear_context(self): - """ - Clears all context. - - Default implementation simply clears the selected items. - """ - self.selected_items = [] - - async def add_context_item(self, id: ContextItemId, query: str): - """ - Adds the given ContextItem to the list of ContextItems. - - Default implementation simply appends the item, not allowing duplicates. - - This method also allows you not to have to load all of the information until an item is selected. - """ - - # Don't add duplicate context - for item in self.selected_items: - if item.description.id.item_id == id.item_id: - return - - if new_item := await self.get_item(id, query): - self.selected_items.append(new_item) - - async def preview_contents(self, id: ContextItemId): - """ - Open a virtual file or otherwise preview the contents of the context provider in the IDE - """ - if item := next( - filter(lambda x: x.description.id == id, self.selected_items), None - ): - await self.ide.showVirtualFile(item.description.name, item.content) - - -class ContextManager: - """ - The context manager is responsible for storing the context to be passed to the LLM, including - - ContextItems (highlighted code, GitHub Issues, etc.) - - ChatMessages in the history - - System Message - - Functions - - It is responsible for compiling all of this information into a single prompt without exceeding the token limit. - """ - - async def get_chat_messages(self, items: List[ContextItem]) -> List[ChatMessage]: - """ - Returns chat messages from each provider. - """ - tasks = [] - msgs = [] - for item in items: - if item.description.id.provider_title in self.context_providers: - tasks.append( - self.context_providers[ - item.description.id.provider_title - ].get_chat_message(item) - ) - else: - msgs.append( - ChatMessage( - role="user", - content=item.content, - summary=item.description.description, - ) - ) - - return (await asyncio.gather(*tasks)) + msgs - - def __init__(self): - self.context_providers = {} - self.provider_titles = set() - - async def start( - self, - context_providers: List[ContextProvider], - ide: AbstractIdeProtocolServer, - only_reloading: bool = False, - disable_indexing: bool = False, - ): - """ - Starts the context manager. - """ - new_context_providers = { - provider.title: provider - for provider in context_providers - if provider.title not in self.provider_titles - } - - self.context_providers = { - provider.title: provider for provider in context_providers - } - self.provider_titles = {provider.title for provider in context_providers} - - for provider in context_providers: - await provider.start( - ide, - ContextManager.delete_documents, - ContextManager.update_documents, - ) - - async def on_err(e): - logger.warning(f"Error loading meilisearch index: {e}") - - # Start MeiliSearch in the background without blocking - async def load_index(providers_to_load: List[ContextProvider]): - running = await check_meilisearch_running() - if not running: - await start_meilisearch(global_config.meilisearch_url) - try: - await asyncio.wait_for(poll_meilisearch_running(), timeout=20) - except asyncio.TimeoutError: - logger.warning( - "Meilisearch did not start in less than 20 seconds. Stopping polling." - ) - return - - ti = time.time() - await self.load_index( - ide.workspace_directory, providers_to_load=providers_to_load - ) - logger.info(f"Loaded Meilisearch index in {time.time() - ti:.3f} seconds") - - providers_to_load = ( - list(new_context_providers.values()) - if only_reloading - else context_providers - ) - - if not disable_indexing: - create_async_task(load_index(providers_to_load), on_err) - - @staticmethod - async def update_documents(context_items: List[ContextItem], workspace_dir: str): - """ - Updates the documents in the search index. - """ - documents = [ - { - "id": item.description.id.to_string(), - "name": item.description.name, - "description": item.description.description, - "content": item.content, - "workspace_dir": workspace_dir, - "provider_name": item.description.id.provider_title, - } - for item in context_items - ] - async with Client(get_meilisearch_url()) as search_client: - - async def add_docs(): - index = await search_client.get_index(SEARCH_INDEX_NAME) - await index.add_documents(documents or []) - - try: - await asyncio.wait_for(add_docs(), timeout=20) - except asyncio.TimeoutError: - logger.warning("Failed to add document to meilisearch in 20 seconds") - except Exception as e: - logger.warning(f"Error adding document to meilisearch: {e}") - - @staticmethod - async def delete_documents(ids): - """ - Deletes the documents in the search index. - """ - async with Client(get_meilisearch_url()) as search_client: - try: - await asyncio.wait_for( - search_client.index(SEARCH_INDEX_NAME).delete_documents(ids), - timeout=20, - ) - except asyncio.TimeoutError: - logger.warning( - "Failed to delete document from meilisearch in 20 seconds" - ) - except Exception as e: - logger.warning(f"Error deleting document from meilisearch: {e}") - - async def load_index( - self, - workspace_dir: str, - should_retry: bool = True, - providers_to_load: Optional[List[ContextProvider]] = None, - ): - try: - async with Client(get_meilisearch_url()) as search_client: - # First, create the index if it doesn't exist - # The index is currently shared by all workspaces - - # Check if need to migrate to new id format - # If so, delete the index before recreating - async def migrate_fn(): - await search_client.delete_index_if_exists(SEARCH_INDEX_NAME) - - await migrate( - "meilisearch_context_items_001", - migrate_fn, - ) - - await search_client.create_index(SEARCH_INDEX_NAME) - globalSearchIndex = await search_client.get_index(SEARCH_INDEX_NAME) - await globalSearchIndex.update_ranking_rules( - ["attribute", "words", "typo", "proximity", "sort", "exactness"] - ) - await globalSearchIndex.update_searchable_attributes( - ["name", "description"] - ) - await globalSearchIndex.update_filterable_attributes( - ["workspace_dir", "provider_name"] - ) - - async def load_context_provider(provider: ContextProvider): - context_items = await provider.provide_context_items(workspace_dir) - documents = [ - { - "id": item.description.id.to_string() - + remove_meilisearch_disallowed_chars(workspace_dir), - "name": item.description.name, - "description": item.description.description, - "content": item.content, - "workspace_dir": workspace_dir, - "provider_name": provider.title, - } - for item in context_items - ] - if len(documents) > 0: - await globalSearchIndex.add_documents(documents) - - return len(documents) - - async def safe_load(provider: ContextProvider): - try: - await asyncio.wait_for( - load_context_provider(provider), timeout=20 - ) - except asyncio.TimeoutError: - logger.warning( - f"Failed to add documents to meilisearch for context provider {provider.__class__.__name__} in 20 seconds" - ) - return - except Exception as e: - logger.warning( - f"Error adding documents to meilisearch for context provider {provider.__class__.__name__}: {e}" - ) - return - - # logger.info( - # f"Loaded {num_documents} documents into meilisearch in {tf - ti} seconds for context provider {provider.title}" - # ) - - tasks = [ - safe_load(provider) - for _, provider in ( - {provider.title: provider for provider in providers_to_load} - if providers_to_load - else self.context_providers - ).items() - ] - await asyncio.wait_for(asyncio.gather(*tasks), timeout=20) - - except Exception as e: - logger.debug(f"Error loading meilisearch index: {e}") - if should_retry: - try: - await restart_meilisearch() - await asyncio.wait_for(poll_meilisearch_running(), timeout=20) - except asyncio.TimeoutError: - logger.warning( - "Meilisearch did not restart in less than 20 seconds. Stopping polling." - ) - except Exception as e: - logger.warning(f"Error restarting meilisearch: {e}") - - await self.load_index(workspace_dir, False) - - async def get_context_item(self, id: str, query: str) -> Optional[ContextItem]: - """ - Returns the ContextItem with the given id. - """ - item_id: ContextItemId = ContextItemId.from_string(id) - if item_id.provider_title not in self.provider_titles: - raise ValueError( - f"Context provider with title {item_id.provider_title} not found" - ) - - posthog_logger.capture_event( - "select_context_item", - { - "provider_title": item_id.provider_title, - "item_id": item_id.item_id, - "query": query, - }, - ) - dev_data_logger.capture( - "select_context_item", - { - "provider_title": item_id.provider_title, - "item_id": item_id.item_id, - "query": query, - }, - ) - - return await self.context_providers[item_id.provider_title].get_item( - item_id, query - ) - - async def preview_context_item(self, id: str): - """ - Opens a virtual file or otherwise previews the contents of the context provider in the IDE. - """ - item_id: ContextItemId = ContextItemId.from_string(id) - if item_id.provider_title not in self.provider_titles: - raise ValueError( - f"Context provider with title {item_id.provider_title} not found" - ) - - await self.context_providers[item_id.provider_title].preview_contents(item_id) - - -""" -Should define "ArgsTransformer" and "PromptTransformer" classes for the different LLMs. A standard way for them to ingest the -same format of prompts so you don't have to redo all of this logic. -""" diff --git a/archive/server/continuedev/core/env.py b/archive/server/continuedev/core/env.py deleted file mode 100644 index 60b865387..000000000 --- a/archive/server/continuedev/core/env.py +++ /dev/null @@ -1,31 +0,0 @@ -import os - -from dotenv import load_dotenv - - -def get_env_var(var_name: str): - load_dotenv() - return os.getenv(var_name) - - -def make_sure_env_exists(): - if not os.path.exists(".env"): - with open(".env", "w") as f: - f.write("") - - -def save_env_var(var_name: str, var_value: str): - make_sure_env_exists() - - with open(".env", "r") as f: - lines = f.readlines() - with open(".env", "w") as f: - values = {} - for line in lines: - key, value = line.split("=") - value = value.replace('"', "") - values[key] = value - - values[var_name] = var_value - for key, value in values.items(): - f.write(f'{key}="{value}"\n') diff --git a/archive/server/continuedev/core/lsp.py b/archive/server/continuedev/core/lsp.py deleted file mode 100644 index 379396862..000000000 --- a/archive/server/continuedev/core/lsp.py +++ /dev/null @@ -1,416 +0,0 @@ -import asyncio -import threading -from typing import List, Literal, Optional - -import aiohttp -from pydantic import BaseModel - -from ..models.filesystem import RangeInFile -from ..models.main import Position, Range - - -def filepath_to_uri(filename: str) -> str: - return f"file://{filename}" - - -def uri_to_filepath(uri: str) -> str: - if uri.startswith("file://"): - return uri[7:] - else: - return uri - - -PORT = 8099 - - -class LSPClient: - ready: bool = False - lock: asyncio.Lock = asyncio.Lock() - - def __init__(self, host: str, port: int, workspace_paths: List[str]): - self.host = host - self.port = port - self.session = aiohttp.ClientSession() - self.next_id = 0 - self.workspace_paths = workspace_paths - - async def connect(self): - print("Connecting") - self.ws = await self.session.ws_connect(f"ws://{self.host}:{self.port}/") - print("Connected") - self.ready = True - - async def send(self, data): - await self.ws.send_json(data) - - async def recv(self): - await self.lock.acquire() - - try: - return await self.ws.receive_json() - finally: - self.lock.release() - - async def close(self): - await self.ws.close() - await self.session.close() - - async def call_method(self, method_name, **kwargs): - body = { - "jsonrpc": "2.0", - "id": self.next_id, - "method": method_name, - "params": kwargs, - } - self.next_id += 1 - await self.send(body) - response = await self.recv() - return response - - async def initialize(self): - initialization_args = { - "capabilities": { - "textDocument": { - "codeAction": {"dynamicRegistration": True}, - "codeLens": {"dynamicRegistration": True}, - "colorProvider": {"dynamicRegistration": True}, - "completion": { - "completionItem": { - "commitCharactersSupport": True, - "documentationFormat": ["markdown", "plaintext"], - "snippetSupport": True, - }, - "completionItemKind": { - "valueSet": [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - ] - }, - "contextSupport": True, - "dynamicRegistration": True, - }, - "definition": {"dynamicRegistration": True}, - "documentHighlight": {"dynamicRegistration": True}, - "documentLink": {"dynamicRegistration": True}, - "documentSymbol": { - "dynamicRegistration": True, - "symbolKind": { - "valueSet": [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - ] - }, - }, - "formatting": {"dynamicRegistration": True}, - "hover": { - "contentFormat": ["markdown", "plaintext"], - "dynamicRegistration": True, - }, - "implementation": {"dynamicRegistration": True}, - "onTypeFormatting": {"dynamicRegistration": True}, - "publishDiagnostics": {"relatedInformation": True}, - "rangeFormatting": {"dynamicRegistration": True}, - "references": {"dynamicRegistration": True}, - "rename": {"dynamicRegistration": True}, - "signatureHelp": { - "dynamicRegistration": True, - "signatureInformation": { - "documentationFormat": ["markdown", "plaintext"] - }, - }, - "synchronization": { - "didSave": True, - "dynamicRegistration": True, - "willSave": True, - "willSaveWaitUntil": True, - }, - "typeDefinition": {"dynamicRegistration": True}, - }, - "workspace": { - "applyEdit": True, - "configuration": True, - "didChangeConfiguration": {"dynamicRegistration": True}, - "didChangeWatchedFiles": {"dynamicRegistration": True}, - "executeCommand": {"dynamicRegistration": True}, - "symbol": { - "dynamicRegistration": True, - "symbolKind": { - "valueSet": [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - 26, - ] - }, - }, - "workspaceEdit": {"documentChanges": True}, - "workspaceFolders": True, - }, - }, - "processId": 1234, - "rootPath": None, - "rootUri": filepath_to_uri(self.workspace_paths[0]), - "initializationOptions": {}, - "trace": "off", - "workspaceFolders": [ - { - "uri": filepath_to_uri(workspacePath), - "name": workspacePath.split("/")[-1], - } - for workspacePath in self.workspace_paths - ], - } - return await self.call_method("initialize", **initialization_args) - - async def goto_definition(self, filepath: str, position: Position): - return await self.call_method( - "textDocument/definition", - textDocument={"uri": filepath_to_uri(filepath)}, - position=position.dict(), - ) - - async def document_symbol(self, filepath: str): - return await self.call_method( - "textDocument/documentSymbol", - textDocument={"uri": filepath_to_uri(filepath)}, - ) - - async def find_references( - self, filepath: str, position: Position, include_declaration: bool = False - ): - return await self.call_method( - "textDocument/references", - textDocument={"uri": filepath_to_uri(filepath)}, - position=position.dict(), - context={"includeDeclaration": include_declaration}, - ) - - async def folding_range(self, filepath: str): - response = await self.call_method( - "textDocument/foldingRange", - textDocument={"uri": filepath_to_uri(filepath)}, - ) - return response["result"] - - -async def start_language_server() -> threading.Thread: - """Manually start the python language server. Not used currently.""" - raise NotImplementedError() - # try: - # kill_proc(PORT) - # thread = threading.Thread( - # target=start_ws_lang_server, - # args=(PORT, False, PythonLSPServer), - # ) - # thread.daemon = True - # thread.start() - - # except Exception as e: - # logger.warning("Could not start TCP server: %s", e) - - # await asyncio.sleep(2) - - # return thread - - -class DocumentSymbol(BaseModel): - name: str - containerName: Optional[str] = None - kind: int - location: RangeInFile - - -class FoldingRange(BaseModel): - range: Range - kind: Optional[Literal["comment", "imports", "region"]] = None - - -class ContinueLSPClient(BaseModel): - workspace_dir: str - - lsp_client: LSPClient - lsp_thread: Optional[threading.Thread] = None - - @property - def ready(self): - if self.lsp_client is None: - return False - return self.lsp_client.ready - - class Config: - arbitrary_types_allowed = True - - def dict(self, **kwargs): - original_dict = super().dict(**kwargs) - original_dict.pop("lsp_client", None) - return original_dict - - async def start(self): - self.lsp_thread = await start_language_server() - self.lsp_client = LSPClient("localhost", PORT, [self.workspace_dir]) - await self.lsp_client.connect() - await self.lsp_client.initialize() - - async def stop(self): - await self.lsp_client.close() - if self.lsp_thread: - self.lsp_thread.join() - - def location_to_range_in_file(self, location): - return RangeInFile( - filepath=uri_to_filepath(location["uri"]), - range=Range.from_shorthand( - location["range"]["start"]["line"], - location["range"]["start"]["character"], - location["range"]["end"]["line"], - location["range"]["end"]["character"], - ), - ) - - async def goto_definition( - self, position: Position, filename: str - ) -> List[RangeInFile]: - response = await self.lsp_client.goto_definition( - filename, - position, - ) - return [self.location_to_range_in_file(x) for x in response] - - async def find_references( - self, position: Position, filename: str, include_declaration: bool = False - ) -> List[RangeInFile]: - response = await self.lsp_client.find_references( - filename, - position, - include_declaration=include_declaration, - ) - return [self.location_to_range_in_file(x) for x in response["result"]] - - async def document_symbol(self, filepath: str) -> List: - response = await self.lsp_client.document_symbol(filepath) - return [ - DocumentSymbol( - name=x["name"], - containerName=x["containerName"], - kind=x["kind"], - location=self.location_to_range_in_file(x["location"]), - ) - for x in response["result"] - ] - - async def folding_range(self, filepath: str) -> List[FoldingRange]: - response = await self.lsp_client.folding_range(filepath) - - return [ - FoldingRange( - range=Range.from_shorthand( - x["startLine"], - x.get("startCharacter", 0), - x["endLine"] if "endCharacter" in x else x["endLine"] + 1, - x.get("endCharacter", 0), - ), - kind=x.get("kind"), - ) - for x in response - ] - - async def get_enclosing_folding_range_of_position( - self, position: Position, filepath: str - ) -> Optional[FoldingRange]: - ranges = await self.folding_range(filepath) - - max_start_position = Position(line=0, character=0) - max_range = None - for r in ranges: - if r.range.contains(position): - if r.range.start > max_start_position: - max_start_position = r.range.start - max_range = r - - return max_range - - async def get_enclosing_folding_range( - self, range_in_file: RangeInFile - ) -> Optional[FoldingRange]: - ranges = await self.folding_range(range_in_file.filepath) - - max_start_position = Position(line=0, character=0) - max_range = None - for r in ranges: - if r.range.contains(range_in_file.range.start) and r.range.contains( - range_in_file.range.end - ): - if r.range.start > max_start_position: - max_start_position = r.range.start - max_range = r - - return max_range diff --git a/archive/server/continuedev/core/main.py b/archive/server/continuedev/core/main.py deleted file mode 100644 index ecfaa9b19..000000000 --- a/archive/server/continuedev/core/main.py +++ /dev/null @@ -1,447 +0,0 @@ -import json -from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Union, cast - -from pydantic import BaseModel, Field, validator -from pydantic.schema import schema - -from ..models.main import ContinueBaseModel -from .observation import Observation - -ChatMessageRole = Literal["assistant", "user", "system", "function"] - - -class FunctionCall(ContinueBaseModel): - name: str - arguments: str - - -class ChatMessage(ContinueBaseModel): - role: ChatMessageRole - content: str = "" - name: Optional[str] = None - # A summary for pruning chat context to fit context window. Often the Step name. - summary: str = Field(default=None, title="Summary") - function_call: Optional[FunctionCall] = None - - @validator("summary", pre=True, always=True) - def summary_is_content(cls, summary, values): - if summary is None: - return values.get("content", "") - return summary - - def to_dict(self, with_functions: bool = False) -> Dict[str, str]: - d = self.dict() - del d["summary"] - if d["function_call"] is not None: - d["function_call"]["name"] = d["function_call"]["name"].replace(" ", "") - - if d["content"] is None: - d["content"] = "" - for key, value in list(d.items()): - if value is None: - del d[key] - - if not with_functions: - if d["role"] == "function": - d["role"] = "assistant" - if "name" in d: - del d["name"] - if "function_call" in d: - del d["function_call"] - return d - - -def resolve_refs(schema_data): - def traverse(obj): - if isinstance(obj, dict): - if "$ref" in obj: - ref = obj["$ref"] - parts = ref.split("/") - ref_obj = schema_data - for part in parts[1:]: - ref_obj = ref_obj[part] - return traverse(ref_obj) - else: - for key, value in obj.items(): - obj[key] = traverse(value) - elif isinstance(obj, list): - for i in range(len(obj)): - obj[i] = traverse(obj[i]) - return obj - - return traverse(schema_data) - - -unincluded_parameters = [ - "system_message", - "chat_context", - "manage_own_chat_context", - "hide", - "name", - "description", -] - - -def step_to_json_schema(step) -> Dict[str, Any]: - pydantic_class = step.__class__ - schema_data = schema([pydantic_class]) - resolved_schema = cast(Dict[str, Any], resolve_refs(schema_data)) - parameters = resolved_schema["definitions"][pydantic_class.__name__] - for parameter in unincluded_parameters: - if parameter in parameters["properties"]: - del parameters["properties"][parameter] - return { - "name": step.name.replace(" ", ""), - "description": step.description or "", - "parameters": parameters, - } - - -def step_to_fn_call_arguments(step: "Step") -> str: - args = step.dict() - for parameter in unincluded_parameters: - if parameter in args: - del args[parameter] - return json.dumps(args) - - -class ContinueError(BaseModel): - title: str - message: str - - -class SetStep(BaseModel): - step_type: Optional[str] = None - name: Optional[str] = None - description: Optional[str] = None - - params: Optional[Dict[str, Any]] = None - - hide: Optional[bool] = None - depth: Optional[int] = None - - error: Optional[ContinueError] = None - observations: Optional[List[Observation]] = None - logs: Optional[List[str]] = None - - def dict(self, *args, **kwargs): - kwargs["exclude_none"] = True - return super().dict(*args, **kwargs) - - -class DeltaStep(BaseModel): - name: Optional[str] = None - description: Optional[str] = None - - observations: Optional[List[Observation]] = None - logs: Optional[List[str]] = None - - def dict(self, *args, **kwargs): - kwargs["exclude_none"] = True - return super().dict(*args, **kwargs) - - -class StepDescription(BaseModel): - step_type: str - name: str - description: str - - params: Dict[str, Any] - - hide: bool - depth: int - - error: Optional[ContinueError] = None - observations: List[Observation] = [] - logs: List[str] = [] - - def update(self, update: "UpdateStep"): - if isinstance(update, DeltaStep): - for key, value in update.dict(exclude_none=True).items(): - setattr(self, key, getattr(self, key) + value) - elif isinstance(update, SetStep): - for key, value in update.dict(exclude_none=True).items(): - setattr(self, key, value) - - @staticmethod - def from_empty() -> "StepDescription": - return StepDescription( - step_type="EmptyStep", - name="", - description="", - params={}, - hide=True, - depth=0, - error=None, - observations=[], - logs=[], - ) - - -class SessionUpdate(BaseModel): - index: int - update: "UpdateStep" - stop: Optional[bool] = None - - class Config: - smart_union = True - - def dict(self, *args, **kwargs): - d = super().dict(*args, **kwargs) - # Because the front-end doesn't see the Model type - d["delta"] = isinstance(self.update, DeltaStep) - return d - - -UpdateStep = Union[DeltaStep, SetStep, SessionUpdate] - -SessionUpdate.update_forward_refs() - -StepGenerator = AsyncGenerator[Union[str, UpdateStep, Observation], None] -AutopilotGeneratorOutput = Union[SessionUpdate, StepDescription] -AutopilotGenerator = AsyncGenerator[AutopilotGeneratorOutput, None] - - -class SlashCommandDescription(ContinueBaseModel): - name: str - description: str - - -class ContextItemId(BaseModel): - """ - A ContextItemId is a unique identifier for a ContextItem. - """ - - provider_title: str - item_id: str - - @validator("provider_title", "item_id") - def must_be_valid_id(cls, v): - import re - - if not re.match(r"^[0-9a-zA-Z_-]*$", v): - raise ValueError( - "Both provider_title and item_id can only include characters 0-9, a-z, A-Z, -, and _" - ) - return v - - def to_string(self) -> str: - return f"{self.provider_title}-{self.item_id}" - - def __eq__(self, other): - return ( - self.provider_title == other.provider_title - and self.item_id == other.item_id - ) - - @staticmethod - def from_string(string: str) -> "ContextItemId": - provider_title, *rest = string.split("-") - item_id = "-".join(rest) - return ContextItemId(provider_title=provider_title, item_id=item_id) - - -class ContextItemDescription(BaseModel): - """ - A ContextItemDescription is a description of a ContextItem that is displayed to the user when they type '@'. - - The id can be used to retrieve the ContextItem from the ContextManager. - """ - - name: str - description: str - id: ContextItemId - - -class ContextItem(BaseModel): - """ - A ContextItem is a single item that is stored in the ContextManager. - """ - - description: ContextItemDescription - content: str - - @validator("content", pre=True) - def content_must_be_string(cls, v): - if v is None: - return "" - return v - - editing: bool = False - editable: bool = False - - -class SessionInfo(ContinueBaseModel): - session_id: str - title: str - date_created: str - workspace_directory: Optional[str] = None - - -class ContinueConfig(ContinueBaseModel): - system_message: Optional[str] - temperature: Optional[float] - - class Config: - extra = "allow" - - def dict(self, **kwargs): - original_dict = super().dict(**kwargs) - original_dict.pop("policy", None) - return original_dict - - -class ContextProviderDescription(BaseModel): - title: str - display_title: str - description: str - dynamic: bool - requires_query: bool - - -class SessionState(ContinueBaseModel): - """Full session history and important state needed for autopilot to Continue""" - - history: List[StepDescription] - context_items: List[ContextItem] - # future: List = [] - - @staticmethod - def from_empty(): - return SessionState(history=[], context_items=[]) - - @classmethod - def parse_obj(cls, obj: Any): - # Safety net against the client sending malformed data - valid_steps = [] - for step in obj["history"]: - try: - StepDescription.parse_obj(step) - valid_steps.append(step) - except Exception: - valid_steps.append(StepDescription.from_empty()) - - obj["history"] = valid_steps - - return super().parse_obj(obj) - - -class ContinueSDK: - async def run_step(self, step: "Step"): - ... - - -class Models: - ... - - -class Policy(ContinueBaseModel): - """A rule that determines which step to take next""" - - # Note that history is mutable, kinda sus - def next( - self, config: ContinueConfig, session_state: SessionState - ) -> Optional["Step"]: - raise NotImplementedError - - -class Step(ContinueBaseModel): - name: str = Field(default=None, title="Name") - hide: bool = False - description: str = "" - - class_name: str = "Step" - - @validator("class_name", pre=True, always=True) - def class_name_is_class_name(cls, class_name): - return cls.__name__ - - system_message: Union[str, None] = None - chat_context: List[ChatMessage] = [] - manage_own_chat_context: bool = False - - class Config: - copy_on_model_validation = False - - async def describe(self, models: Models) -> str: - if self.description is not None: - return self.description - return "Running step: " + self.name - - def on_stop(self, sdk: ContinueSDK) -> Optional[StepGenerator]: - return None - - def dict(self, *args, **kwargs): - d = super().dict(*args, **kwargs) - # Make sure description is always a string - d["description"] = self.description or "" - return d - - @validator("name", pre=True, always=True) - def name_is_class_name(cls, name): - if name is None: - return cls.__name__ - return name - - async def run(self, sdk: ContinueSDK) -> StepGenerator: - raise NotImplementedError - - async def __call__(self, sdk: ContinueSDK) -> StepGenerator: - return await self.run(sdk) - - def __rshift__(self, other: "Step"): - steps = [] - if isinstance(self, SequentialStep): - steps = self.steps - else: - steps.append(self) - if isinstance(other, SequentialStep): - steps += other.steps - else: - steps.append(other) - return SequentialStep(steps=steps) - - -class SequentialStep(Step): - steps: List[Step] - hide: bool = True - - async def run(self, sdk: ContinueSDK): - for step in self.steps: - await sdk.run_step(step) - - -class ValidatorObservation(Observation): - passed: bool - observation: Observation - - -class Validator(Step): - def run(self, sdk: ContinueSDK) -> ValidatorObservation: - raise NotImplementedError - - -class Context: - key_value: Dict[str, Any] = {} - - def set(self, key: str, value: Any): - self.key_value[key] = value - - def get(self, key: str) -> Any: - return self.key_value.get(key, None) - - -class ContinueCustomException(Exception): - title: str - message: str - with_step: Union[Step, None] - - def __init__( - self, - message: str, - title: str = "Error while running step:", - with_step: Union[Step, None] = None, - ): - self.message = message - self.title = title - self.with_step = with_step diff --git a/archive/server/continuedev/core/models.py b/archive/server/continuedev/core/models.py deleted file mode 100644 index fedbf66f7..000000000 --- a/archive/server/continuedev/core/models.py +++ /dev/null @@ -1,147 +0,0 @@ -import uuid -from typing import Any, Callable, Dict, List, Optional, Type, Union - -from pydantic import BaseModel, validator - -from ..libs.llm.anthropic import AnthropicLLM -from ..libs.llm.base import LLM -from ..libs.llm.ggml import GGML -from ..libs.llm.google_palm_api import GooglePaLMAPI -from ..libs.llm.hf_inference_api import HuggingFaceInferenceAPI -from ..libs.llm.hf_tgi import HuggingFaceTGI -from ..libs.llm.llamacpp import LlamaCpp -from ..libs.llm.llamafile import Llamafile -from ..libs.llm.lmstudio import LMStudio -from ..libs.llm.ollama import Ollama -from ..libs.llm.openai import OpenAI -from ..libs.llm.openai_free_trial import OpenAIFreeTrial -from ..libs.llm.replicate import ReplicateLLM -from ..libs.llm.text_gen_webui import TextGenWebUI -from ..libs.llm.together import TogetherLLM - - -class ContinueSDK(BaseModel): - pass - - -ALL_MODEL_ROLES = [ - "default", - "summarize", - "edit", - "chat", -] - -MODEL_CLASSES: Dict[str, Type[LLM]] = { - cls.__name__: cls - for cls in [ - OpenAI, - OpenAIFreeTrial, - GGML, - TogetherLLM, - AnthropicLLM, - ReplicateLLM, - Ollama, - LlamaCpp, - HuggingFaceInferenceAPI, - HuggingFaceTGI, - GooglePaLMAPI, - TextGenWebUI, - LMStudio, - Llamafile, - ] -} - -MODEL_MODULE_NAMES = { - "OpenAI": "openai", - "OpenAIFreeTrial": "openai_free_trial", - "GGML": "ggml", - "TogetherLLM": "together", - "AnthropicLLM": "anthropic", - "ReplicateLLM": "replicate", - "Ollama": "ollama", - "LlamaCpp": "llamacpp", - "HuggingFaceInferenceAPI": "hf_inference_api", - "HuggingFaceTGI": "hf_tgi", - "GooglePaLMAPI": "google_palm_api", - "TextGenWebUI": "text_gen_webui", - "LMStudio": "lmstudio", - "Llamafile": "llamafile", -} - - -class Models(BaseModel): - """Main class that holds the current model configuration""" - - default: Union[Any, LLM] - summarize: Union[Any, LLM] - edit: Union[Any, LLM] - chat: Union[Any, LLM] - - saved: List[Union[Any, LLM]] = [] - - temperature: Optional[float] = None - system_message: Optional[str] = None - - @validator( - "summarize", - "edit", - "chat", - pre=True, - always=True, - ) - def roles_not_none(cls, v, values): - if v is None: - return values["default"] - return v - - def dict(self, **kwargs): - original_dict = super().dict(**kwargs) - return original_dict - - @property - def all_models(self) -> List[LLM]: - models = [getattr(self, role) for role in ALL_MODEL_ROLES] - return [model for model in models if model is not None] - - def set_main_config_params( - self, system_msg: Optional[str], temperature: Optional[float] - ): - self.system_message = system_msg - self.temperature = temperature - for model in self.all_models: - model.set_main_config_params(system_msg, temperature) - - def start( - self, - unique_id: str, - system_message: Optional[str], - temperature: Optional[float], - llm_request_hook: Optional[Callable[[str, str], Any]] = None, - ): - """Start each of the LLMs, or fall back to default""" - for model in self.saved + self.all_models: - model.start(unique_id) - model.write_log = self.write_log - model.llm_request_hook = llm_request_hook - - self.set_main_config_params(system_message, temperature) - - async def stop(self): - """Stop each LLM (if it's not the default, which is shared)""" - for model in self.all_models: - await model.stop() - - _loggers = {} - - async def write_log(self, msg): - for logger in self._loggers.values(): - await logger(msg) - - def add_logger(self, logger: Callable[[str], Any]) -> str: - logger_id = uuid.uuid4().hex - self._loggers[logger_id] = logger - return logger_id - - def remove_logger(self, logger_id: str): - if logger_id in self._loggers: - del self._loggers[logger_id] diff --git a/archive/server/continuedev/core/observation.py b/archive/server/continuedev/core/observation.py deleted file mode 100644 index 8a5e454eb..000000000 --- a/archive/server/continuedev/core/observation.py +++ /dev/null @@ -1,41 +0,0 @@ -from pydantic import BaseModel, validator - -from ..models.main import Traceback - - -class Observation(BaseModel): - pass - - -class TracebackObservation(Observation): - traceback: Traceback - - -class ValidatorObservation(Observation): - passed: bool - - -class UserInputObservation(Observation): - user_input: str - - -class DictObservation(Observation): - values: dict - - def __getitem__(self, key): - return self.values[key] - - -class TextObservation(Observation): - text: str - - @validator("text", pre=True, always=True) - def text_not_none(cls, v): - if v is None: - return "" - return v - - -class InternalErrorObservation(Observation): - title: str - error: str diff --git a/archive/server/continuedev/core/sdk.py b/archive/server/continuedev/core/sdk.py deleted file mode 100644 index 426336412..000000000 --- a/archive/server/continuedev/core/sdk.py +++ /dev/null @@ -1,277 +0,0 @@ -import asyncio -import os -from abc import ABC -from typing import List, Optional, Union - -from ..models.filesystem import RangeInFile -from ..models.filesystem_edit import ( - AddDirectory, - AddFile, - DeleteDirectory, - DeleteFile, - FileEdit, - FileSystemEdit, -) -from ..models.main import Range -from ..plugins.context_providers.highlighted_code import HighlightedCodeContextProvider -from ..server.protocols.gui_protocol import AbstractGUIProtocolServer -from ..server.protocols.ide_protocol import AbstractIdeProtocolServer -from .abstract_sdk import AbstractContinueSDK -from .config import ContinueConfig -from .context import ContextManager -from .lsp import ContinueLSPClient -from .main import ( - ChatMessage, - Context, - ContextItem, - ContinueCustomException, - SessionState, - Step, - StepDescription, -) -from .models import Models -from .steps import ( - DefaultModelEditCodeStep, - FileSystemEditStep, - RangeInFileWithContents, - ShellCommandsStep, -) - - -class Autopilot(ABC): - session_state: SessionState - ide: AbstractIdeProtocolServer - gui: AbstractGUIProtocolServer - config: ContinueConfig - context_manager: ContextManager - - context: Context = Context() - - async def run_step(self, step: Step): - ... - - -class ContinueSDK(AbstractContinueSDK): - """The SDK provided as parameters to a step""" - - ide: AbstractIdeProtocolServer - gui: AbstractGUIProtocolServer - config: ContinueConfig - models: Models - - lsp: Optional[ContinueLSPClient] = None - context: Context = Context() - - __autopilot: Autopilot - - def __init__( - self, - config: ContinueConfig, - ide: AbstractIdeProtocolServer, - gui: AbstractGUIProtocolServer, - autopilot: Autopilot, - models: Models, - ): - self.ide = ide - self.gui = gui - self.config = config - self.models = models - self.__autopilot = autopilot - - @property - def history(self) -> List[StepDescription]: - return self.__autopilot.session_state.history - - @property - def context_items(self) -> List[ContextItem]: - return self.__autopilot.session_state.context_items - - async def _ensure_absolute_path(self, path: str) -> str: - if os.path.isabs(path): - return path - - # Else if in workspace - workspace_path = os.path.join(self.ide.workspace_directory, path) - if os.path.exists(workspace_path): - return workspace_path - else: - # Check if it matches any of the open files, then use that absolute path - open_files = await self.ide.getOpenFiles() - for open_file in open_files: - if os.path.basename(open_file) == os.path.basename(path): - return open_file - raise Exception(f"Path {path} does not exist") - - async def run_step(self, step: Step): - await self.__autopilot.run_step(step) - - async def apply_filesystem_edit( - self, - edit: FileSystemEdit, - name: str = "Filesystem Edit", - description: str = "Filesystem Edit", - ): - return await self.run_step( - FileSystemEditStep(edit=edit, description=description, name=name) - ) - - async def run( - self, - commands: Union[List[str], str], - cwd: Optional[str] = None, - name: str = "Run Command", - description: str = "Run Command", - handle_error: bool = True, - ): - commands = commands if isinstance(commands, List) else [commands] - await self.run_step( - ShellCommandsStep( - cmds=commands, - cwd=cwd, - description=description, - handle_error=handle_error, - name=name, - ) - ) # TODO: Return the output - - async def edit_file( - self, - filename: str, - prompt: str, - name: str = "Edit File", - description: str = "", - range: Optional[Range] = None, - ): - filepath = await self._ensure_absolute_path(filename) - - await self.ide.setFileOpen(filepath) - contents = await self.ide.readFile(filepath) - await self.run_step( - DefaultModelEditCodeStep( - range_in_files=[ - RangeInFile(filepath=filepath, range=range) - if range is not None - else RangeInFile.from_entire_file(filepath, contents) - ], - user_input=prompt, - description=description, - name=name, - ) - ) - - async def append_to_file(self, filename: str, content: str): - filepath = await self._ensure_absolute_path(filename) - previous_content = await self.ide.readFile(filepath) - file_edit = FileEdit.from_append(filepath, previous_content, content) - await self.ide.applyFileSystemEdit(file_edit) - - async def add_file(self, filename: str, content: Union[str, None]): - filepath = await self._ensure_absolute_path(filename) - dir_name = os.path.dirname(filepath) - os.makedirs(dir_name, exist_ok=True) - return await self.run_step( - FileSystemEditStep(edit=AddFile(filepath=filepath, content=content or "")) - ) - - async def delete_file(self, filename: str): - filename = await self._ensure_absolute_path(filename) - return await self.run_step( - FileSystemEditStep(edit=DeleteFile(filepath=filename)) - ) - - async def add_directory(self, path: str): - path = await self._ensure_absolute_path(path) - return await self.run_step(FileSystemEditStep(edit=AddDirectory(path=path))) - - async def delete_directory(self, path: str): - path = await self._ensure_absolute_path(path) - return await self.run_step(FileSystemEditStep(edit=DeleteDirectory(path=path))) - - async def get_code_context( - self, only_editing: bool = False - ) -> List[RangeInFileWithContents]: - editing = filter( - lambda x: x.editable and (x.editing or not only_editing), self.context_items - ) - return await asyncio.gather( - *[ - HighlightedCodeContextProvider.get_range_in_file_with_contents( - self.ide, item - ) - for item in editing - ] - ) - - async def add_context_item(self, item: ContextItem): - index = len(self.__autopilot.session_state.history) - 1 - while index > 0: - if ( - self.__autopilot.session_state.history[index].step_type - == "UserInputStep" - ): - break - index -= 1 - - await self.add_context_item_at_index(item, index) - - async def add_context_item_at_index(self, item: ContextItem, index: int): - context_items = self.__autopilot.session_state.history[index].params.get( - "context_items", [] - ) - context_items.append(item.dict()) - self.__autopilot.session_state.history[index].params[ - "context_items" - ] = context_items - await self.gui.add_context_item_at_index(item, index) - - def set_loading_message(self, message: str): - # self.__autopilot.set_loading_message(message) - raise NotImplementedError() - - def raise_exception( - self, message: str, title: str, with_step: Union[Step, None] = None - ): - raise ContinueCustomException(message, title, with_step) - - async def get_chat_context(self) -> List[ChatMessage]: - msgs = [] - - for step in filter(lambda x: x.hide is False, self.history): - role = "assistant" - if step.step_type == "UserInputStep": - role = "user" - msgs.extend( - await self.__autopilot.context_manager.get_chat_messages( - [ContextItem(**itm) for itm in step.params["context_items"]] - ) - ) - - msgs.append( - ChatMessage( - role=role, - name=step.step_type, - content=step.description or f"Ran function {step.name}", - summary=f"Called function {step.name}", - ) - ) - - ctx_msgs = await self.__autopilot.context_manager.get_chat_messages( - self.context_items - ) - for ctx_msg in ctx_msgs: - # Add as second-to-last message - msgs.insert(-1, ctx_msg) - - return msgs - - async def get_context_item_chat_messages( - self, exclude: Optional[str] = None - ) -> List[ChatMessage]: - return await self.__autopilot.context_manager.get_chat_messages( - # list( - # filter( - # lambda x: x.description, - self.context_items - # ) - # ) - ) diff --git a/archive/server/continuedev/core/steps.py b/archive/server/continuedev/core/steps.py deleted file mode 100644 index 71181f652..000000000 --- a/archive/server/continuedev/core/steps.py +++ /dev/null @@ -1,873 +0,0 @@ -# These steps are depended upon by ContinueSDK -import difflib -import subprocess -import time -from textwrap import dedent -from typing import Any, AsyncGenerator, Dict, List, Optional, Union - -from pydantic import Field - -from ..libs.llm.base import LLM -from ..libs.llm.openai_free_trial import OpenAIFreeTrial -from ..libs.util.count_tokens import DEFAULT_MAX_TOKENS -from ..libs.util.devdata import dev_data_logger -from ..libs.util.strings import ( - dedent_and_get_common_whitespace, - remove_quotes_and_escapes, -) -from ..libs.util.telemetry import posthog_logger -from ..libs.util.templating import render_prompt_template -from ..models.filesystem import FileSystem, RangeInFile, RangeInFileWithContents -from ..models.filesystem_edit import EditDiff, FileEditWithFullContents, FileSystemEdit -from .abstract_sdk import AbstractContinueSDK -from .main import ( - ChatMessage, - ContextItem, - ContinueCustomException, - DeltaStep, - SessionUpdate, - SetStep, - Step, -) -from .observation import TextObservation, UserInputObservation - - -class Models: - default: LLM - summarize: LLM = Field(default=None) - edit: LLM = Field(default=None) - chat: LLM = Field(default=None) - - -class ReversibleStep(Step): - async def reverse(self, sdk: AbstractContinueSDK): - raise NotImplementedError - - -class MessageStep(Step): - name: str = "Message" - message: str - - async def describe(self, models: Models): - return self.message - - async def run(self, sdk: AbstractContinueSDK): - yield TextObservation(text=self.message) - - -class DisplayErrorStep(Step): - name: str = "Error in the Continue server" - - title: str = "Error in the Continue server" - message: str = "There was an error in the Continue server." - - @staticmethod - def from_exception(e: Exception) -> "DisplayErrorStep": - if isinstance(e, ContinueCustomException): - return DisplayErrorStep(title=e.title, message=e.message, name=e.title) - - return DisplayErrorStep(message=str(e)) - - class Config: - arbitrary_types_allowed = True - - async def describe(self, models: Models): - return self.message - - async def run(self, sdk: AbstractContinueSDK): - raise ContinueCustomException(message=self.message, title=self.title) - - -class FileSystemEditStep(ReversibleStep): - edit: FileSystemEdit - _diff: Union[EditDiff, None] = None - - hide: bool = True - - async def run(self, sdk: "AbstractContinueSDK"): - self._diff = await sdk.ide.applyFileSystemEdit(self.edit) - - async def reverse(self, sdk: "AbstractContinueSDK"): - if self._diff: - await sdk.ide.applyFileSystemEdit(self._diff.backward) - - -def output_contains_error(output: str) -> bool: - return "Traceback" in output or "SyntaxError" in output - - -AI_ASSISTED_STRING = "(✨ AI-Assisted ✨)" - - -class ShellCommandsStep(Step): - cmds: List[str] - cwd: Union[str, None] = None - name: str = "Run Shell Commands" - handle_error: bool = True - - _err_text: Union[str, None] = None - - async def describe(self, models: Models) -> str: - if self._err_text is not None: - return f"Error when running shell commands:\n```\n{self._err_text}\n```" - - cmds_str = "\n".join(self.cmds) - return await models.summarize.complete( - f"{cmds_str}\n\nSummarize what was done in these shell commands, using markdown bullet points:" - ) - - async def run(self, sdk: AbstractContinueSDK): - process = subprocess.Popen( - "/bin/bash", - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - cwd=self.cwd or sdk.ide.workspace_directory, - ) - - stdin_input = "\n".join(self.cmds) - out, err_bytes = process.communicate(stdin_input.encode()) - err = err_bytes.decode() - - # If it fails, return the error - if err is not None and err != "": - self._err_text = err - return TextObservation(text=err) - - -class DefaultModelEditCodeStep(Step): - user_input: str - model: Optional[LLM] = None - range_in_files: List[RangeInFile] - name: str = "Editing Code" - hide = False - description: str = "" - _prompt: str = dedent( - """\ - Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. - - Example: - - - class Database: - def __init__(self): - self._data = {{}} - - def get(self, key): - return self._data[key] - - - - def set(self, key, value): - self._data[key] = value - - - - def clear_all(): - self._data = {{}} - - - Raise an error if the key already exists. - - - def set(self, key, value): - if key in self._data: - raise KeyError(f"Key {{key}} already exists") - self._data[key] = value - - - Main task: - """ - ) - _previous_contents: str = "" - _new_contents: str = "" - _prompt_and_completion: str = "" - - summary_prompt: str = "Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:" - - async def get_prompt_parts( - self, - rif: RangeInFileWithContents, - sdk: AbstractContinueSDK, - full_file_contents: str, - ): - # We don't know here all of the functions being passed in. - # We care because if this prompt itself goes over the limit, then the entire message will have to be cut from the completion. - # Overflow won't happen, but prune_chat_messages in count_tokens.py will cut out this whole thing, instead of us cutting out only as many lines as we need. - - model_to_use = self.model or sdk.models.edit - max_tokens = int(model_to_use.context_length / 2) - - TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = 1200 - if ( - model_to_use.count_tokens(rif.contents) - > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE - ): - self.description += "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**" - - # At this point, we also increase the max_tokens parameter so it doesn't stop in the middle of generation - # Increase max_tokens to be double the size of the range - # But don't exceed twice default max tokens - max_tokens = int( - min(model_to_use.count_tokens(rif.contents), DEFAULT_MAX_TOKENS) * 2.5 - ) - - BUFFER_FOR_FUNCTIONS = 400 - total_tokens = ( - model_to_use.count_tokens( - full_file_contents + self._prompt + self.user_input - ) - + BUFFER_FOR_FUNCTIONS - + max_tokens - ) - - # If using 3.5 and overflows, upgrade to 3.5.16k - if ( - model_to_use.model == "gpt-3.5-turbo" - and model_to_use.__class__.__name__ == "OpenAI" - ): - if total_tokens > model_to_use.context_length: - model_to_use = OpenAIFreeTrial(model="gpt-3.5-turbo-0613") - - # Remove tokens from the end first, and then the start to clear space - # This part finds the start and end lines - full_file_contents_lst = full_file_contents.split("\n") - max_start_line = rif.range.start.line - min_end_line = rif.range.end.line - cur_start_line = 0 - cur_end_line = len(full_file_contents_lst) - 1 - - if total_tokens > model_to_use.context_length: - while cur_end_line > min_end_line: - total_tokens -= model_to_use.count_tokens( - full_file_contents_lst[cur_end_line] - ) - cur_end_line -= 1 - if total_tokens < model_to_use.context_length: - break - - if total_tokens > model_to_use.context_length: - while cur_start_line < max_start_line: - cur_start_line += 1 - total_tokens -= model_to_use.count_tokens( - full_file_contents_lst[cur_start_line] - ) - if total_tokens < model_to_use.context_length: - break - - # Now use the found start/end lines to get the prefix and suffix strings - file_prefix = "\n".join(full_file_contents_lst[cur_start_line:max_start_line]) - file_suffix = "\n".join(full_file_contents_lst[min_end_line : cur_end_line - 1]) - - # Move any surrounding blank line in rif.contents to the prefix/suffix - # TODO: Keep track of start line of the range, because it's needed below for offset stuff - if len(rif.contents) > 0: - lines = rif.contents.splitlines(keepends=True) - first_line = lines[0] if lines else None - while first_line and first_line.strip() == "": - file_prefix += first_line - rif.contents = rif.contents[len(first_line) :] - lines = rif.contents.splitlines(keepends=True) - first_line = lines[0] if lines else None - - last_line = lines[-1] if lines else None - while last_line and last_line.strip() == "": - file_suffix = last_line + file_suffix - rif.contents = rif.contents[: len(rif.contents) - len(last_line)] - lines = rif.contents.splitlines(keepends=True) - last_line = lines[-1] if lines else None - - while rif.contents.startswith("\n"): - file_prefix += "\n" - rif.contents = rif.contents[1:] - while rif.contents.endswith("\n"): - file_suffix = "\n" + file_suffix - rif.contents = rif.contents[:-1] - - return file_prefix, rif.contents, file_suffix, model_to_use, max_tokens - - def compile_prompt( - self, - file_prefix: str, - contents: str, - file_suffix: str, - sdk: AbstractContinueSDK, - ) -> str: - if contents.strip() == "": - # Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file - prompt = dedent( - f"""\ - -{file_prefix} - - - -{file_suffix} - - -{self.user_input} - - -Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:""" - ) - return prompt - - prompt = self._prompt - if file_prefix.strip() != "": - prompt += dedent( - f""" - -{file_prefix} -""" - ) - prompt += dedent( - f""" - -{contents} -""" - ) - if file_suffix.strip() != "": - prompt += dedent( - f""" - -{file_suffix} -""" - ) - prompt += dedent( - f""" - -{self.user_input} - - -""" - ) - - return prompt - - def is_end_line(self, line: str) -> bool: - return ( - "" in line - or "" in line - or "[/CODE]" in line - ) - - def line_to_be_ignored(self, line: str, is_first_line: bool = False) -> bool: - return ( - "```" in line - or "" in line - or "" in line - or "" in line - or "" in line - or "" in line - or "" in line - or "" in line - or "" in line - ) - - async def stream_rif( - self, rif: RangeInFileWithContents, sdk: AbstractContinueSDK - ) -> AsyncGenerator[SetStep, None]: - await sdk.ide.saveFile(rif.filepath) - full_file_contents = await sdk.ide.readFile(rif.filepath) - - ( - file_prefix, - contents, - file_suffix, - model_to_use, - max_tokens, - ) = await self.get_prompt_parts(rif, sdk, full_file_contents) - contents, common_whitespace = dedent_and_get_common_whitespace(contents) - prompt = self.compile_prompt(file_prefix, contents, file_suffix, sdk) - full_file_contents_lines = full_file_contents.split("\n") - - lines_to_display = [] - - async def sendDiffUpdate( - lines: List[str], sdk: AbstractContinueSDK, final: bool = False - ): - nonlocal full_file_contents_lines, rif, lines_to_display - - completion = "\n".join(lines) - - full_prefix_lines = full_file_contents_lines[: rif.range.start.line] - full_suffix_lines = full_file_contents_lines[rif.range.end.line :] - - # Don't do this at the very end, just show the inserted code - if final: - lines_to_display = [] - - # Only recalculate at every new-line, because this is sort of expensive - elif completion.endswith("\n"): - contents_lines = rif.contents.split("\n") - rewritten_lines = 0 - for line in lines: - for i in range(rewritten_lines, len(contents_lines)): - if ( - difflib.SequenceMatcher( - None, line, contents_lines[i] - ).ratio() - > 0.7 - and contents_lines[i].strip() != "" - ): - rewritten_lines = i + 1 - break - lines_to_display = contents_lines[rewritten_lines:] - - new_file_contents = ( - "\n".join(full_prefix_lines) - + "\n" - + completion - + "\n" - + ( - "\n".join(lines_to_display) + "\n" - if len(lines_to_display) > 0 - else "" - ) - + "\n".join(full_suffix_lines) - ) - - step_index = len(sdk.history) - 1 - - await sdk.ide.showDiff(rif.filepath, new_file_contents, step_index) - - # Important state variables - # ------------------------- - original_lines = [] if rif.contents == "" else rif.contents.split("\n") - # In the actual file, taking into account block offset - current_line_in_file = rif.range.start.line - current_block_lines = [] - original_lines_below_previous_blocks = original_lines - # The start of the current block in file, taking into account block offset - current_block_start = -1 - offset_from_blocks = 0 - - # Don't end the block until you've matched N simultaneous lines - # This helps avoid many tiny blocks - LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2 - # If a line has been matched at the end of the block, this is its index within original_lines_below_previous_blocks - # Except we are keeping track of multiple potentialities, so it's a list - # We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one - # This is a tuple of (index_of_last_matched_line, number_of_lines_matched) - indices_of_last_matched_lines = [] - - async def handle_generated_line(line: str): - nonlocal current_block_start, current_line_in_file, original_lines, original_lines_below_previous_blocks, current_block_lines, indices_of_last_matched_lines, LINES_TO_MATCH_BEFORE_ENDING_BLOCK, offset_from_blocks - - if len(current_block_lines) == 0: - # Set this as the start of the next block - current_block_start = ( - rif.range.start.line - + len(original_lines) - - len(original_lines_below_previous_blocks) - + offset_from_blocks - ) - if ( - len(original_lines_below_previous_blocks) > 0 - and line == original_lines_below_previous_blocks[0] - ): - # Line is equal to the next line in file, move past this line - original_lines_below_previous_blocks = ( - original_lines_below_previous_blocks[1:] - ) - return - - # In a block, and have already matched at least one line - # Check if the next line matches, for each of the candidates - matches_found = [] - first_valid_match = None - for ( - index_of_last_matched_line, - num_lines_matched, - ) in indices_of_last_matched_lines: - if ( - index_of_last_matched_line + 1 - < len(original_lines_below_previous_blocks) - and line - == original_lines_below_previous_blocks[ - index_of_last_matched_line + 1 - ] - ): - matches_found.append( - (index_of_last_matched_line + 1, num_lines_matched + 1) - ) - if ( - first_valid_match is None - and num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK - ): - first_valid_match = ( - index_of_last_matched_line + 1, - num_lines_matched + 1, - ) - indices_of_last_matched_lines = matches_found - - if first_valid_match is not None: - # We've matched the required number of lines, insert suggestion! - - # We added some lines to the block that were matched (including maybe some blank lines) - # So here we will strip all matching lines from the end of current_block_lines - lines_stripped = [] - index_of_last_line_in_block = first_valid_match[0] - while ( - len(current_block_lines) > 0 - and current_block_lines[-1] - == original_lines_below_previous_blocks[ - index_of_last_line_in_block - 1 - ] - ): - lines_stripped.append(current_block_lines.pop()) - index_of_last_line_in_block -= 1 - - # Reset current block / update variables - current_line_in_file += 1 - offset_from_blocks += len(current_block_lines) - original_lines_below_previous_blocks = ( - original_lines_below_previous_blocks[ - index_of_last_line_in_block + 1 : - ] - ) - current_block_lines = [] - current_block_start = -1 - indices_of_last_matched_lines = [] - - return - - # Always look for new matching candidates - new_matches = [] - for i in range(len(original_lines_below_previous_blocks)): - og_line = original_lines_below_previous_blocks[i] - # TODO: It's a bit sus to be disqualifying empty lines. - # What you ideally do is find ALL matches, and then throw them out as you check the following lines - if og_line == line: # and og_line.strip() != "": - new_matches.append((i, 1)) - indices_of_last_matched_lines += new_matches - - # Make sure they are sorted by index - indices_of_last_matched_lines = sorted( - indices_of_last_matched_lines, key=lambda x: x[0] - ) - - current_block_lines.append(line) - - messages = await sdk.get_chat_context() - # Delete the last user and assistant messages - i = len(messages) - 1 - deleted = 0 - while i >= 0 and deleted < 2: - if messages[i].role == "user" or messages[i].role == "assistant": - messages.pop(i) - deleted += 1 - i -= 1 - messages.append( - ChatMessage(role="user", content=prompt, summary=self.user_input) - ) - - lines_of_prefix_copied = 0 - lines = [] - unfinished_line = "" - completion_lines_covered = 0 - repeating_file_suffix = False - line_below_highlighted_range = file_suffix.lstrip().split("\n")[0] - - # Use custom templates defined by the model - if template := model_to_use.prompt_templates.get("edit"): - rendered = render_prompt_template( - template if isinstance(template, str) else template.prompt, - messages[:-1], - { - "code_to_edit": rif.contents, - "user_input": self.user_input, - "file_prefix": file_prefix, - "file_suffix": file_suffix, - "system_message": model_to_use.system_message - or sdk.config.system_message - or "", - "context_items": "\n\n".join( - list( - map( - lambda x: x.content or "", - await sdk.get_context_item_chat_messages(), - ) - ) - ), - }, - ) - if isinstance(rendered, str): - messages = [ - ChatMessage( - role="user", - content=rendered, - summary=self.user_input, - ) - ] - else: - messages = rendered - - params: Dict[str, Any] = {"prompt": rendered} - if template.__class__.__name__ == "PromptTemplate": - params.update(template.dict(exclude={"prompt"})) - - params.update( - {"max_tokens": min(max_tokens, model_to_use.context_length // 2, 4096)} - ) - generator = model_to_use.stream_complete(**params) - - else: - - async def gen(): - async for chunk in model_to_use.stream_chat( - messages, - temperature=sdk.config.completion_options.temperature, - max_tokens=min(max_tokens, model_to_use.context_length // 2, 4096), - ): - yield chunk.content - - generator = gen() - - posthog_logger.capture_event( - "model_use", - {"model": model_to_use.model, "provider": model_to_use.__class__.__name__}, - ) - dev_data_logger.capture( - "model_use", - {"model": model_to_use.model, "provider": model_to_use.__class__.__name__}, - ) - - try: - last_task_time = time.time() - async for chunk in generator: - yield SetStep( - hide=False - ) # Doing this so that there are breakpoints for cancellation - - # Stop early if it is repeating the file_suffix or the step was deleted - if repeating_file_suffix: - break - - # Accumulate lines - chunk_lines = chunk.split("\n") - chunk_lines[0] = unfinished_line + chunk_lines[0] - if chunk.endswith("\n"): - unfinished_line = "" - chunk_lines.pop() # because this will be an empty string - else: - unfinished_line = chunk_lines.pop() - - # Deal with newly accumulated lines - for i in range(len(chunk_lines)): - # Trailing whitespace doesn't matter - chunk_lines[i] = chunk_lines[i].rstrip() - chunk_lines[i] = common_whitespace + chunk_lines[i] - - # Lines that should signify the end of generation - if self.is_end_line(chunk_lines[i]): - break - # Lines that should be ignored, like the <> tags - elif self.line_to_be_ignored( - chunk_lines[i], completion_lines_covered == 0 - ): - continue # noice - # Check if we are currently just copying the prefix - elif ( - (lines_of_prefix_copied > 0 or completion_lines_covered == 0) - and lines_of_prefix_copied < len(file_prefix.splitlines()) - and chunk_lines[i] - == full_file_contents_lines[lines_of_prefix_copied] - ): - # This is a sketchy way of stopping it from repeating the file_prefix. Is a bug if output happens to have a matching line - lines_of_prefix_copied += 1 - continue # also nice - # Because really short lines might be expected to be repeated, this is only a !heuristic! - # Stop when it starts copying the file_suffix - elif ( - chunk_lines[i].strip() == line_below_highlighted_range.strip() - and len(chunk_lines[i].strip()) > 4 - and not ( - len(original_lines_below_previous_blocks) > 0 - and chunk_lines[i].strip() - == original_lines_below_previous_blocks[0].strip() - ) - ): - repeating_file_suffix = True - break - - lines.append(chunk_lines[i]) - completion_lines_covered += 1 - current_line_in_file += 1 - - # Debounce the diff updates, last in only out for each period - if last_task_time is None or time.time() - last_task_time > 0.15: - last_task_time = time.time() - await sendDiffUpdate( - lines - + [ - common_whitespace - if unfinished_line.startswith("<") - else (common_whitespace + unfinished_line) - ], - sdk, - ) - - finally: - await generator.aclose() - - # Add the unfinished line - if ( - unfinished_line != "" - and not self.line_to_be_ignored( - unfinished_line, completion_lines_covered == 0 - ) - and not self.is_end_line(unfinished_line) - ): - unfinished_line = common_whitespace + unfinished_line - lines.append(unfinished_line) - await handle_generated_line(unfinished_line) - completion_lines_covered += 1 - current_line_in_file += 1 - - await sendDiffUpdate(lines, sdk, final=True) - - # Record the completion - completion = "\n".join(lines) - self._previous_contents = "\n".join(original_lines) - self._new_contents = completion - self._prompt_and_completion += prompt + completion - - async def run(self, sdk: AbstractContinueSDK): - rif_with_contents = [] - for range_in_file in map( - lambda x: RangeInFile( - filepath=x.filepath, - # Only consider the range line-by-line. Maybe later don't if it's only a single line. - range=x.range.to_full_lines(), - ), - self.range_in_files, - ): - file_contents = await sdk.ide.readRangeInFile(range_in_file) - rif_with_contents.append( - RangeInFileWithContents.from_range_in_file(range_in_file, file_contents) - ) - - rif_dict = {} - for rif in rif_with_contents: - rif_dict[rif.filepath] = rif.contents - - for rif in rif_with_contents: - await sdk.ide.setSuggestionsLocked(rif.filepath, True) - async for update in self.stream_rif(rif, sdk): - yield update - await sdk.ide.setSuggestionsLocked(rif.filepath, False) - - changes = "\n".join( - difflib.ndiff( - self._previous_contents.splitlines(), - self._new_contents.splitlines(), - ) - ) - - if sdk.config.disable_summaries: - yield SetStep( - name="", - description=f"Edited {len(self.range_in_files)} files", - ) - else: - yield SetStep( - name="Generating summary", - description="", - ) - async for chunk in sdk.models.summarize.stream_complete( - dedent( - f"""\ - Diff summary: "{self.user_input}" - - ```diff - {changes} - ``` - - {self.summary_prompt}""" - ) - ): - yield chunk - - # TODO: Follow-up edits might die with this update??? - sdk.context.set("last_edit_user_input", self.user_input) - sdk.context.set("last_edit_diff", changes) - sdk.context.set("last_edit_range", self.range_in_files[-1].range) - - -class EditFileStep(Step): - filepath: str - prompt: str - hide: bool = True - model: Optional[LLM] = None - - async def describe(self, models: Models): - return "Editing file: " + self.filepath - - async def run(self, sdk: AbstractContinueSDK): - file_contents = await sdk.ide.readFile(self.filepath) - await sdk.run_step( - DefaultModelEditCodeStep( - range_in_files=[ - RangeInFile.from_entire_file(self.filepath, file_contents) - ], - user_input=self.prompt, - model=self.model, - ) - ) - - -class ManualEditStep(ReversibleStep): - edit_diff: EditDiff - hide: bool = True - - hide: bool = True - - async def describe(self, models: Models): - return "Manual edit step" - # TODO - only handling FileEdit here, but need all other types of FileSystemEdits - # Also requires the merge_file_edit function - # return llm.complete(dedent(f"""This code was replaced: - - # {self.edit_diff.backward.replacement} - - # With this code: - - # {self.edit_diff.forward.replacement} - - # Maximally concise summary of changes in bullet points (can use markdown): - # """)) - - @classmethod - def from_sequence(cls, edits: List[FileEditWithFullContents]) -> "ManualEditStep": - diffs = [] - for edit in edits: - _, diff = FileSystem.apply_edit_to_str(edit.fileContents, edit.fileEdit) - diffs.append(diff) - return cls(edit_diff=EditDiff.from_sequence(diffs)) - - async def run(self, sdk: AbstractContinueSDK): - ... - - async def reverse(self, sdk: AbstractContinueSDK): - await sdk.ide.applyFileSystemEdit(self.edit_diff.backward) - - -class UserInputStep(Step): - user_input: str - context_items: List[ContextItem] = [] - name: str = "User Input" - hide: bool = False - - manage_own_chat_context: bool = True - - async def describe(self, models: Models): - if self.description is not None: - return self.description - return self.user_input - - async def run(self, sdk: AbstractContinueSDK): - self.chat_context.append( - ChatMessage(role="user", content=self.user_input, summary=self.user_input) - ) - self.description = self.user_input - yield UserInputObservation(user_input=self.user_input) diff --git a/archive/server/continuedev/experiments/test.ipynb b/archive/server/continuedev/experiments/test.ipynb deleted file mode 100644 index f10d85e9f..000000000 --- a/archive/server/continuedev/experiments/test.ipynb +++ /dev/null @@ -1,634 +0,0 @@ -{ - "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: \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: \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(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": [ - " 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 -} diff --git a/archive/server/continuedev/experiments/y.json b/archive/server/continuedev/experiments/y.json deleted file mode 100644 index b2507bf77..000000000 --- a/archive/server/continuedev/experiments/y.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "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" - ] - } - ] -} diff --git a/archive/server/continuedev/headless/__init__.py b/archive/server/continuedev/headless/__init__.py deleted file mode 100644 index e058f8547..000000000 --- a/archive/server/continuedev/headless/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -from typing import List, Optional, Union - -from ..core.autopilot import Autopilot -from ..core.config import ContinueConfig -from ..core.context import ContextManager, ContextProvider -from ..core.main import SessionState -from ..server.protocols.cli_gui import CommandLineGUI -from .headless_ide import LocalIdeProtocol - - -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 = 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.completion_options.temperature - # ) - - models = _config.construct_models() - models.start( - ide.window_info.unique_id, - _config.system_message, - _config.completion_options.temperature, - _config.llm_request_hook, - ) - - return Autopilot( - session_state=state or SessionState.from_empty(), - ide=ide, - gui=CommandLineGUI(), - config=_config, - context_manager=context_manager, - models=models, - ) diff --git a/archive/server/continuedev/headless/headless_ide.py b/archive/server/continuedev/headless/headless_ide.py deleted file mode 100644 index 526885a50..000000000 --- a/archive/server/continuedev/headless/headless_ide.py +++ /dev/null @@ -1,202 +0,0 @@ -import os -import subprocess -import uuid -from typing import Any, Callable, List, Optional - -from dotenv import load_dotenv -from fastapi import WebSocket - -from ..models.filesystem import ( - FileSystem, - RangeInFile, - RangeInFileWithContents, - RealFileSystem, -) -from ..models.filesystem_edit import EditDiff, FileEdit, FileSystemEdit -from ..models.main import Position -from ..server.protocols.ide_protocol import AbstractIdeProtocolServer - -load_dotenv() - - -def get_mac_address(): - mac_num = hex(uuid.getnode()).replace("0x", "").upper() - mac = "-".join(mac_num[i : i + 2] for i in range(0, 11, 2)) - return mac - - -class LocalIdeProtocol(AbstractIdeProtocolServer): - websocket: WebSocket - session_id: Optional[str] - workspace_directory: str = os.getcwd() - unique_id: str = get_mac_address() - - filesystem: FileSystem = RealFileSystem() - - def __init__(self, workspace_directory: Optional[str] = None): - if workspace_directory: - self.workspace_directory = workspace_directory - - async def handle_json(self, data: Any): - """Handle a json message""" - pass - - def showSuggestion(self, file_edit: FileEdit): - """Show a suggestion to the user""" - pass - - async def setFileOpen(self, filepath: str, open: bool = True): - """Set whether a file is open""" - pass - - async def showMessage(self, message: str): - """Show a message to the user""" - print(message) - - async def showVirtualFile(self, name: str, contents: str): - """Show a virtual file""" - pass - - async def setSuggestionsLocked(self, filepath: str, locked: bool = True): - """Set whether suggestions are locked""" - pass - - async def getSessionId(self): - """Get a new session ID""" - pass - - def onAcceptRejectSuggestion(self, accepted: bool): - """Called when the user accepts or rejects a suggestion""" - pass - - def onFileSystemUpdate(self, update: FileSystemEdit): - """Called when a file system update is received""" - pass - - def onCloseGUI(self, session_id: str): - """Called when a GUI is closed""" - pass - - def onOpenGUIRequest(self): - """Called when a GUI is requested to be opened""" - pass - - async def getOpenFiles(self) -> List[str]: - """Get a list of open files""" - return [] - - async def getVisibleFiles(self) -> List[str]: - """Get a list of visible files""" - return [] - - async def getHighlightedCode(self) -> List[RangeInFile]: - """Get a list of highlighted code""" - return [] - - async def readFile(self, filepath: str) -> str: - """Read a file""" - try: - return self.filesystem.read(filepath) - except UnicodeDecodeError: - return "" - - async def readRangeInFile(self, range_in_file: RangeInFile) -> str: - """Read a range in a file""" - return self.filesystem.read_range_in_file(range_in_file) - - async def editFile(self, edit: FileEdit): - """Edit a file""" - self.filesystem.apply_file_edit(edit) - - async def applyFileSystemEdit(self, edit: FileSystemEdit) -> EditDiff: - """Apply a file edit""" - return self.filesystem.apply_edit(edit) - - async def saveFile(self, filepath: str): - """Save a file""" - pass - - async def getUserSecret(self, key: str): - """Get a user secret""" - return os.environ.get(key) - - async def highlightCode(self, range_in_file: RangeInFile, color: str): - """Highlight code""" - pass - - async def runCommand(self, command: str) -> str: - """Run a command using subprocess (don't pass, actually implement)""" - return subprocess.check_output(command, shell=True).decode("utf-8") - - def onHighlightedCodeUpdate(self, range_in_files: List[RangeInFileWithContents]): - """Called when highlighted code is updated""" - pass - - def onDeleteAtIndex(self, index: int): - """Called when a step is deleted at a given index""" - pass - - async def showDiff(self, filepath: str, replacement: str, step_index: int): - """Show a diff""" - pass - - def subscribeToFilesCreated(self, callback: Callable[[List[str]], None]): - """Subscribe to files created event""" - pass - - def subscribeToFilesDeleted(self, callback: Callable[[List[str]], None]): - """Subscribe to files deleted event""" - pass - - def subscribeToFilesRenamed(self, callback: Callable[[List[str], List[str]], None]): - """Subscribe to files renamed event""" - pass - - def subscribeToFileSaved(self, callback: Callable[[str, str], None]): - """Subscribe to file saved event""" - pass - - def onFilesCreated(self, filepaths: List[str]): - """Called when files are created""" - pass - - def onFilesDeleted(self, filepaths: List[str]): - """Called when files are deleted""" - pass - - def onFilesRenamed(self, old_filepaths: List[str], new_filepaths: List[str]): - """Called when files are renamed""" - pass - - def onFileSaved(self, filepath: str, contents: str): - """Called when a file is saved""" - pass - - async def fileExists(self, filepath: str) -> bool: - """Check if a file exists""" - return self.filesystem.exists(filepath) - - async def getTerminalContents(self) -> str: - return "" - - async def listDirectoryContents( - self, directory: str, recursive: bool = False - ) -> List[str]: - return self.filesystem.list_directory_contents(directory, recursive=recursive) - - async def goto_definition(self, filepath: str, position: Position): - raise NotImplementedError() - - async def document_symbol(self, filepath: str): - raise NotImplementedError() - - async def find_references( - self, filepath: str, position: Position, include_declaration: bool = False - ): - raise NotImplementedError() - - async def folding_range(self, filepath: str): - raise NotImplementedError() - - async def get_enclosing_folding_range(self, position: Position, filepath: str): - raise NotImplementedError() diff --git a/archive/server/continuedev/libs/__init__.py b/archive/server/continuedev/libs/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/archive/server/continuedev/libs/chroma/.gitignore b/archive/server/continuedev/libs/chroma/.gitignore deleted file mode 100644 index 6320cd248..000000000 --- a/archive/server/continuedev/libs/chroma/.gitignore +++ /dev/null @@ -1 +0,0 @@ -data \ No newline at end of file diff --git a/archive/server/continuedev/libs/chroma/update.py b/archive/server/continuedev/libs/chroma/update.py deleted file mode 100644 index 041586767..000000000 --- a/archive/server/continuedev/libs/chroma/update.py +++ /dev/null @@ -1,53 +0,0 @@ -# import faiss -import os -import subprocess -from typing import List - -from dotenv import load_dotenv - -load_dotenv() - -FILE_TYPES_TO_IGNORE = [".pyc", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico"] - - -def filter_ignored_files(files: List[str], root_dir: str): - """Further filter files before indexing.""" - for file in files: - if ( - file.endswith(tuple(FILE_TYPES_TO_IGNORE)) - or file.startswith(".git") - or file.startswith("archive") - ): - continue # nice - yield root_dir + "/" + file - - -def get_git_ignored_files(root_dir: str): - """Get the list of ignored files in a Git repository.""" - try: - output = ( - subprocess.check_output( - ["git", "ls-files", "--ignored", "--others", "--exclude-standard"], - cwd=root_dir, - ) - .strip() - .decode() - ) - return output.split("\n") - except subprocess.CalledProcessError: - return [] - - -def get_all_files(root_dir: str): - """Get a list of all files in a directory.""" - for dir_path, _, file_names in os.walk(root_dir): - for file_name in file_names: - yield os.path.join(os.path.relpath(dir_path, root_dir), file_name) - - -def get_input_files(root_dir: str): - """Get a list of all files in a Git repository that are not ignored.""" - ignored_files = set(get_git_ignored_files(root_dir)) - all_files = set(get_all_files(root_dir)) - nonignored_files = all_files - ignored_files - return filter_ignored_files(nonignored_files, root_dir) diff --git a/archive/server/continuedev/libs/constants/default_config.py b/archive/server/continuedev/libs/constants/default_config.py deleted file mode 100644 index a89eb1080..000000000 --- a/archive/server/continuedev/libs/constants/default_config.py +++ /dev/null @@ -1,64 +0,0 @@ -default_config = """\ -\"\"\" -config.py allows you to modify Continue programmatically instead of just using config.json. - -First, config.json is loaded. Then, if you have defined modify_config here, the function will be given the result of -loading config.json, and will return the final ContinueConfig to be used. -\"\"\" - -from continuedev.core.config import ContinueConfig - -def modify_config(config: ContinueConfig) -> ContinueConfig: - # config.completion_options.temperature = 0.5 - return config - -""" - -default_config_json = """\ -{ - "models": [ - { - "title": "GPT-4", - "provider": "free-trial", - "model": "gpt-4" - }, - { - "title": "GPT-3.5-Turbo", - "provider": "free-trial", - "model": "gpt-3.5-turbo" - } - ], - "model_roles": { - "default": "GPT-4" - }, - "slash_commands": [ - { - "name": "edit", - "description": "Edit highlighted code", - "step": "EditHighlightedCodeStep" - }, - { - "name": "comment", - "description": "Write comments for the highlighted code", - "step": "CommentCodeStep" - }, - { - "name": "share", - "description": "Download and share this session", - "step": "ShareSessionStep" - }, - { - "name": "cmd", - "description": "Generate a shell command", - "step": "GenerateShellCommandStep" - } - ], - "custom_commands": [ - { - "name": "test", - "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "Write unit tests for highlighted code" - } - ] -} -""" diff --git a/archive/server/continuedev/libs/constants/main.py b/archive/server/continuedev/libs/constants/main.py deleted file mode 100644 index f5964df62..000000000 --- a/archive/server/continuedev/libs/constants/main.py +++ /dev/null @@ -1,6 +0,0 @@ -## PATHS ## - -CONTINUE_GLOBAL_FOLDER = ".continue" -CONTINUE_SESSIONS_FOLDER = "sessions" -CONTINUE_SERVER_FOLDER = "server" -CONTINUE_SERVER_VERSION_FILE = "server_version.txt" diff --git a/archive/server/continuedev/libs/index/.gitignore b/archive/server/continuedev/libs/index/.gitignore deleted file mode 100644 index 6320cd248..000000000 --- a/archive/server/continuedev/libs/index/.gitignore +++ /dev/null @@ -1 +0,0 @@ -data \ No newline at end of file diff --git a/archive/server/continuedev/libs/index/build_index.py b/archive/server/continuedev/libs/index/build_index.py deleted file mode 100644 index cc4750cab..000000000 --- a/archive/server/continuedev/libs/index/build_index.py +++ /dev/null @@ -1,79 +0,0 @@ -import asyncio -from typing import AsyncGenerator - -from ...core.config import ContinueConfig -from ...libs.index.indices.chroma_index import MAX_CHUNK_SIZE, ChromaCodebaseIndex -from ...libs.index.indices.meilisearch_index import MeilisearchCodebaseIndex -from ...server.protocols.ide_protocol import AbstractIdeProtocolServer -from .chunkers.chunk_directory import ( - local_stream_chunk_directory, - stream_chunk_directory, -) - - -async def build_index( - ide: AbstractIdeProtocolServer, config: ContinueConfig -) -> AsyncGenerator[float, None]: - tag = await ide.getTag() - branch = await ide.getBranch() - settings = config.retrieval_settings - chroma_index = ChromaCodebaseIndex( - tag, - 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(tag) - - n = 2 - done = False - buffers = [[] for _ in range(n)] - - async def generator_for_chroma(): - nonlocal buffers - while not done or len(buffers[0]) > 0: - if len(buffers[0]) > 0: - yield buffers[0].pop(0) - else: - await asyncio.sleep(0.1) - - async def generator_for_meilisearch(): - nonlocal buffers - while not done or len(buffers[1]) > 0: - if len(buffers[1]) > 0: - yield buffers[1].pop(0) - else: - await asyncio.sleep(0.1) - - chroma_task = asyncio.create_task(chroma_index.build(generator_for_chroma())) - meilisearch_task = asyncio.create_task( - meilisearch_index.build(generator_for_meilisearch()) - ) - - server_url = ide.window_info.ide_info.get("server_url", "http://localhost:65432") - if ide.window_info.ide_info.get("remote_name", None) in ["ssh-remote", "wsl"] or ( - "localhost" not in server_url and "127.0.0.1" not in server_url - ): - # Use the old method if workspace is remote OR if Continue server is not running on the same machine as the IDE - async for chunk, progress in stream_chunk_directory(ide, MAX_CHUNK_SIZE): - if chunk is not None: - buffers[0].append(("compute", chunk)) - buffers[1].append(("compute", chunk)) - yield progress - - else: - # If on same machine, can access files directly - for action, chunk, progress in local_stream_chunk_directory( - ide.workspace_directory, MAX_CHUNK_SIZE, branch - ): - buffers[0].append((action, chunk)) - buffers[1].append((action, chunk)) - yield progress - - done = True - while not chroma_task.done() or not meilisearch_task.done(): - await asyncio.sleep(0.1) - - yield 1 diff --git a/archive/server/continuedev/libs/index/chunk_metadata.py b/archive/server/continuedev/libs/index/chunk_metadata.py deleted file mode 100644 index 461214500..000000000 --- a/archive/server/continuedev/libs/index/chunk_metadata.py +++ /dev/null @@ -1,11 +0,0 @@ -import os -from typing import Dict - - -def chunk_metadata(filepath: str, chunk: str) -> Dict[str, str]: - # TODO: Try adding c-tags to the top of each chunk - return {} - - -def format_chunk_with_metadata(filepath: str, chunk: str) -> str: - return f"```title={os.path.basename(filepath)}\n{chunk}```" diff --git a/archive/server/continuedev/libs/index/chunkers/__init__.py b/archive/server/continuedev/libs/index/chunkers/__init__.py deleted file mode 100644 index 919d2c70e..000000000 --- a/archive/server/continuedev/libs/index/chunkers/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -from typing import List, Optional - -from .basic import basic_chunker -from .chunk import Chunk, ChunkWithoutID -from .code import code_chunker, file_extension_to_language - - -def _chunk_document_without_id( - filepath: str, contents: Optional[str], max_chunk_size: int -) -> List[ChunkWithoutID]: - """Chunk a document into smaller pieces.""" - if contents is None: - return [] - - ext = filepath.split(".")[-1] - if ext in file_extension_to_language: - return code_chunker(filepath, contents, max_chunk_size) - - return basic_chunker(contents, max_chunk_size) - - -def chunk_document( - filepath: str, contents: Optional[str], max_chunk_size: int, digest: str -) -> List[Chunk]: - chunks = _chunk_document_without_id(filepath, contents, max_chunk_size) - return [chunk.with_id(digest, i, filepath) for i, chunk in enumerate(chunks)] diff --git a/archive/server/continuedev/libs/index/chunkers/basic.py b/archive/server/continuedev/libs/index/chunkers/basic.py deleted file mode 100644 index 342a3e1ed..000000000 --- a/archive/server/continuedev/libs/index/chunkers/basic.py +++ /dev/null @@ -1,42 +0,0 @@ -from typing import List - -from .chunk import ChunkWithoutID -from ...util.count_tokens import count_tokens - - -def basic_chunker(contents: str, max_chunk_size: int) -> List[ChunkWithoutID]: - """Chunk a document into smaller pieces.""" - chunks = [] - - chunk_content = "" - chunk_tokens = 0 - start_line = 0 - curr_line = 0 - - for line in contents.split("\n"): - line_tokens = count_tokens(line) - if chunk_tokens + line_tokens > max_chunk_size: - chunks.append( - ChunkWithoutID( - content=chunk_content, - start_line=start_line, - end_line=curr_line - 1, - ) - ) - chunk_content = "" - chunk_tokens = 0 - start_line = curr_line - - chunk_content += line + "\n" - chunk_tokens += line_tokens - curr_line += 1 - - chunks.append( - ChunkWithoutID( - content=chunk_content, - start_line=start_line, - end_line=curr_line - 1, - index=len(chunks), - ) - ) - return chunks diff --git a/archive/server/continuedev/libs/index/chunkers/chunk.py b/archive/server/continuedev/libs/index/chunkers/chunk.py deleted file mode 100644 index b1458da77..000000000 --- a/archive/server/continuedev/libs/index/chunkers/chunk.py +++ /dev/null @@ -1,43 +0,0 @@ -from chromadb.types import Metadata - -from ....models.main import ContinueBaseModel - - -class ChunkWithoutID(ContinueBaseModel): - content: str - start_line: int - end_line: int - other_metadata: Metadata = {} - - def with_id(self, digest: str, index: int, filepath: str): - return Chunk( - content=self.content, - start_line=self.start_line, - end_line=self.end_line, - other_metadata=self.other_metadata, - digest=digest, - index=index, - filepath=filepath, - ) - - -class Chunk(ChunkWithoutID): - digest: str - index: int # The index of the chunk in the document - filepath: str - - @property - def id(self): - return f"{self.digest}::{self.index}" - - @property - def metadata(self): - # Nested dicts not allowed by chromadb - other_metadata = self.other_metadata.copy() - d = self.dict() - del d["content"] - del d["other_metadata"] - return { - **other_metadata, - **d, - } diff --git a/archive/server/continuedev/libs/index/chunkers/chunk_directory.py b/archive/server/continuedev/libs/index/chunkers/chunk_directory.py deleted file mode 100644 index 01ca2554e..000000000 --- a/archive/server/continuedev/libs/index/chunkers/chunk_directory.py +++ /dev/null @@ -1,140 +0,0 @@ -import asyncio -import hashlib -import os -from typing import ( - AsyncGenerator, - Callable, - Generator, - List, - Literal, - Optional, - Tuple, - Union, -) - -from continuedev.continuedev import sync_results - -from ....server.protocols.ide_protocol import AbstractIdeProtocolServer -from . import chunk_document -from .chunk import Chunk -from .ignore import should_ignore_file_factory - -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]) - - -async def get_all_filepaths( - ide: AbstractIdeProtocolServer, ignore_files: List[str] = [] -) -> Tuple[List[str], Callable[[str], bool]]: - 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) - } - - should_ignore_file = should_ignore_file_factory(ignore_files, gitignores) - - return files, should_ignore_file - - -async def stream_file_contents( - ide: AbstractIdeProtocolServer, ignore_files: List[str] = [], group_size: int = 100 -) -> AsyncGenerator[Tuple[str, Optional[str], float], None]: - # Get list of filenames to index - # TODO: Don't get all at once, walk the tree, or break up - files, should_ignore = await get_all_filepaths(ide, ignore_files) - - # Don't want to flood with too many requests - i = 0 - total = len(files) - for file in files: - if should_ignore(file): - total = max(1, total - 1) - yield (file, None, i / total) - continue - - contents = await get_file_contents(file, ide) - yield (file, contents, i / total) - i += 1 - - -async def stream_chunk_directory( - ide: AbstractIdeProtocolServer, max_chunk_size: int, ignore_files: List[str] = [] -) -> AsyncGenerator[Tuple[Optional[Chunk], float], None]: - async for file, contents, progress in stream_file_contents( - ide, ignore_files=ignore_files - ): - if contents is None: - yield (None, progress) - continue - - for chunk in chunk_document( - file, contents, max_chunk_size, hashlib.sha1(contents.encode()).hexdigest() - ): - yield (chunk, progress) - - -IndexAction = Literal["compute", "delete", "add_label", "remove_label"] - - -def local_stream_chunk_directory( - workspace_dir: str, max_chunk_size: int, branch: str -) -> Generator[Tuple[IndexAction, Union[str, Chunk], float], None, None]: - """Stream Tuples of (action, chunk, progress). the chunk is a Chunk if 'compute' action, otherwise it is the digest string. the assumption in this case is to delete/update all chunks for the document id (digest).""" - (compute, delete, add_label, remove_label) = sync_results(workspace_dir, branch) - - progress = 1 - total = len(compute) + len(delete) + len(add_label) + len(remove_label) + 1 - - for filepath, digest in compute: - # Ignore if the file is too large (cutoff is 10MB) - if os.path.getsize(filepath) > 10_000_000: - continue - - try: - contents = open(filepath, "r").read() - except Exception as e: - print(e, filepath) - continue - - if contents.strip() == "": - continue - - for chunk in chunk_document(filepath, contents, max_chunk_size, digest): - yield ("compute", chunk, progress / total) - - progress += 1 - - for filepath, digest in delete: - yield ("delete", digest, progress / total) - progress += 1 - - for filepath, digest in add_label: - yield ("add_label", digest, progress / total) - progress += 1 - - for filepath, digest in remove_label: - yield ("remove_label", digest, progress / total) - progress += 1 diff --git a/archive/server/continuedev/libs/index/chunkers/code.py b/archive/server/continuedev/libs/index/chunkers/code.py deleted file mode 100644 index 52fd771ea..000000000 --- a/archive/server/continuedev/libs/index/chunkers/code.py +++ /dev/null @@ -1,169 +0,0 @@ -from typing import List, Union -from .chunk import ChunkWithoutID -from tree_sitter_languages import get_parser -from tree_sitter import Node -from ...util.count_tokens import count_tokens - -file_extension_to_language = { - "py": "python", - "js": "javascript", - "ts": "typescript", - "java": "java", - "go": "go", - "rb": "ruby", - "rs": "rust", - "c": "c", - "cpp": "cpp", - "cs": "c_sharp", - "php": "php", - "scala": "scala", - "swift": "swift", - "kt": "kotlin", -} - - -def get_parser_for_file(filepath: str): - ext = filepath.split(".")[-1] - if lang := file_extension_to_language.get(ext): - return get_parser(lang) - - raise Exception(f"Could not find language for file {filepath}") - - -def get_all_nodes(node: Node): - yield node - for child in node.children: - yield from get_all_nodes(child) - - -def first_child(node: Node, grammar_name: Union[str, List[str]]): - if isinstance(grammar_name, list): - return next( - filter(lambda x: x.grammar_name in grammar_name, node.children), None - ) - return next(filter(lambda x: x.grammar_name == grammar_name, node.children), None) - - -# TODO: This should actually happen a level up. Given the whole function, return `def f():\n\t...` for example -def collapsed_replacement(node: Node): - if node.grammar_name == "statement_block": - return "{ ... }" - else: - return "..." - - -def collapse_children( - node: Node, - code: str, - block_types: List[str], - collapse_types: List[str], - collapse_block_types: List[str], -) -> str: - code = code[: node.end_byte] - if block := first_child(node, block_types): - for child in reversed( - list( - filter( - lambda x: x.grammar_name in collapse_types, - block.children, - ) - ) - ): - if grand_child := first_child(child, collapse_block_types): - start = grand_child.start_byte - end = grand_child.end_byte - code = code[:start] + collapsed_replacement(grand_child) + code[end:] - - return code[node.start_byte :] - - -def construct_class_definition_chunk(node: Node, code): - return collapse_children( - node, - code, - ["block", "class_body", "declaration_list"], - ["method_definition", "function_definition", "function_item"], - ["block", "statement_block"], - ) - - -def construct_function_definition_chunk(node: Node, code) -> str: - func_text = node.text.decode("utf8") - if ( - node.parent - and node.parent.grammar_name in ["block", "declaration_list"] - and node.parent.parent - and node.parent.parent.grammar_name in ["class_definition", "impl_item"] - ): - # If inside a class, include the class header - class_node = node.parent.parent - class_block = node.parent - - return ( - code[class_node.start_byte : class_block.start_byte] - + "...\n\n" - + (" " * node.start_point[1]) - + func_text - ) - - return func_text - - -collapsed_node_constructors = { - # Classes, structs, etc - "class_definition": construct_class_definition_chunk, - "class_declaration": construct_class_definition_chunk, - "impl_item": construct_class_definition_chunk, - # Functions - "function_definition": construct_function_definition_chunk, - "function_declaration": construct_function_definition_chunk, - "function_item": construct_function_definition_chunk, -} - - -def get_smart_collapsed_chunks( - node: Node, code: str, max_chunk_size: int, root: bool = True -) -> List[ChunkWithoutID]: - # Keep entire text if not over size - if (root or node.grammar_name in collapsed_node_constructors) and count_tokens( - node.text.decode("utf8") - ) < max_chunk_size: - yield ChunkWithoutID( - content=node.text.decode("utf8"), - start_line=node.start_point[0], - end_line=node.end_point[0], - ) - return - - # If a collapsed form is defined, use that - if node.grammar_name in collapsed_node_constructors: - yield ChunkWithoutID( - content=collapsed_node_constructors[node.grammar_name](node, code), - start_line=node.start_point[0], - end_line=node.end_point[0], - ) - # TODO - if this is still too large, what can you do? - - # TODO: Should try to group elements together from the top. If you can fit together multiple functions, that is prob ideal - # But how to avoid separating a docstring from it's function for example? - # Also find a metric to test against please! - - # Recurse (because even if collapsed version was shown, want to show the children in full somewhere) - for child in node.children: - yield from get_smart_collapsed_chunks(child, code, max_chunk_size, root=False) - - -def code_chunker( - filepath: str, contents: str, max_chunk_size: int -) -> List[ChunkWithoutID]: - if contents is None or len(contents.strip()) == 0: - return [] - - try: - parser = get_parser_for_file(filepath) - except Exception: - return [] - - tree = parser.parse(bytes(contents, "utf8")) - - return list(get_smart_collapsed_chunks(tree.root_node, contents, max_chunk_size)) diff --git a/archive/server/continuedev/libs/index/chunkers/fast_index.py b/archive/server/continuedev/libs/index/chunkers/fast_index.py deleted file mode 100644 index 18fe9c5f0..000000000 --- a/archive/server/continuedev/libs/index/chunkers/fast_index.py +++ /dev/null @@ -1,140 +0,0 @@ -# TODO: -""" -- Follow .continueignore -- How do we know to remove embeddings? -On window load, check the list of branches against -those you have indexed. Then purge any that don't exist. -""" - -from contextlib import contextmanager -import os -from typing import Callable, Generator, List, Tuple -from ...util.paths import getGlobalFolderPath -from .ignore import should_ignore_file_factory, local_find_gitignores -import pygit2 - -INDEX_CACHE_PATH = os.path.join(getGlobalFolderPath(), ".index_cache") -INDEX_BRANCHES_PATH = os.path.join(getGlobalFolderPath(), ".index_branches") - - -class DiskSet: - """ - An on-disk set. - - On disk - - Set operations - - False positives not okay - - False negatives okay - """ - - def __init__(self, path: str): - if not os.path.exists(path): - with open(path, "w") as f: - f.write("") - - self.file = open(path, "a+") - - def __contains__(self, item: str) -> bool: - self.file.seek(0) - for line in self.file.readlines(): - if line.strip() == item: - return True - return False - - def add(self, item: str) -> None: - if item in self: - return - - self.file.write(item + "\n") - self.file.flush() - - def remove(self, item: str) -> None: - self.file.seek(0) - lines = self.file.readlines() - self.file.seek(0) - self.file.truncate(0) - for line in lines: - if line.strip() != item: - self.file.write(line) - - def close(self) -> None: - self.file.close() - - -@contextmanager -def disk_set(path: str) -> Generator[DiskSet, None, None]: - set = DiskSet(path) - try: - yield set - finally: - set.close() - - -FileAndHash = Tuple[str, str] - - -def stream_files_to_update( - workspace_dir: str, -) -> Generator[FileAndHash, None, None]: - """Yield (file, hash) pairs""" - - repo = pygit2.Repository(workspace_dir) - commit = repo.head.peel(pygit2.Commit) - - gitignores = local_find_gitignores(workspace_dir) - should_ignore = should_ignore_file_factory([], gitignores) - - with disk_set(INDEX_CACHE_PATH) as already_indexed: - yield from files_to_update_in( - commit, already_indexed, repo.workdir, should_ignore - ) - - # Yield from files changed in the working tree - should_yield = set( - [ - pygit2.GIT_STATUS_INDEX_NEW, - pygit2.GIT_STATUS_INDEX_MODIFIED, - pygit2.GIT_STATUS_WT_MODIFIED, - pygit2.GIT_STATUS_WT_NEW, - ] - ) - for filepath, status in repo.status().items(): - if status in should_yield and not should_ignore(filepath): - digest = repo.revparse_single("HEAD:" + filepath).hex - yield filepath, digest - - -def files_to_update_in( - obj: pygit2.Object, - already_indexed: DiskSet, - path: str, - should_ignore: Callable[[str], bool], -) -> Generator[FileAndHash, None, None]: - """Given an object, yield all files to update""" - if obj.hex in already_indexed or should_ignore(path): - return - - if obj.type == pygit2.GIT_OBJ_BLOB: - yield path, obj.hex - elif obj.type == pygit2.GIT_OBJ_TREE: - for entry in obj: - yield from files_to_update_in( - entry, already_indexed, os.path.join(path, entry.name), should_ignore - ) - elif obj.type == pygit2.GIT_OBJ_COMMIT: - yield from files_to_update_in(obj.tree, already_indexed, path, should_ignore) - else: - raise Exception("Unknown type: " + str(obj.type)) - - already_indexed.add(obj.hex) - - -def get_all_branches(workspace_dir: str) -> List[str]: - repo = pygit2.Repository(workspace_dir) - return [ref for ref in repo.branches.local] - - -def clean_deleted_branches(current_branches: str): - with disk_set(INDEX_BRANCHES_PATH) as indexed_branches: - for branch in indexed_branches: - if branch not in current_branches: - indexed_branches.remove(branch) diff --git a/archive/server/continuedev/libs/index/chunkers/ignore.py b/archive/server/continuedev/libs/index/chunkers/ignore.py deleted file mode 100644 index 53a72cb9d..000000000 --- a/archive/server/continuedev/libs/index/chunkers/ignore.py +++ /dev/null @@ -1,105 +0,0 @@ -import os -from typing import Callable, Dict, List -from ...util.filter_files import DEFAULT_IGNORE_PATTERNS, should_filter_path - -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", - "*.woff", - "*.woff2", - "*.eot", - "*.cur", - "*.avi", - "*.mpg", - "*.mpeg", - "*.mov", - "*.mp3", - "*.mp4", - "*.mkv", - "*.mkv", - "*.webm", - "*.jar", -] - - -def gi_basename(path: str) -> str: - if ".gitignore" in path: - return path[: path.index(".gitignore")] - elif ".continueignore" in path: - return path[: path.index(".continueignore")] - else: - return path - - -def local_find_gitignores(workspace_dir: str) -> Dict[str, str]: - gitignores = {} - for root, dirs, files in os.walk(workspace_dir): - for file in files: - if file.endswith(".gitignore") or file.endswith(".continueignore"): - path = os.path.join(root, file) - with open(path, "r") as f: - gitignores[path] = f.read() - - return gitignores - - -def should_ignore_file_factory( - ignore_files: List[str], gitignores: Dict[str, str] -) -> Callable[[str], bool]: - gitignore_paths = list(gitignores.keys()) - - 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 - - def should_ignore_file(filepath: str) -> bool: - return should_filter_path( - filepath, - ignore_files - + DEFAULT_IGNORE_PATTERNS - + FILE_IGNORE_PATTERNS - + gitignore_patterns_for_file(filepath), - ) - - return should_ignore_file diff --git a/archive/server/continuedev/libs/index/git.py b/archive/server/continuedev/libs/index/git.py deleted file mode 100644 index eb7ff169e..000000000 --- a/archive/server/continuedev/libs/index/git.py +++ /dev/null @@ -1,89 +0,0 @@ -from functools import cached_property -import os -import subprocess -from typing import List, Tuple - -from .update import filter_ignored_files - - -class GitProject: - directory: str - - def __init__(self, directory: str): - self.directory = directory - - @cached_property - def current_commit(self) -> str: - """Get the current commit.""" - try: - return ( - subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=self.directory - ) - .decode("utf-8") - .strip() - ) - except Exception: - return "NONE" - - @cached_property - def current_branch(self) -> str: - """Get the current branch.""" - try: - return ( - subprocess.check_output( - ["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=self.directory - ) - .decode("utf-8") - .strip() - ) - except Exception: - return "NONE" - - @cached_property - def git_root_dir(self): - """Get the root directory of a Git repository.""" - try: - return ( - subprocess.check_output( - ["git", "rev-parse", "--show-toplevel"], cwd=self.directory - ) - .strip() - .decode() - ) - except Exception: - return None - - def get_modified_deleted_files( - self, since_commit: str - ) -> Tuple[List[str], List[str]]: - """Get a list of all files that have been modified since the last commit.""" - - try: - modified_deleted_files = ( - subprocess.check_output( - ["git", "diff", "--name-only", since_commit, self.current_commit] - ) - .decode("utf-8") - .strip() - ) - except Exception: - return [], [] - - modified_deleted_files = modified_deleted_files.split("\n") - modified_deleted_files = [f for f in modified_deleted_files if f] - - deleted_files = [ - f - for f in modified_deleted_files - if not os.path.exists(os.path.join(self.directory, f)) - ] - modified_files = [ - f - for f in modified_deleted_files - if os.path.exists(os.path.join(self.directory, f)) - ] - - return filter_ignored_files( - modified_files, self.index_dir - ), filter_ignored_files(deleted_files, self.index_dir) diff --git a/archive/server/continuedev/libs/index/hyde.py b/archive/server/continuedev/libs/index/hyde.py deleted file mode 100644 index e1a48c2ca..000000000 --- a/archive/server/continuedev/libs/index/hyde.py +++ /dev/null @@ -1,50 +0,0 @@ -# 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(", ") diff --git a/archive/server/continuedev/libs/index/indices/base.py b/archive/server/continuedev/libs/index/indices/base.py deleted file mode 100644 index 24a2313da..000000000 --- a/archive/server/continuedev/libs/index/indices/base.py +++ /dev/null @@ -1,19 +0,0 @@ -from abc import ABC, abstractmethod -from typing import AsyncGenerator, List, Tuple, Union - -from ..chunkers import Chunk -from ..chunkers.chunk_directory import IndexAction - - -class CodebaseIndex(ABC): - @abstractmethod - async def build( - self, chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None] - ): - """Builds the index, yielding progress as a float between 0 and 1. Chunks are yielded from the given generator.""" - raise NotImplementedError() - - @abstractmethod - async def query(self, query: str, n: int = 4) -> List[Chunk]: - """Queries the index, returning the top n results""" - raise NotImplementedError() diff --git a/archive/server/continuedev/libs/index/indices/chroma_index.py b/archive/server/continuedev/libs/index/indices/chroma_index.py deleted file mode 100644 index 5c6895fb0..000000000 --- a/archive/server/continuedev/libs/index/indices/chroma_index.py +++ /dev/null @@ -1,273 +0,0 @@ -import asyncio -import os -import re -import sqlite3 -from functools import cached_property -from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Tuple, Union - -import chromadb - -# from chromadb.api import ClientAPI -from chromadb.config import Settings -from chromadb.utils import embedding_functions -from dotenv import load_dotenv -from openai import RateLimitError -from pydantic import BaseModel - -from ...util.logging import logger -from ...util.paths import getIndexFolderPath -from ..chunkers.chunk import Chunk -from ..chunkers.chunk_directory import IndexAction -from ..git import GitProject -from .base import CodebaseIndex - -load_dotenv() - -EmbeddingsType = Literal["default", "openai"] - -MAX_CHUNK_SIZE = 512 - -collection: chromadb.Collection = None - - -class CodebaseIndexMetadata(BaseModel): - commit: str - chunks: Dict[str, int] - - -GROUP_SIZE = 5 - - -class ChromaCodebaseIndex(CodebaseIndex): - tag: str - client: Any - openai_api_key: Optional[str] = None - api_base: Optional[str] = None - api_version: Optional[str] = None - api_type: Optional[str] = None - organization_id: Optional[str] = None - git_project: GitProject - - def __init__( - self, - tag: str, - openai_api_key: Optional[str] = None, - api_base: Optional[str] = None, - api_version: Optional[str] = None, - api_type: Optional[str] = None, - organization_id: Optional[str] = None, - ): - self.tag = tag - self.openai_api_key = openai_api_key - self.api_base = api_base - self.api_version = api_version - self.api_type = api_type - self.organization_id = organization_id - self.client = chromadb.PersistentClient( - path=self.chroma_dir, - settings=Settings(anonymized_telemetry=False), - ) - - os.environ.setdefault("TOKENIZERS_PARALLELISM", "true") - - @property - def chroma_dir(self): - return os.path.join(self.index_dir, "chroma") - - @property - def embeddings_type(self) -> EmbeddingsType: - return "default" if self.openai_api_key is None else "openai" - - @cached_property - def index_dir(self) -> str: - directory = os.path.join( - getIndexFolderPath(), - "chroma", - self.embeddings_type, - ) - os.makedirs(directory, exist_ok=True) - return directory - - @property - def index_name(self) -> str: - return self.embeddings_type - - def exists(self): - """Check whether the codebase index has already been built and saved on disk""" - return os.path.exists(self.chroma_dir) - - def convert_to_valid_chroma_collection(self, name: str) -> str: - # https://docs.trychroma.com/usage-guide#creating-inspecting-and-deleting-collections - - # Truncate or pad name to correct length - if len(name) < 3: - name = name.ljust(3, "a") - elif len(name) > 63: - name = name[:63] - - # Ensure name starts and ends with a lowercase letter or digit - if not re.match("^[a-z0-9]", name[0]): - name = "a" + name[1:] - if not re.match("[a-z0-9]$", name[-1]): - name = name[:-1] + "a" - - # Replace invalid characters with 'a' - name = re.sub("[^a-z0-9._-]", "a", name) - - # Replace consecutive dots with a single dot - name = re.sub("\\.\\.+", ".", name) - - return name - - @property - def collection(self): - global collection - - if os.path.exists(self.chroma_dir) and collection is not None: - return collection - - kwargs: Dict[str, Any] = { - "name": self.convert_to_valid_chroma_collection( - f"chroma-{self.embeddings_type}" - ), - } - if self.openai_api_key is not None: - kwargs["embedding_function"] = embedding_functions.OpenAIEmbeddingFunction( - api_key=self.openai_api_key, - model_name="text-embedding-ada-002", - api_base=self.api_base, - api_version=self.api_version, - api_type=self.api_type, - organization_id=self.organization_id, - ) - - collection = self.client.get_or_create_collection(**kwargs) - return collection - - async def add_chunks(self, chunks: List[Chunk]): - global collection - - # Flatten chunks, metadata, and ids for insertion to Chroma - documents = [] - metadatas = [] - ids = [] - - for chunk in chunks: - documents.append(chunk.content) - metadata = {**chunk.metadata} - metadata["filepath"] = chunk.filepath - metadata[ - "document_id" - ] = chunk.digest # Need to be able to filter by document_id (hash) - metadata[self.tag] = 1 # This is how we filter by tag - metadatas.append(metadata) - ids.append(chunk.id) - - # Embed the chunks and place into vector database - # Attempt to avoid rate-limiting - i = 0 - wait_time = 4.0 - while i < len(ids): - try: - await asyncio.sleep(0.05) - - self.collection.upsert( - documents=documents[i : i + GROUP_SIZE], - metadatas=metadatas[i : i + GROUP_SIZE], - ids=ids[i : i + GROUP_SIZE], - ) - i += GROUP_SIZE - - 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 - - except sqlite3.OperationalError as e: - logger.debug(f"SQL error: {e}") - collection = None - - def delete_chunks(self, digest: str): - # Delete the chunks from the vector database - result = self.collection.get(where={"document_id": digest}) - ids = result["ids"] - - if len(ids) > 0: - self.collection.delete(ids=ids) - - def add_label(self, digest: str): - ids = self.collection.get(where={"document_id": digest})["ids"] - self.collection.update(ids=ids, metadatas=[{self.tag: 1}] * len(ids)) - - def remove_label(self, digest: str): - ids = self.collection.get(where={"document_id": digest})["ids"] - self.collection.update(ids=ids, metadatas=[{self.tag: 0}] * len(ids)) - - async def build( - self, - chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None], - ): - """Create a new index for the current branch.""" - - group = [] - async for action, chunk in chunks: - if action == "compute": - if chunk.content.strip() == "": - continue - - group.append(chunk) - if len(group) < GROUP_SIZE: - continue - - await self.add_chunks(group) - group = [] - elif action == "delete": - self.delete_chunks(chunk) - elif action == "add_label": - self.add_label(chunk) - elif action == "remove_label": - self.remove_label(chunk) - - if len(group) > 0: - await self.add_chunks(group) - - async def query(self, query: str, n: int = 4) -> List[Chunk]: - """Query the codebase index for top n results""" - if not self.exists(): - logger.warning(f"No index found for the codebase at {self.index_dir}") - return [] - - results = self.collection.query( - query_texts=[query], n_results=n, where={self.tag: {"$ne": 0}} - ) - - chunks = [] - ids = results["ids"][0] - metadatas = results["metadatas"][0] - documents = results["documents"][0] - for i in range(len(ids)): - # Probably better to define some wrapper on Chroma or other VectorDB in general that is "Chunk in, Chunk out" - other_metadata = metadatas[i] - start_line = other_metadata.pop("start_line") - end_line = other_metadata.pop("end_line") - index = other_metadata.pop("index") - document_id = other_metadata.pop("document_id") - filepath = other_metadata.pop("filepath") - chunks.append( - Chunk( - content=documents[i], - start_line=start_line, - end_line=end_line, - other_metadata=other_metadata, - digest=document_id, - index=index, - filepath=filepath, - ) - ) - return chunks - - async def delete_branch(self): - self.collection.copy - self.collection.delete() diff --git a/archive/server/continuedev/libs/index/indices/meilisearch_index.py b/archive/server/continuedev/libs/index/indices/meilisearch_index.py deleted file mode 100644 index f990cd934..000000000 --- a/archive/server/continuedev/libs/index/indices/meilisearch_index.py +++ /dev/null @@ -1,198 +0,0 @@ -import asyncio -from functools import cached_property -from typing import Any, AsyncGenerator, Dict, List, Tuple, Union - -from meilisearch_python_async import Client -from meilisearch_python_async.index import Index - -from ....server.meilisearch_server import ( - get_meilisearch_url, - remove_meilisearch_disallowed_chars, -) -from ...util.logging import logger -from ..chunkers import Chunk -from ..chunkers.chunk_directory import IndexAction -from .base import CodebaseIndex - - -class MeilisearchCodebaseIndex(CodebaseIndex): - """ - The documents have the following structure: - - document_id field is the hash of the document - - actual id is document_id + :: + chunk index - - tags is a list of each (directory + branch) the chunk is indexed for, then we can query for all chunks with a given label - - There is only a single index because it allows us to share between sub-directories - """ - - tag: str - - def __init__(self, tag: str): - self.tag = tag - - @cached_property - def index_name(self) -> str: - return remove_meilisearch_disallowed_chars("continue_codebase_index") - - def chunk_to_meilisearch_document( - self, chunk: Chunk, index: int, tags: List[str] - ) -> Dict[str, Any]: - return { - "id": str(index), - "content": chunk.content, - "document_id": chunk.digest, - "tags": [], - **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"] - del other_metadata["tags"] - del other_metadata["filepath"] - - return Chunk( - content=document["content"], - start_line=document["metadata"]["start_line"], - end_line=document["metadata"]["end_line"], - index=document["metadata"]["index"], - digest=document["document_id"], - filepath=document["filepath"], - other_metadata=other_metadata, - ) - - async def add_chunks(self, chunks: List[Chunk], index: Index, offset: int): - await index.add_documents( - [ - self.chunk_to_meilisearch_document( - chunk, int(chunk.digest, 16), [self.tag] - ) - for chunk in chunks - ], - primary_key="id", - ) - - async def delete_chunks(self, document_ids: List[str], index: Index): - documents = ( - await index.get_documents( - filter=f'document_id IN [{",".join(document_ids)}]' - ) - ).results - - ids = [document["id"] for document in documents] - await index.delete_documents(ids) - - async def get_docs_for_digest(self, digest: str, index: Index): - """Given the hash of a document, give all of the ids of the chunks stored in the index""" - return await index.get_documents(filter=f'document_id="{digest}"') - - async def remove_label(self, digest: str, label: str, index: Index): - documents = (await self.get_docs_for_digest(digest, index)).results - for document in documents: - document["tags"].remove(label) - - await index.update_documents(documents, primary_key="id") - - async def add_label(self, digest: str, label: str, index: Index): - documents = (await self.get_docs_for_digest(digest, index)).results - for document in documents: - document["tags"].append(label) - - await index.update_documents(documents, primary_key="id") - - async def build( - self, chunks: AsyncGenerator[Tuple[IndexAction, Union[str, Chunk]], None] - ): - """Builds the index, yielding progress as a float between 0 and 1""" - async with Client(get_meilisearch_url()) as search_client: - try: - await search_client.create_index(self.index_name, primary_key="id") - 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"]) - await index.update_filterable_attributes(["tags", "document_id"]) - - i = 0 - GROUP_SIZE = 100 - group = [] - async for action, chunk in chunks: - if action == "compute": - if len(group) < GROUP_SIZE: - group.append(chunk) - continue - - await self.add_chunks( - group, - index, - i, - ) - - i += GROUP_SIZE - group = [] - await asyncio.sleep(0.1) - elif action == "delete": - await self.delete_chunks([chunk], index) - elif action == "add_label": - await self.add_label(chunk, self.tag, index) - elif action == "remove_label": - await self.remove_label(chunk, self.tag, index) - - if len(group) > 0: - await self.add_chunks(group, index, i) - - except Exception as e: - logger.warning(f"Error while building meilisearch index: {e}") - - 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, filter=f'tags IN ["{self.tag}"]' - ) - - 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 diff --git a/archive/server/continuedev/libs/index/indices/mstest.py b/archive/server/continuedev/libs/index/indices/mstest.py deleted file mode 100644 index 2b6a4bdd0..000000000 --- a/archive/server/continuedev/libs/index/indices/mstest.py +++ /dev/null @@ -1,56 +0,0 @@ -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: ,\n errorElement: ,\n children: [\n {\n path: "/index.html",\n element: ,\n },\n {\n path: "/",\n element: ,\n },\n {\n path: "/history",\n element: ,\n },\n {\n path: "/help",\n element: ,\n },\n {\n path: "/settings",\n element: ,\n },\n {\n path: "/models",\n element: ,\n },\n {\n path: "/help",\n element: ,\n },\n {\n path: "/modelconfig/:modelName",\n element: ,\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 \n \n \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 \n \n \n \n \n \n \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()) diff --git a/archive/server/continuedev/libs/index/pipelines/main.py b/archive/server/continuedev/libs/index/pipelines/main.py deleted file mode 100644 index 63ea34df9..000000000 --- a/archive/server/continuedev/libs/index/pipelines/main.py +++ /dev/null @@ -1,70 +0,0 @@ -from typing import List, Optional - -from ....core.sdk import ContinueSDK -from ..chunkers.chunk import Chunk -from ..hyde import code_hyde -from ..indices.chroma_index import ChromaCodebaseIndex -from ..indices.meilisearch_index import MeilisearchCodebaseIndex -from ..rerankers.default import default_reranker_parallel -from ..rerankers.single_token import single_token_reranker_parallel - - -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]: - tag = await sdk.ide.getTag() - chroma_index = ChromaCodebaseIndex(tag, 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 diff --git a/archive/server/continuedev/libs/index/rerankers/default.py b/archive/server/continuedev/libs/index/rerankers/default.py deleted file mode 100644 index 478eb410c..000000000 --- a/archive/server/continuedev/libs/index/rerankers/default.py +++ /dev/null @@ -1,167 +0,0 @@ -import asyncio -import os -from typing import Dict, List - -from ...llm.base import LLM -from ..chunkers.chunk import Chunk - - -async def decide_include_remove( - 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. - - Returns a tuple of (include, remove) where both are lists of chunk ids - """ - # TODO: Go back to using disambiguated names instead of just basename - results_prompt = "\n\n".join( - map( - lambda chunk: f"{os.path.basename(chunk.id)}\n```\n{chunk.content[:500]}\n```", - chunks, - ) - ) - include_prompt = f"""\ -You will be asked to select the most relevant results from a list. You should choose the results that will be most useful in answering the user's request. For each result that you think is important, you should simply say its title on a new line. Here is an example input: -\"\"\" -add.py::0 -``` -def add(a, b): - return a + b -``` - -multiply.py::0 -``` -def multiply(a, b): - return a * b -``` - -subtract.py::0 -``` -def subtract(a, b): - return a - b -``` -\"\"\" -And here is the output you would give if you thought that add.py and subtract.py were the most relevant results: -\"\"\" -add.py::0 -subtract.py::0 -\"\"\" - -Now for the real task, here are the top {len(chunks)} results from the codebase for the user request, "{user_input}": - -{results_prompt} - -Here are the {n} most relevant results listed in the same format from the example:""" - - remove_prompt = f"""\ -You will be asked to select items from a list that are irrelevant to the given request. For each result that is unrelated, you should simply say its title on a new line. Here is an example input: -\"\"\" -add.py::0 -``` -def add(a, b): - return a + b -``` - -multiply.py::0 -``` -def multiply(a, b): - return a * b -``` - -subtract.py::0 -``` -def subtract(a, b): - return a - b -``` -\"\"\" -And here is the output you would give if you thought that add.py and subtract.py were not useful to answer the given request: -\"\"\" -add.py::0 -subtract.py::0 -\"\"\" - -Now for the real task, here are the top {len(chunks)} results from the codebase for the user request, "{user_input}": - -{results_prompt} - -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 = 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, 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 - """ - # Split the results into groups of max size 10 - groups = [] - group = [] - for chunk in chunks: - group.append(chunk) - if len(group) == group_size: - groups.append(group) - group = [] - - if len(group) > 0: - groups.append(group) - - # Gather the ids of chunks that should be removed and included - include = set([]) - remove = set([]) - - tasks = [] - for group in groups: - tasks.append(decide_include_remove(group, user_input, n, model)) - - reranking_results = await asyncio.gather(*tasks) - for rr in reranking_results: - include.update(rr[0]) - remove.update(rr[1]) - - # Determine which documents were repeated, these are probably important - counts_per_document = {} - for chunk in chunks: - if chunk.digest not in counts_per_document: - counts_per_document[chunk.digest] = 0 - counts_per_document[chunk.digest] += 1 - - repeated_documents = set( - filter(lambda x: counts_per_document[x] > 1, counts_per_document) - ) - - not_disqualified = set( - [ - chunk.id - for chunk in chunks - if chunk.id not in remove or chunk.digest in repeated_documents - ] - ) - - included = set([id for id in not_disqualified if chunk.id in include]) - - additional = n - len(included) - for i in range(additional): - if len(not_disqualified) == 0: - break - - # Get an item from not_disqualified - included.add(not_disqualified.pop()) - - if additional < 0: - # We need to remove some items - additional = -additional - for i in range(additional): - if len(included) == 0: - break - - # Remove one - included.pop() - - return [chunk for chunk in chunks if chunk.id in included] diff --git a/archive/server/continuedev/libs/index/rerankers/single_token.py b/archive/server/continuedev/libs/index/rerankers/single_token.py deleted file mode 100644 index bc6855496..000000000 --- a/archive/server/continuedev/libs/index/rerankers/single_token.py +++ /dev/null @@ -1,91 +0,0 @@ -import asyncio -from typing import List - -from ...llm.base import LLM -from ...util.logging import logger -from ..chunkers.chunk import Chunk - -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(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.digest - ) - - if False: - return 0.5 - # 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]] diff --git a/archive/server/continuedev/libs/index/update.py b/archive/server/continuedev/libs/index/update.py deleted file mode 100644 index 041586767..000000000 --- a/archive/server/continuedev/libs/index/update.py +++ /dev/null @@ -1,53 +0,0 @@ -# import faiss -import os -import subprocess -from typing import List - -from dotenv import load_dotenv - -load_dotenv() - -FILE_TYPES_TO_IGNORE = [".pyc", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico"] - - -def filter_ignored_files(files: List[str], root_dir: str): - """Further filter files before indexing.""" - for file in files: - if ( - file.endswith(tuple(FILE_TYPES_TO_IGNORE)) - or file.startswith(".git") - or file.startswith("archive") - ): - continue # nice - yield root_dir + "/" + file - - -def get_git_ignored_files(root_dir: str): - """Get the list of ignored files in a Git repository.""" - try: - output = ( - subprocess.check_output( - ["git", "ls-files", "--ignored", "--others", "--exclude-standard"], - cwd=root_dir, - ) - .strip() - .decode() - ) - return output.split("\n") - except subprocess.CalledProcessError: - return [] - - -def get_all_files(root_dir: str): - """Get a list of all files in a directory.""" - for dir_path, _, file_names in os.walk(root_dir): - for file_name in file_names: - yield os.path.join(os.path.relpath(dir_path, root_dir), file_name) - - -def get_input_files(root_dir: str): - """Get a list of all files in a Git repository that are not ignored.""" - ignored_files = set(get_git_ignored_files(root_dir)) - all_files = set(get_all_files(root_dir)) - nonignored_files = all_files - ignored_files - return filter_ignored_files(nonignored_files, root_dir) diff --git a/archive/server/continuedev/libs/index/vectordb.py b/archive/server/continuedev/libs/index/vectordb.py deleted file mode 100644 index e141eae45..000000000 --- a/archive/server/continuedev/libs/index/vectordb.py +++ /dev/null @@ -1,21 +0,0 @@ -from abc import ABC, abstractmethod -from typing import List -from .chunkers.chunk import Chunk - - -class VectorDB(ABC): - @abstractmethod - def query(query: str, n: int = 4) -> List[Chunk]: - raise NotImplementedError - - @abstractmethod - def insert(chunks: List[Chunk]): - raise NotImplementedError - - -class ChromaVectorDB(VectorDB): - def query(self, query: str, n: int = 4): - raise NotImplementedError - - def insert(self, chunks: List[Chunk]): - raise NotImplementedError diff --git a/archive/server/continuedev/libs/llm/__init__.py b/archive/server/continuedev/libs/llm/__init__.py deleted file mode 100644 index 4503d4064..000000000 --- a/archive/server/continuedev/libs/llm/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -from .anthropic import AnthropicLLM # noqa: F401 -from .ggml import GGML # noqa: F401 -from .google_palm_api import GooglePaLMAPI # noqa: F401 -from .hf_inference_api import HuggingFaceInferenceAPI # noqa: F401 -from .hf_tgi import HuggingFaceTGI # noqa: F401 -from .llamacpp import LlamaCpp # noqa: F401 -from .ollama import Ollama # noqa: F401 -from .openai import OpenAI # noqa: F401 -from .openai_free_trial import OpenAIFreeTrial # noqa: F401 -from .proxy_server import ProxyServer # noqa: F401 -from .queued import QueuedLLM # noqa: F401 -from .replicate import ReplicateLLM # noqa: F401 -from .text_gen_webui import TextGenWebUI # noqa: F401 -from .together import TogetherLLM # noqa: F401 diff --git a/archive/server/continuedev/libs/llm/anthropic.py b/archive/server/continuedev/libs/llm/anthropic.py deleted file mode 100644 index f948b3f46..000000000 --- a/archive/server/continuedev/libs/llm/anthropic.py +++ /dev/null @@ -1,73 +0,0 @@ -from typing import Any, Callable, Coroutine, Optional - -from anthropic import AI_PROMPT, HUMAN_PROMPT, AsyncAnthropic - -from .base import LLM, CompletionOptions -from .prompts.chat import anthropic_template_messages - - -class AnthropicLLM(LLM): - """ - To setup Anthropic, add the following to your `config.json` file: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Anthropic", - "provider": "anthropic", - "model": "claude-2", - "api_key": "YOUR_API_KEY" - }] - } - ``` - - Claude 2 is not yet publicly released. You can request early access [here](https://www.anthropic.com/earlyaccess). - - """ - - api_key: Optional[str] - "Anthropic API key" - - model: str = "claude-2" - - template_messages: Callable = anthropic_template_messages - - class Config: - arbitrary_types_allowed = True - - def start(self, *args, **kwargs): - super().start(*args, **kwargs) - - if self.model == "claude-2": - self.context_length = 100_000 - - def collect_args(self, options: CompletionOptions): - options.stop = None - args = super().collect_args(options) - - if "max_tokens" in args: - args["max_tokens_to_sample"] = args["max_tokens"] - del args["max_tokens"] - if "frequency_penalty" in args: - del args["frequency_penalty"] - if "presence_penalty" in args: - del args["presence_penalty"] - return args - - async def _stream_complete(self, prompt: str, options): - args = self.collect_args(options) - prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}" - - async for chunk in await AsyncAnthropic( - api_key=self.api_key - ).completions.create(prompt=prompt, stream=True, **args): - yield chunk.completion - - async def _complete(self, prompt: str, options) -> Coroutine[Any, Any, str]: - args = self.collect_args(options) - prompt = f"{HUMAN_PROMPT} {prompt} {AI_PROMPT}" - return ( - await AsyncAnthropic(api_key=self.api_key).completions.create( - prompt=prompt, **args - ) - ).completion diff --git a/archive/server/continuedev/libs/llm/base.py b/archive/server/continuedev/libs/llm/base.py deleted file mode 100644 index dc1da9372..000000000 --- a/archive/server/continuedev/libs/llm/base.py +++ /dev/null @@ -1,478 +0,0 @@ -import os -import ssl -from time import time -from typing import Any, AsyncGenerator, Callable, Coroutine, Dict, List, Optional - -import aiohttp -import certifi -from pydantic import Field, validator - -from ...core.config_utils.shared import ( - autodetect_prompt_templates, - autodetect_template_function, -) -from ...core.main import ChatMessage -from ...models.llm import BaseCompletionOptions, CompletionOptions, RequestOptions -from ...models.main import ContinueBaseModel -from ..util.count_tokens import ( - CONTEXT_LENGTH_FOR_MODEL, - DEFAULT_ARGS, - compile_chat_messages, - count_tokens, - format_chat_messages, - prune_raw_prompt_from_top, -) -from ..util.devdata import dev_data_logger -from ..util.logging import logger -from ..util.telemetry import posthog_logger - - -class LLM(ContinueBaseModel): - title: Optional[str] = Field( - default=None, - description="A title that will identify this model in the model selection dropdown", - ) - - unique_id: Optional[str] = Field( - default=None, description="The unique ID of the user." - ) - model: str = Field( - default=..., - description="The name of the model to be used (e.g. gpt-4, codellama)", - ) - - system_message: Optional[str] = Field( - default=None, - description="A system message that will always be followed by the LLM", - ) - - context_length: int = Field( - default=2048, - description="The maximum context length of the LLM in tokens, as counted by count_tokens.", - ) - - completion_options: BaseCompletionOptions = Field( - default=BaseCompletionOptions(), - description="Options for the completion endpoint. Read more about the completion options in the documentation.", - ) - - request_options: RequestOptions = Field( - default=RequestOptions(), - description="Options for the HTTP request to the LLM.", - ) - - prompt_templates: dict = Field( - default=None, - description='A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation. See the documentation for more information.', - ) - - template_messages: Optional[Callable[[List[ChatMessage]], str]] = Field( - default=None, - description="A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format.", - ) - write_log: Optional[Callable[[str], Coroutine]] = Field( - default=None, - description="A function that is called upon every prompt and completion, by default to log to the file which can be viewed by clicking on the magnifying glass.", - ) - llm_request_hook: Optional[Callable[[str, str], Any]] = Field( - default=None, - description="A function that will be called before every request to the LLM. It will be passed the model used (str) and the exact prompt that is sent to the LLM (str).", - ) - - api_key: Optional[str] = Field( - default=None, description="The API key for the LLM provider." - ) - api_base: Optional[str] = Field( - default=None, description="The base URL of the LLM API." - ) - - class Config: - arbitrary_types_allowed = True - extra = "allow" - fields = { - "title": { - "description": "A title that will identify this model in the model selection dropdown" - }, - "system_message": { - "description": "A system message that will always be followed by the LLM" - }, - "context_length": { - "description": "The maximum context length of the LLM in tokens, as counted by count_tokens." - }, - "unique_id": {"description": "The unique ID of the user."}, - "model": { - "description": "The name of the model to be used (e.g. gpt-4, codellama)" - }, - "prompt_templates": { - "description": 'A dictionary of prompt templates that can be used to customize the behavior of the LLM in certain situations. For example, set the "edit" key in order to change the prompt that is used for the /edit slash command. Each value in the dictionary is a string templated in mustache syntax, and filled in at runtime with the variables specific to the situation OR an instance of the PromptTemplate class if you want to control other parameters. See the documentation for more information.' - }, - "template_messages": { - "description": "A function that takes a list of messages and returns a prompt. This ensures that models like llama2, which are trained on specific chat formats, will always receive input in that format." - }, - } - - @validator("template_messages", pre=True, always=True) - def set_template_messages(cls, template_messages, values): - return template_messages or autodetect_template_function(values["model"]) - - @validator("prompt_templates", pre=True, always=True) - def set_prompt_templates(cls, prompt_templates, values): - return prompt_templates or autodetect_prompt_templates(values["model"]) - - def dict(self, **kwargs): - original_dict = super().dict(**kwargs) - original_dict.pop("write_log") - if self.template_messages is not None: - original_dict["template_messages"] = self.template_messages.__name__ - original_dict.pop("unique_id") - original_dict["class_name"] = self.__class__.__name__ - return original_dict - - def start(self, unique_id: Optional[str] = None): - """Start the connection to the LLM.""" - self.unique_id = unique_id - - async def stop(self): - """Stop the connection to the LLM.""" - pass - - _config_system_message: Optional[str] = None - _config_temperature: Optional[float] = None - - def set_main_config_params( - self, system_msg: Optional[str], temperature: Optional[float] - ): - self._config_system_message = system_msg - self._config_temperature = temperature - - def create_client_session(self): - if self.request_options.verify_ssl is False: - return aiohttp.ClientSession( - connector=aiohttp.TCPConnector(verify_ssl=False), - timeout=aiohttp.ClientTimeout(total=self.request_options.timeout), - headers=self.request_options.headers, - trust_env=True, - ) - else: - ca_bundle_path = ( - certifi.where() - if self.request_options.ca_bundle_path is None - else self.request_options.ca_bundle_path - ) - if os.path.exists(ca_bundle_path): - ssl_context = ssl.create_default_context(cafile=ca_bundle_path) - return aiohttp.ClientSession( - connector=aiohttp.TCPConnector(ssl_context=ssl_context), - timeout=aiohttp.ClientTimeout(total=self.request_options.timeout), - headers=self.request_options.headers, - trust_env=True, - ) - else: - logger.warning( - "Could not find CA bundle at %s, using default SSL context", - ca_bundle_path, - ) - return aiohttp.ClientSession( - timeout=aiohttp.ClientTimeout(total=self.request_options.timeout), - headers=self.request_options.headers, - trust_env=True, - ) - - def collect_args(self, options: CompletionOptions) -> Dict[str, Any]: - """Collect the arguments for the LLM.""" - args = {**DEFAULT_ARGS.copy(), "model": self.model} - args.update(options.dict(exclude_unset=True, exclude_none=True)) - return args - - def compile_log_message( - self, prompt: str, completion_options: CompletionOptions - ) -> str: - dict = {"context_length": self.context_length} - dict.update(completion_options.dict(exclude_unset=True, exclude_none=True)) - settings = "\n".join([f"{key}: {value}" for key, value in dict.items()]) - return f"""\ -Settings: -{settings} - -############################################ - -{prompt}""" - - def get_system_message(self) -> Optional[str]: - return ( - self.system_message - if self.system_message is not None - else self._config_system_message - ) - - def compile_chat_messages( - self, - options: CompletionOptions, - msgs: List[ChatMessage], - functions: Optional[List[Any]] = None, - ) -> List[ChatMessage]: - # In case gpt-3.5-turbo-16k or something else is specified that has longer context_length - context_length = self.context_length - if options.model != self.model and options.model in CONTEXT_LENGTH_FOR_MODEL: - context_length = CONTEXT_LENGTH_FOR_MODEL[options.model] - - return compile_chat_messages( - model_name=options.model, - msgs=msgs, - context_length=context_length, - max_tokens=options.max_tokens, - functions=functions, - system_message=self.get_system_message(), - ) - - def template_prompt_like_messages(self, prompt: str) -> str: - if self.template_messages is None: - return prompt - - msgs = [ChatMessage(role="user", content=prompt, summary=prompt)] - - if system_message := self.get_system_message(): - msgs.insert( - 0, - ChatMessage(role="system", content=system_message, summary=""), - ) - - return self.template_messages(msgs) - - def log_tokens_generated(self, model: str, completion: str): - tokens = self.count_tokens(completion) - dev_data_logger.capture( - "tokens_generated", - {"model": model, "tokens": tokens, "model_class": self.__class__.__name__}, - ) - posthog_logger.capture_event( - "tokens_generated", - {"model": model, "tokens": tokens, "model_class": self.__class__.__name__}, - ) - - async def stream_complete( - self, - prompt: str, - raw: bool = False, - model: Optional[str] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - top_k: Optional[int] = None, - presence_penalty: Optional[float] = None, - frequency_penalty: Optional[float] = None, - stop: Optional[List[str]] = None, - max_tokens: Optional[int] = None, - functions: Optional[List[Any]] = None, - log: bool = True, - ) -> AsyncGenerator[str, None]: - """Yield completion response, either streamed or not.""" - options = CompletionOptions( - model=model or self.model, - temperature=temperature or self.completion_options.temperature, - top_p=top_p or self.completion_options.top_p, - top_k=top_k or self.completion_options.top_k, - presence_penalty=presence_penalty - or self.completion_options.presence_penalty, - frequency_penalty=frequency_penalty - or self.completion_options.frequency_penalty, - stop=stop or self.completion_options.stop, - max_tokens=max_tokens or self.completion_options.max_tokens, - functions=functions, - ) - - prompt = prune_raw_prompt_from_top( - self.model, self.context_length, prompt, options.max_tokens - ) - - if not raw: - prompt = self.template_prompt_like_messages(prompt) - - if log: - if self.write_log: - await self.write_log(self.compile_log_message(prompt, options)) - if self.llm_request_hook: - self.llm_request_hook(options.model, prompt) - - completion = "" - async for chunk in self._stream_complete(prompt=prompt, options=options): - yield chunk - completion += chunk - - # if log: - # self.write_log(f"Completion: \n\n{completion}") - - self.log_tokens_generated(options.model, completion) - - async def complete( - self, - prompt: str, - raw: bool = False, - model: Optional[str] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - top_k: Optional[int] = None, - presence_penalty: Optional[float] = None, - frequency_penalty: Optional[float] = None, - stop: Optional[List[str]] = None, - max_tokens: Optional[int] = None, - functions: Optional[List[Any]] = None, - log: bool = True, - ) -> str: - """Yield completion response, either streamed or not.""" - options = CompletionOptions( - model=model or self.model, - temperature=temperature or self.completion_options.temperature, - top_p=top_p or self.completion_options.top_p, - top_k=top_k or self.completion_options.top_k, - presence_penalty=presence_penalty - or self.completion_options.presence_penalty, - frequency_penalty=frequency_penalty - or self.completion_options.frequency_penalty, - stop=stop or self.completion_options.stop, - max_tokens=max_tokens or self.completion_options.max_tokens, - functions=functions, - ) - - prompt = prune_raw_prompt_from_top( - self.model, self.context_length, prompt, options.max_tokens - ) - - if not raw: - prompt = self.template_prompt_like_messages(prompt) - - if log: - if self.write_log: - await self.write_log(self.compile_log_message(prompt, options)) - if self.llm_request_hook: - self.llm_request_hook(options.model, prompt) - - completion = await self._complete(prompt=prompt, options=options) - - # if log: - # self.write_log(f"Completion: \n\n{completion}") - - self.log_tokens_generated(options.model, completion) - - return completion - - async def stream_chat( - self, - messages: List[ChatMessage], - model: Optional[str] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - top_k: Optional[int] = None, - presence_penalty: Optional[float] = None, - frequency_penalty: Optional[float] = None, - stop: Optional[List[str]] = None, - max_tokens: Optional[int] = None, - functions: Optional[List[Any]] = None, - log: bool = True, - ) -> AsyncGenerator[ChatMessage, None]: - """Yield completion response, either streamed or not.""" - options = CompletionOptions( - model=model or self.model, - temperature=temperature or self.completion_options.temperature, - top_p=top_p or self.completion_options.top_p, - top_k=top_k or self.completion_options.top_k, - presence_penalty=presence_penalty - or self.completion_options.presence_penalty, - frequency_penalty=frequency_penalty - or self.completion_options.frequency_penalty, - stop=stop or self.completion_options.stop, - max_tokens=max_tokens or self.completion_options.max_tokens, - functions=functions, - ) - - messages = self.compile_chat_messages( - options=options, msgs=messages, functions=functions - ) - if self.template_messages is not None: - prompt = self.template_messages(messages) - else: - prompt = format_chat_messages(messages) - - if log: - if self.write_log: - await self.write_log(self.compile_log_message(prompt, options)) - if self.llm_request_hook: - self.llm_request_hook(options.model, prompt) - - completion = "" - - # Use the template_messages function if it exists and do a raw completion - ti = time() - tf = None - if self.template_messages is None: - async for chunk in self._stream_chat(messages=messages, options=options): - yield chunk - if chunk.content: - completion += chunk.content - if tf is None: - tf = time() - ttft = tf - ti - posthog_logger.capture_event( - "time_to_first_token", - { - "model": self.model, - "model_class": self.__class__.__name__, - "time": ttft, - "tokens": sum( - self.count_tokens(m.content or "") for m in messages - ), - }, - ) - - else: - async for chunk in self._stream_complete(prompt=prompt, options=options): - yield ChatMessage(role="assistant", content=chunk, summary=chunk) - completion += chunk - if tf is None: - tf = time() - ttft = tf - ti - posthog_logger.capture_event( - "time_to_first_token", - { - "model": self.model, - "model_class": self.__class__.__name__, - "time": ttft, - "tokens": self.count_tokens(prompt), - }, - ) - - # if log: - # self.write_log(f"Completion: \n\n{completion}") - - self.log_tokens_generated(options.model, completion) - - def _stream_complete( - self, prompt, options: CompletionOptions - ) -> AsyncGenerator[str, None]: - """Stream the completion through generator.""" - raise NotImplementedError - - async def _complete(self, prompt: str, options: CompletionOptions) -> str: - """Return the completion of the text with the given temperature.""" - completion = "" - async for chunk in self._stream_complete(prompt=prompt, options=options): - completion += chunk - - return completion - - async def _stream_chat( - self, messages: List[ChatMessage], options: CompletionOptions - ) -> AsyncGenerator[ChatMessage, None]: - """Stream the chat through generator.""" - if self.template_messages is None: - raise NotImplementedError( - "You must either implement template_messages or _stream_chat" - ) - - async for chunk in self._stream_complete( - prompt=self.template_messages(messages), options=options - ): - yield ChatMessage(role="assistant", content=chunk, summary=chunk) - - def count_tokens(self, text: str): - """Return the number of tokens in the given text.""" - return count_tokens(text, self.model) diff --git a/archive/server/continuedev/libs/llm/continue_test.py b/archive/server/continuedev/libs/llm/continue_test.py deleted file mode 100644 index 2e32c8628..000000000 --- a/archive/server/continuedev/libs/llm/continue_test.py +++ /dev/null @@ -1,92 +0,0 @@ -import json -import aiohttp -import requests - -IP = "129.213.24.72" - - -def requests_test(): - resp = requests.post( - f"http://{IP}:8000/v1/completions", - json={ - "prompt": "Hello! What is your name?", - "model": "mistralai/Mistral-7B-Instruct-v0.1", - }, - ) - print(resp.json()) - - -async def basic_test(): - async with aiohttp.ClientSession() as client_session: - async with client_session.post( - f"http://{IP}:8000/v1/completions", - json={ - "prompt": "Hello! What is your name?", - "model": "mistralai/Mistral-7B-Instruct-v0.1", - }, - ) as resp: - j = await resp.json() - print(j) - return j - - -async def streaming_test(): - headers = {"Content-Type": "application/json"} - - async with aiohttp.ClientSession( - timeout=aiohttp.ClientTimeout(total=3600), - headers=headers, - trust_env=True, - ) as client_session: - async with client_session.post( - f"http://{IP}:8000/v1/completions", - json={ - "prompt": "Hello! What is your name?", - "model": "mistralai/Mistral-7B-Instruct-v0.1", - "stream": True, - }, - headers=headers, - ) as resp: - if resp.status != 200: - raise Exception(f"Error calling /completions endpoint: {resp.status}") - - async for line in resp.content.iter_any(): - if line: - chunks = line.decode("utf-8") - for chunk in chunks.split("\n"): - if ( - chunk.startswith(": ping - ") - or chunk.startswith("data: [DONE]") - or chunk.strip() == "" - ): - continue - elif chunk.startswith("data: "): - chunk = chunk[6:] - try: - j = json.loads(chunk) - except Exception: - continue - if ( - "choices" in j - and len(j["choices"]) > 0 - and "text" in j["choices"][0] - ): - yield j["choices"][0]["text"] - - -async def main(): - # Test requests (you mentioned that this worked before) - requests_test() - - # Test non-streaming response - await basic_test() - - # Test streaming response, like what happens in Continue - async for i in streaming_test(): - print(i) - - -if __name__ == "__main__": - import asyncio - - asyncio.run(main()) diff --git a/archive/server/continuedev/libs/llm/ggml.py b/archive/server/continuedev/libs/llm/ggml.py deleted file mode 100644 index 7365c5a02..000000000 --- a/archive/server/continuedev/libs/llm/ggml.py +++ /dev/null @@ -1,255 +0,0 @@ -import json -from typing import Any, AsyncGenerator, Coroutine, List, Literal, Optional - -from pydantic import Field, validator - -from ...core.main import ChatMessage, ContinueCustomException -from ..util.logging import logger -from .base import LLM, CompletionOptions -from .openai import CHAT_MODELS - - -class GGML(LLM): - """ - See our [5 minute quickstart](https://github.com/continuedev/ggml-server-example) to run any model locally with ggml. While these models don't yet perform as well, they are free, entirely private, and run offline. - - You can also use this class for [LM Studio](https://lmstudio.ai). - - Once the model is running on localhost:8000, change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "GGML", - "provider": "openai-aiohttp", - "model": "MODEL_NAME", - "api_base": "http://localhost:8000" - }] - } - ``` - """ - - api_base: Optional[str] = Field( - "http://127.0.0.1:8000", - description="URL of the OpenAI-compatible server where the model is being served", - ) - - @validator("api_base", pre=True, always=True) - def set_api_base(cls, api_base): - return api_base or "http://127.0.0.1:8000" - - model: str = Field( - "ggml", description="The name of the model to use (optional for the GGML class)" - ) - - api_type: Optional[Literal["azure", "openai"]] = Field( - default=None, description="OpenAI API type." - ) - - api_version: Optional[str] = Field( - default=None, - description="OpenAI API version. For use with Azure OpenAI Service.", - ) - - engine: Optional[str] = Field( - default=None, description="OpenAI engine. For use with Azure OpenAI Service." - ) - - chat_endpoint: str = Field( - default="chat/completions", - description="The endpoint to call for chat completions", - ) - - completions_endpoint: str = Field( - default="completions", description="The endpoint to call for chat completions" - ) - - class Config: - arbitrary_types_allowed = True - - def get_headers(self): - headers = { - "Content-Type": "application/json", - } - if self.api_key is not None: - if self.api_type == "azure": - headers["api-key"] = self.api_key - else: - headers["Authorization"] = f"Bearer {self.api_key}" - - return headers - - def get_full_server_url(self, endpoint: str): - endpoint = endpoint.lstrip("/").rstrip("/") - - if self.api_type == "azure": - if self.engine is None or self.api_version is None or self.api_base is None: - raise Exception( - "For Azure OpenAI Service, you must specify engine, api_version, and api_base." - ) - - return f"{self.api_base}/openai/deployments/{self.engine}/{endpoint}?api-version={self.api_version}" - else: - return f"{self.api_base}/v1/{endpoint}" - - async def _raw_stream_complete(self, prompt, options): - args = self.collect_args(options) - - async with self.create_client_session() as client_session: - async with client_session.post( - self.get_full_server_url(endpoint=self.completions_endpoint), - json={ - "prompt": prompt, - "stream": True, - **args, - }, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - if resp.status != 200: - raise Exception( - f"Error calling /completions endpoint: {resp.status}" - ) - - async for line in resp.content.iter_any(): - if line: - chunks = line.decode("utf-8") - for chunk in chunks.split("\n"): - if ( - chunk.startswith(": ping - ") - or chunk.startswith("data: [DONE]") - or chunk.strip() == "" - ): - continue - elif chunk.startswith("data: "): - chunk = chunk[6:] - try: - j = json.loads(chunk) - except Exception: - continue - if ( - "choices" in j - and len(j["choices"]) > 0 - and "text" in j["choices"][0] - ): - yield j["choices"][0]["text"] - - async def _stream_chat( - self, messages: List[ChatMessage], options - ) -> AsyncGenerator[ChatMessage, None]: - args = self.collect_args(options) - - async def generator() -> AsyncGenerator[Any, None]: - async with self.create_client_session() as client_session: - async with client_session.post( - self.get_full_server_url(endpoint=self.chat_endpoint), - json={ - "messages": [msg.to_dict() for msg in messages], - "stream": True, - **args, - }, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - if resp.status != 200: - detail = ( - f"Error calling /chat/completions endpoint: {resp.status}" - ) - try: - json_detail = await resp.json() - if ( - "detail" in json_detail - and "error" in json_detail["detail"] - and "message" in json_detail["detail"]["error"] - ): - detail = json_detail["detail"]["error"]["message"] - elif "message" in json_detail: - detail = json_detail["message"] - elif "detail" in json_detail: - detail = json_detail["detail"] - except Exception: - pass - - raise ContinueCustomException( - title=f"Error calling /chat/completions endpoint: {resp.status}", - message=detail, - ) - - async for line, end in resp.content.iter_chunks(): - json_chunk = line.decode("utf-8") - chunks = json_chunk.split("\n") - for chunk in chunks: - if ( - chunk.strip() == "" - or json_chunk.startswith(": ping - ") - or json_chunk.startswith("data: [DONE]") - ): - continue - try: - delta = json.loads(chunk[6:])["choices"][0]["delta"] - yield ChatMessage( - role="assistant", content=delta.get("content", "") - ) - except Exception: - pass - - # Because quite often the first attempt fails, and it works thereafter - try: - async for chunk in generator(): - yield chunk - except Exception as e: - logger.warning(f"Error calling /chat/completions endpoint: {e}") - async for chunk in generator(): - yield chunk - - async def _raw_complete(self, prompt: str, options) -> Coroutine[Any, Any, str]: - args = self.collect_args(options) - - async with self.create_client_session() as client_session: - async with client_session.post( - self.get_full_server_url(endpoint=self.completions_endpoint), - json={ - "prompt": prompt, - **args, - }, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - if resp.status != 200: - raise Exception( - f"Error calling /completions endpoint: {resp.status}" - ) - - text = await resp.text() - try: - completion = json.loads(text)["choices"][0]["text"] - return completion - except Exception as e: - raise Exception( - f"Error calling /completions endpoint: {e}\n\nResponse text: {text}" - ) - - async def _complete(self, prompt: str, options: CompletionOptions): - completion = "" - if self.model in CHAT_MODELS: - async for chunk in self._stream_chat( - [ChatMessage(role="user", content=prompt)], options - ): - completion += chunk.content - - else: - async for chunk in self._raw_stream_complete(prompt, options): - completion += chunk - - return completion - - async def _stream_complete(self, prompt, options: CompletionOptions): - if self.model in CHAT_MODELS: - async for chunk in self._stream_chat( - [ChatMessage(role="user", content=prompt)], options - ): - yield chunk.content - - else: - async for chunk in self._raw_stream_complete(prompt, options): - yield chunk diff --git a/archive/server/continuedev/libs/llm/google_palm_api.py b/archive/server/continuedev/libs/llm/google_palm_api.py deleted file mode 100644 index 71f15e156..000000000 --- a/archive/server/continuedev/libs/llm/google_palm_api.py +++ /dev/null @@ -1,50 +0,0 @@ -from typing import List - -import requests -from pydantic import Field - -from ...core.main import ChatMessage -from .base import LLM - - -class GooglePaLMAPI(LLM): - """ - The Google PaLM API is currently in public preview, so production applications are not supported yet. However, you can [create an API key in Google MakerSuite](https://makersuite.google.com/u/2/app/apikey) and begin trying out the `chat-bison-001` model. Change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Chat Bison", - "provider": "google-palm", - "model": "chat-bison-001", - "api_key": "YOUR_API_KEY" - }] - } - ``` - """ - - api_key: str = Field(..., description="Google PaLM API key") - - model: str = "chat-bison-001" - - async def _stream_complete(self, prompt, options): - api_url = f"https://generativelanguage.googleapis.com/v1beta2/models/{self.model}:generateMessage?key={self.api_key}" - body = {"prompt": {"messages": [{"content": prompt}]}} - response = requests.post(api_url, json=body) - data = response.json() - if "candidates" in data: - yield data["candidates"][0]["content"] - - async def _stream_chat(self, messages: List[ChatMessage], options): - msg_lst = [] - for message in messages: - msg_lst.append({"content": message.content}) - - api_url = f"https://generativelanguage.googleapis.com/v1beta2/models/{self.model}:generateMessage?key={self.api_key}" - body = {"prompt": {"messages": msg_lst}} - response = requests.post(api_url, json=body) - data = response.json() - if "candidates" in data: - yield ChatMessage( - role="assistant", content=data["candidates"][0]["content"] - ) \ No newline at end of file diff --git a/archive/server/continuedev/libs/llm/hf_inference_api.py b/archive/server/continuedev/libs/llm/hf_inference_api.py deleted file mode 100644 index 25cfe3ed9..000000000 --- a/archive/server/continuedev/libs/llm/hf_inference_api.py +++ /dev/null @@ -1,66 +0,0 @@ -from typing import Optional - -from huggingface_hub import InferenceClient -from pydantic import Field - -from .base import LLM, CompletionOptions - - -class HuggingFaceInferenceAPI(LLM): - """ - Hugging Face Inference API is a great option for newly released language models. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Hugging Face Inference API", - "provider": "huggingface-inference-api", - "model": "MODEL_NAME", - "api_key": "YOUR_HF_TOKEN", - "api_base": "INFERENCE_API_ENDPOINT_URL" - }] - } - ``` - """ - - model: str = Field( - "Hugging Face Inference API", - description="The name of the model to use (optional for the HuggingFaceInferenceAPI class)", - ) - api_key: str = Field(..., description="Your Hugging Face API token") - api_base: Optional[str] = Field( - None, description="Your Hugging Face Inference API endpoint URL" - ) - - class Config: - arbitrary_types_allowed = True - - def collect_args(self, options: CompletionOptions): - options.stop = None - args = super().collect_args(options) - - if "max_tokens" in args: - args["max_new_tokens"] = args["max_tokens"] - del args["max_tokens"] - if "stop" in args: - args["stop_sequences"] = args["stop"] - del args["stop"] - - return args - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - client = InferenceClient(self.api_base, token=self.api_key) - - stream = client.text_generation(prompt, stream=True, details=True, **args) - - for r in stream: - # skip special tokens - if r.token.special: - continue - # stop if we encounter a stop sequence - if options.stop is not None: - if r.token.text in options.stop: - break - yield r.token.text diff --git a/archive/server/continuedev/libs/llm/hf_tgi.py b/archive/server/continuedev/libs/llm/hf_tgi.py deleted file mode 100644 index f8faec895..000000000 --- a/archive/server/continuedev/libs/llm/hf_tgi.py +++ /dev/null @@ -1,65 +0,0 @@ -import json -from typing import Any, Optional - -from pydantic import Field, validator - -from ..util.count_tokens import DEFAULT_MAX_TOKENS -from .base import LLM, CompletionOptions - - -class HuggingFaceTGI(LLM): - model: str = "huggingface-tgi" - api_base: Optional[str] = Field( - "http://127.0.0.1:8080", description="URL of your TGI server" - ) - - @validator("api_base", pre=True, always=True) - def set_api_base(cls, api_base): - return api_base or "http://127.0.0.1:8080" - - class Config: - arbitrary_types_allowed = True - - def collect_args(self, options: CompletionOptions) -> Any: - args = super().collect_args(options) - args = { - **args, - "max_new_tokens": args.get("max_tokens", DEFAULT_MAX_TOKENS), - "best_of": 1, - } - args.pop("max_tokens", None) - args.pop("model", None) - args.pop("functions", None) - return args - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - async with self.create_client_session() as client_session: - async with client_session.post( - f"{self.api_base}/generate_stream", - json={"inputs": prompt, "parameters": args}, - headers={"Content-Type": "application/json"}, - proxy=self.request_options.proxy, - ) as resp: - async for line in resp.content.iter_any(): - if line: - text = line.decode("utf-8") - chunks = text.split("\n") - - for chunk in chunks: - if chunk.startswith("data: "): - chunk = chunk[len("data: ") :] - elif chunk.startswith("data:"): - chunk = chunk[len("data:") :] - - if chunk.strip() == "": - continue - - try: - json_chunk = json.loads(chunk) - except Exception as e: - print(f"Error parsing JSON: {e}") - continue - - yield json_chunk["token"]["text"] diff --git a/archive/server/continuedev/libs/llm/llamacpp.py b/archive/server/continuedev/libs/llm/llamacpp.py deleted file mode 100644 index 891d87a61..000000000 --- a/archive/server/continuedev/libs/llm/llamacpp.py +++ /dev/null @@ -1,83 +0,0 @@ -import json -from typing import Any, Dict, Optional - -from pydantic import Field, validator - -from .base import LLM - - -class LlamaCpp(LLM): - """ - Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0: - - ```shell - .\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\\meta\\llama\\codellama-7b-instruct.Q8_0.gguf - ``` - - After it's up and running, change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Llama CPP", - "provider": "llama.cpp", - "model": "MODEL_NAME", - "api_base": "http://localhost:8080" - }] - } - ``` - """ - - model: str = "llamacpp" - api_base: Optional[str] = Field( - "http://127.0.0.1:8080", description="URL of the server" - ) - - @validator("api_base", pre=True, always=True) - def set_api_base(cls, api_base): - return api_base or "http://127.0.0.1:8080" - - llama_cpp_args: Dict[str, Any] = Field( - {"stop": ["[INST]"]}, - description="A list of additional arguments to pass to llama.cpp. See https://github.com/ggerganov/llama.cpp/tree/master/examples/server#api-endpoints for the complete catalog of options.", - ) - - class Config: - arbitrary_types_allowed = True - - def collect_args(self, options) -> Any: - args = super().collect_args(options) - if "max_tokens" in args: - args["n_predict"] = args["max_tokens"] - del args["max_tokens"] - if "frequency_penalty" in args: - del args["frequency_penalty"] - if "presence_penalty" in args: - del args["presence_penalty"] - - for k, v in self.llama_cpp_args.items(): - if k not in args: - args[k] = v - - return args - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - headers = {"Content-Type": "application/json"} - - async def server_generator(): - async with self.create_client_session() as client_session: - async with client_session.post( - f"{self.api_base}/completion", - json={"prompt": prompt, "stream": True, **args}, - headers=headers, - proxy=self.request_options.proxy, - ) as resp: - async for line in resp.content: - content = line.decode("utf-8") - if content.strip() == "": - continue - yield json.loads(content[6:])["content"] - - async for chunk in server_generator(): - yield chunk diff --git a/archive/server/continuedev/libs/llm/llamafile.py b/archive/server/continuedev/libs/llm/llamafile.py deleted file mode 100644 index ce25ed460..000000000 --- a/archive/server/continuedev/libs/llm/llamafile.py +++ /dev/null @@ -1,116 +0,0 @@ -import asyncio -import socket -import subprocess -from typing import List, Optional - -from continuedev.core.main import ChatMessage, ContinueCustomException -from continuedev.models.llm import CompletionOptions - -from .llamacpp import LlamaCpp - - -def test_port(PORT): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - s.bind(("", PORT)) ## Try to open port - except OSError as e: - if e.errno == 98: ## Errorno 98 means address already bound - return True - elif e.errno == 48: ## Errorno 48 means address already in use - return True - return False - s.close() - return False - - -STARTUP_DELAY = 3.0 - - -class Llamafile(LlamaCpp): - """ - A [llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) is a self-contained binary that can run an open-source LLM. You can configure this provider in your config.json as follows: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Llamafile", - "provider": "llamafile", - "model": "mistral-7b", - }] - } - ``` - - Optionally, you can set the `llamafile_command` property, which will be run to start the llamafile if it isn't already running on port 8080. Be sure to use an absolute path to the llamafile binary. For example: `/Users/yourusername/mistral-7b-instruct-v0.1-Q4_K_M-server.llamafile`. - """ - - llamafile_command: Optional[str] = None - - llamafile_process: Optional[subprocess.Popen] = None - - def check_and_start(self, should_raise: bool) -> bool: - # Try to start the llamafile if it's not already started on port 8080 - if not self.llamafile_command: - return False - - port = int((self.api_base or ":8080").split(":")[-1]) - - if not test_port(port): - if should_raise and self.llamafile_process: - # If already tried to start and it isn't started, raise an exception - _, err = self.llamafile_process.communicate() - err = err.decode("utf-8") if err else "" - err_string = f"Error starting llamafile\n\n{err}" - raise ContinueCustomException(err_string, err_string) - - import threading - - def process_run(): - p = subprocess.Popen( - self.llamafile_command.split(" "), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - close_fds=True, - start_new_session=True, - shell=True, - ) - self.llamafile_process = p - - t = threading.Thread(target=process_run) - t.start() - - return True - - return False - - def start(self, unique_id: str | None = None): - super().start(unique_id) - self.check_and_start(False) - - def dict(self, **kwargs): - d = super().dict(**kwargs) - if "llamafile_process" in d: - del d["llamafile_process"] - - return d - - async def _stream_chat( - self, messages: List[ChatMessage], options: CompletionOptions - ): - if self.check_and_start(True): - await asyncio.sleep(STARTUP_DELAY) - - async for message in super()._stream_chat(messages, options): - yield message - - async def _stream_complete(self, prompt, options): - if self.check_and_start(True): - await asyncio.sleep(STARTUP_DELAY) - - async for message in super()._stream_complete(prompt, options): - yield message - - async def _complete(self, prompt: str, options: CompletionOptions): - if self.check_and_start(True): - await asyncio.sleep(STARTUP_DELAY) - - return await super()._complete(prompt, options) diff --git a/archive/server/continuedev/libs/llm/lmstudio.py b/archive/server/continuedev/libs/llm/lmstudio.py deleted file mode 100644 index 46ec43e71..000000000 --- a/archive/server/continuedev/libs/llm/lmstudio.py +++ /dev/null @@ -1,7 +0,0 @@ -from .ggml import GGML - - -class LMStudio(GGML): - """LMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.""" - - api_base: str = "http://127.0.0.1:1234" diff --git a/archive/server/continuedev/libs/llm/ollama.py b/archive/server/continuedev/libs/llm/ollama.py deleted file mode 100644 index dbf8491d1..000000000 --- a/archive/server/continuedev/libs/llm/ollama.py +++ /dev/null @@ -1,138 +0,0 @@ -import json -from typing import Any, Dict, Optional - -import requests -from pydantic import Field, validator - -from ...core.main import ContinueCustomException -from ..util.logging import logger -from .base import LLM, CompletionOptions - - -class Ollama(LLM): - """ - [Ollama](https://ollama.ai/) is an application for Mac and Linux that makes it easy to locally run open-source models, including Llama-2. Download the app from the website, and it will walk you through setup in a couple of minutes. You can also read more in their [README](https://github.com/jmorganca/ollama). Continue can then be configured to use the `Ollama` LLM class: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Ollama", - "provider": "ollama", - "model": "llama2-7b", - }] - } - ``` - """ - - model: str = "llama2" - api_base: Optional[str] = Field( - "http://127.0.0.1:11434", description="URL of the Ollama server" - ) - - @validator("api_base", pre=True, always=True) - def set_api_base(cls, api_base): - return api_base or "http://127.0.0.1:11434" - - class Config: - arbitrary_types_allowed = True - - def collect_args(self, options: CompletionOptions) -> Dict[str, Any]: - return { - "temperature": options.temperature, - "top_p": options.top_p, - "top_k": options.top_k, - "num_predict": options.max_tokens, - "stop": options.stop, - "num_ctx": self.context_length, - } - - def get_model_name(self): - return { - "mistral-7b": "mistral:7b", - "llama2-7b": "llama2:7b", - "llama2-13b": "llama2:13b", - "codellama-7b": "codellama:7b", - "codellama-13b": "codellama:13b", - "codellama-34b": "codellama:34b", - "phind-codellama-34b": "phind-codellama:34b-v2", - "wizardcoder-7b": "wizardcoder:7b-python", - "wizardcoder-13b": "wizardcoder:13b-python", - "wizardcoder-34b": "wizardcoder:34b-python", - "zephyr-7b": "zephyr:7b", - "codeup-13b": "codeup:13b", - "deepseek-1b": "deepseek-coder:1.3b", - "deepseek-7b": "deepseek-coder:6.7b", - "deepseek-33b": "deepseek-coder:33b", - "neural-chat-7b": "neural-chat:7b-v3.3", - "phi-2.7b": "phi:2.7b" - }.get(self.model, self.model) - - def start(self, *args, **kwargs): - super().start(*args, **kwargs) - try: - requests.post( - f"{self.api_base}/api/generate", - json={ - "prompt": "", - "model": self.get_model_name(), - }, - ) - except Exception as e: - logger.warning(f"Error pre-loading Ollama model: {e}") - - async def get_downloaded_models(self): - async with self.create_client_session() as session: - async with session.get( - f"{self.api_base}/api/tags", - proxy=self.request_options.proxy, - ) as resp: - js_data = await resp.json() - return list(map(lambda x: x["name"], js_data["models"])) - - async def _stream_complete(self, prompt, options): - async with self.create_client_session() as session: - async with session.post( - f"{self.api_base}/api/generate", - json={ - "prompt": prompt, - "raw": True, - "model": self.get_model_name(), - "options": self.collect_args(options), - }, - proxy=self.request_options.proxy, - ) as resp: - if resp.status == 400: - txt = await resp.text() - extra_msg = "" - if "no such file" in txt: - extra_msg = f"\n\nThis means that the model '{self.get_model_name()}' is not downloaded.\n\nYou have the following models downloaded: {', '.join(await self.get_downloaded_models())}.\n\nTo download this model, run `ollama run {self.get_model_name()}` in your terminal." - raise ContinueCustomException( - f"Ollama returned an error: {txt}{extra_msg}", - "Invalid request to Ollama", - ) - elif resp.status == 404: - model_name = self.get_model_name() - raise ContinueCustomException( - f"Ollama returned 404. Make sure the server is running and '{model_name}' is downloaded with `ollama run {model_name}`.\n\n{await resp.text()}", - f"Ollama returned 404. Make sure the server is running and '{model_name}' is downloaded with `ollama run {model_name}`.", - ) - elif resp.status != 200: - raise ContinueCustomException( - f"Ollama returned an error: {await resp.text()}", - f"Ollama returned an error: {await resp.text()}", - ) - async for line in resp.content.iter_any(): - if line: - json_chunk = line.decode("utf-8") - chunks = json_chunk.split("\n") - for chunk in chunks: - if chunk.strip() != "": - try: - j = json.loads(chunk) - except Exception as e: - logger.warning( - f"Error parsing Ollama response: {e} {chunk}" - ) - continue - if "response" in j: - yield j["response"] diff --git a/archive/server/continuedev/libs/llm/openai.py b/archive/server/continuedev/libs/llm/openai.py deleted file mode 100644 index 1a86b9d96..000000000 --- a/archive/server/continuedev/libs/llm/openai.py +++ /dev/null @@ -1,227 +0,0 @@ -import asyncio -from contextlib import asynccontextmanager -from typing import AsyncGenerator, List, Literal, Optional - -import httpx -import litellm -from litellm import acompletion -from pydantic import Field, validator - -from ...core.main import ChatMessage -from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL -from .base import LLM - -CHAT_MODELS = { - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-1106-preview", -} -NON_CHAT_MODELS = { - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "code-davinci-002", - "babbage-002", - "davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - "davinci", - "curie", - "babbage", - "ada", -} - - -class OpenAI(LLM): - """ - The OpenAI class can be used to access OpenAI models like GPT-4, GPT-4 Turbo, and GPT-3.5 Turbo. - - ### Azure OpenAI Service - - If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant. After applying for access [here](https://azure.microsoft.com/en-us/products/ai-services/openai-service), you will typically hear back within only a few days. Once you have access, set up a model in `config.json` like so: - - ```json - "models": [{ - "title": "Azure OpenAI", - "provider": "openai", - "model": "gpt-4", - "api_base": "https://my-azure-openai-instance.openai.azure.com/", - "engine": "my-azure-openai-deployment", - "api_version": "2023-07-01-preview", - "api_type": "azure", - "api_key": "" - }] - ``` - - The easiest way to find this information is from the chat playground in the Azure OpenAI portal. Under the "Chat Session" section, click "View Code" to see each of these parameters. - - ### OpenAI compatible servers / APIs - - OpenAI compatible servers - - [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation) - - [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md) - - [LocalAI](https://localai.io/basics/getting_started/) - - [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server) - - OpenAI compatible APIs - - [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) - - [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) - - If you are [using an OpenAI compatible server / API](../../model-setup/select-provider#local), you can change the `api_base` like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "OpenAI-compatible server / API", - "provider": "openai", - "model": "MODEL_NAME", - "api_key": "EMPTY", - "api_base": "http://localhost:8000" - }] - } - ``` - """ - - api_key: str = Field( - ..., - description="OpenAI API key", - ) - - api_base: Optional[str] = Field(default=None, description="OpenAI API base URL.") - - api_type: Optional[Literal["azure", "openai"]] = Field( - default=None, description="OpenAI API type." - ) - - api_version: Optional[str] = Field( - default=None, - description="OpenAI API version. For use with Azure OpenAI Service.", - ) - - engine: Optional[str] = Field( - default=None, description="OpenAI engine. For use with Azure OpenAI Service." - ) - - use_legacy_completions_endpoint: bool = Field( - default=False, - description="Manually specify to use the legacy completions endpoint instead of chat completions.", - ) - - @validator("context_length") - def context_length_for_model(cls, v, values): - return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096) - - def start(self, unique_id: Optional[str] = None): - super().start(unique_id=unique_id) - - if self.context_length is None: - self.context_length = CONTEXT_LENGTH_FOR_MODEL.get(self.model, 4096) - - def collect_args(self, options): - args = super().collect_args(options) - if self.api_type == "azure": - assert self.engine is not None, "engine must be specified for Azure API" - args["model"] = f"azure/{self.engine}" - args["api_version"] = self.api_version - - args["api_key"] = self.api_key - args["api_base"] = self.api_base - - if not args["model"].endswith("0613") and "functions" in args: - del args["functions"] - - return args - - def httpx_client(self) -> httpx.AsyncClient: - args = {} - if timeout := self.request_options.timeout: - args["timeout"] = httpx.Timeout(timeout) - - if verify_ssl := self.request_options.verify_ssl: - args["verify"] = verify_ssl - - if ca_bundle_path := self.request_options.ca_bundle_path: - args["cert"] = ca_bundle_path - - if proxy := self.request_options.proxy: - args["proxies"] = {"https": proxy, "http": proxy} - - if headers := self.request_options.headers: - args["headers"] = headers - - return httpx.AsyncClient(**args) - - @asynccontextmanager - async def httpx_client_context(self): - client = self.httpx_client() - litellm.aclient_session = client - try: - yield - finally: - await client.aclose() - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - async with self.httpx_client_context(): - resp = await acompletion( - messages=[{"content": prompt, "role": "user"}], - **args, - stream=True, - ) - async for chunk in resp: - if chunk.choices[0].delta.content is None: - continue - - yield chunk.choices[0].delta.content - - async def _stream_chat( - self, messages: List[ChatMessage], options - ) -> AsyncGenerator[ChatMessage, None]: - args = self.collect_args(options) - # and not self.use_legacy_completions_endpoint - # headers=self.request_options.headers, - # resp = await acompletion( - # messages=[msg.to_dict() for msg in messages], - # **args, - # api_base=self.api_base, - # api_version=self.api_version, - # # engine=self.engine, - # api_key=self.api_key, - # custom_llm_provider="azure" if self.api_type == "azure" else None, - # ) - - async with self.httpx_client_context(): - resp = await acompletion( - messages=[msg.to_dict() for msg in messages], - **args, - stream=True, - ) - async for chunk in resp: - if len(chunk.choices) == 0: - continue # :) - - if self.api_type == "azure": - if self.model == "gpt-4": - await asyncio.sleep(0.03) - else: - await asyncio.sleep(0.01) - - yield ChatMessage( - role="assistant", content=chunk.choices[0].delta.content or "" - ) - - async def _complete(self, prompt: str, options): - args = self.collect_args(options) - - async with self.httpx_client_context(): - resp = await acompletion( - messages=[{"content": prompt, "role": "user"}], - **args, - ) - - return resp.choices[0].message.content diff --git a/archive/server/continuedev/libs/llm/openai_free_trial.py b/archive/server/continuedev/libs/llm/openai_free_trial.py deleted file mode 100644 index 28f56eb95..000000000 --- a/archive/server/continuedev/libs/llm/openai_free_trial.py +++ /dev/null @@ -1,101 +0,0 @@ -from typing import List, Optional - -from pydantic import Field, validator - -from ...core.main import ChatMessage -from ...models.llm import RequestOptions -from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL -from .base import LLM -from .openai import OpenAI -from .proxy_server import ProxyServer - - -class OpenAIFreeTrial(LLM): - """ - With the `OpenAIFreeTrial` `LLM`, new users can try out Continue with GPT-4 using a proxy server that securely makes calls to OpenAI using our API key. Continue should just work the first time you install the extension in VS Code. - - Once you are using Continue regularly though, you will need to add an OpenAI API key that has access to GPT-4 by following these steps: - - 1. Copy your API key from https://platform.openai.com/account/api-keys - 2. Open `~/.continue/config.json`. You can do this by using the '/config' command in Continue - 3. Change the default LLMs to look like this: - - ```json title="~/.continue/config.json" - { - "models": [ - { - "title": "GPT-4", - "provider": "openai", - "model": "gpt-4", - "api_key": "YOUR_API_KEY" - }, - { - "title": "GPT-3.5-Turbo", - "provider": "openai", - "model": "gpt-3.5-turbo", - "api_key": "YOUR_API_KEY" - } - ], - "model_roles": { - "default": "GPT-4", - "summarize": "GPT-3.5-Turbo" - } - } - ``` - """ - - llm: LLM = Field(default=None, description="The LLM to use for completion.") - - @validator("llm", pre=True, always=True) - def set_llm(cls, llm, values): - api_key = values.get("api_key") - if api_key is None or api_key.strip() == "": - return ProxyServer( - model=values["model"], - request_options=RequestOptions( - timeout=values["request_options"].timeout, - verify_ssl=values["request_options"].verify_ssl, - ), - ) - else: - return OpenAI( - api_key=api_key, - model=values["model"], - request_options=RequestOptions( - timeout=values["request_options"].timeout, - verify_ssl=values["request_options"].verify_ssl, - ), - ) - - @validator("context_length", pre=True, always=True) - def context_length_for_model(cls, v, values): - return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096) - - def update_llm_properties(self): - self.llm.system_message = self.system_message - - def start(self, unique_id: Optional[str] = None): - super().start(unique_id=unique_id) - self.llm.start(unique_id=unique_id) - - async def stop(self): - await self.llm.stop() - - async def _complete(self, prompt: str, options): - self.update_llm_properties() - return await self.llm._complete(prompt, options) - - async def _stream_complete(self, prompt, options): - self.update_llm_properties() - resp = self.llm._stream_complete(prompt, options) - async for item in resp: - yield item - - async def _stream_chat(self, messages: List[ChatMessage], options): - self.update_llm_properties() - resp = self.llm._stream_chat(messages=messages, options=options) - async for item in resp: - yield item - - def count_tokens(self, text: str): - return self.llm.count_tokens(text) diff --git a/archive/server/continuedev/libs/llm/prompt_utils.py b/archive/server/continuedev/libs/llm/prompt_utils.py deleted file mode 100644 index 930b5220b..000000000 --- a/archive/server/continuedev/libs/llm/prompt_utils.py +++ /dev/null @@ -1,76 +0,0 @@ -from typing import Dict, List, Union - -from ...models.filesystem import RangeInFileWithContents -from ...models.filesystem_edit import FileEdit - - -class MarkdownStyleEncoderDecoder: - # Filename -> the part of the file you care about - range_in_files: List[RangeInFileWithContents] - - def __init__(self, range_in_files: List[RangeInFileWithContents]): - self.range_in_files = range_in_files - - def encode(self) -> str: - return "\n\n".join( - [ - f"File ({rif.filepath})\n```\n{rif.contents}\n```" - for rif in self.range_in_files - ] - ) - - def _suggestions_to_file_edits(self, suggestions: Dict[str, str]) -> List[FileEdit]: - file_edits: List[FileEdit] = [] - for suggestion_filepath, suggestion in suggestions.items(): - matching_rifs = list( - filter(lambda r: r.filepath == suggestion_filepath, self.range_in_files) - ) - if len(matching_rifs) > 0: - range_in_file = matching_rifs[0] - file_edits.append( - FileEdit( - range=range_in_file.range, - filepath=range_in_file.filepath, - replacement=suggestion, - ) - ) - - return file_edits - - def _decode_to_suggestions(self, completion: str) -> Dict[str, str]: - if len(self.range_in_files) == 0: - return {} - - if "```" not in completion: - completion = "```\n" + completion + "\n```" - if completion.strip().splitlines()[0].strip() == "```": - first_filepath = self.range_in_files[0].filepath - completion = f"File ({first_filepath})\n" + completion - - suggestions: Dict[str, str] = {} - current_file_lines: List[str] = [] - current_filepath: Union[str, None] = None - last_was_file = False - inside_file = False - for line in completion.splitlines(): - if line.strip().startswith("File ("): - last_was_file = True - current_filepath = line.strip()[6:-1] - elif last_was_file and line.startswith("```"): - last_was_file = False - inside_file = True - elif inside_file: - if line.startswith("```"): - inside_file = False - suggestions[current_filepath] = "\n".join(current_file_lines) - current_file_lines = [] - current_filepath = None - else: - current_file_lines.append(line) - - return suggestions - - def decode(self, completion: str) -> List[FileEdit]: - suggestions = self._decode_to_suggestions(completion) - file_edits = self._suggestions_to_file_edits(suggestions) - return file_edits diff --git a/archive/server/continuedev/libs/llm/prompts/chat.py b/archive/server/continuedev/libs/llm/prompts/chat.py deleted file mode 100644 index 2d369e9c6..000000000 --- a/archive/server/continuedev/libs/llm/prompts/chat.py +++ /dev/null @@ -1,261 +0,0 @@ -from textwrap import dedent -from typing import List - -from anthropic import AI_PROMPT, HUMAN_PROMPT - -from ....core.main import ChatMessage - - -def anthropic_template_messages(messages: List[ChatMessage]) -> str: - prompt = "" - - # Anthropic prompt must start with a Human turn - if ( - len(messages) > 0 - and messages[0].role != "user" - and messages[0].role != "system" - ): - prompt += f"{HUMAN_PROMPT} Hello." - for msg in messages: - prompt += f"{HUMAN_PROMPT if (msg.role == 'user' or msg.role == 'system') else AI_PROMPT} {msg.content} " - - prompt += AI_PROMPT - return prompt - - -def zephyr_template_messages(msgs: List[ChatMessage]) -> str: - """ " - <|system|> - - <|user|> - {prompt} - <|assistant|> - """ - prompt = "" - - if msgs[0].role == "system": - prompt += f"<|system|>{msgs[0].content}\n" - msgs.pop(0) - else: - prompt += "<|system|> \n" - - for msg in msgs: - prompt += "<|user|>\n" if msg.role == "user" else "<|assistant|>\n" - prompt += f"{msg.content}\n" - - prompt += "<|assistant|>\n" - - return prompt - - -def chatml_template_messages(messages: List[ChatMessage]) -> str: - prompt = "" - - for msg in messages: - prompt += f"<|im_start|>{msg.role}\n{msg.content}<|im_end|>\n" - - prompt += "<|im_start|>assistant\n" - return prompt - - -def template_alpaca_messages(msgs: List[ChatMessage]) -> str: - prompt = "" - - if msgs[0].role == "system": - prompt += f"{msgs[0].content}\n\n" - msgs.pop(0) - - for msg in msgs: - prompt += "### Instruction:\n" if msg.role == "user" else "### Response:\n" - prompt += f"{msg.content}\n\n" - - prompt += "### Response:\n" - - return prompt - - -def deepseek_template_messages(msgs: List[ChatMessage]) -> str: - prompt = "" - system = None - prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n" - if msgs[0].role == "system": - system = msgs.pop(0).content - - for i in range(len(msgs)): - msg = msgs[i] - prompt += "### Instruction:\n" if msg.role == "user" else "### Response:\n" - - if system and msg.role == "user" and i == len(msgs) - 1: - prompt += system + "\n" - - prompt += f"{msg.content}" - prompt += "\n" if msg.role == "user" else "<|EOT|>\n" - - return prompt + "### Response:\n" - - -def phind_template_messages(msgs: List[ChatMessage]) -> str: - prompt = "" - - if msgs[0].role == "system": - prompt += f"### System Prompt\n{msgs[0].content}\n\n" - msgs.pop(0) - - for msg in msgs: - prompt += "### User Message\n" if msg.role == "user" else "### Assistant\n" - prompt += f"{msg.content}\n" - - prompt += "### Assistant\n" - - return prompt - -def neuralchat_template_messages(msgs: List[ChatMessage]) -> str: - prompt = "" - - if msgs[0].role == "system": - prompt += f"### System:\n{msgs[0].content}\n" - msgs.pop(0) - - for msg in msgs: - prompt += "### User:\n" if msg.role == "user" else "### Assistant:\n" - prompt += f"{msg.content}\n" - - prompt += "### Assistant:\n" - - return prompt - -def raw_input_template(msgs: List[ChatMessage]) -> str: - return msgs[-1].content - - -SQL_CODER_DEFAULT_SCHEMA = """\ -CREATE TABLE products ( - product_id INTEGER PRIMARY KEY, -- Unique ID for each product - name VARCHAR(50), -- Name of the product - price DECIMAL(10,2), -- Price of each unit of the product - quantity INTEGER -- Current quantity in stock -); - -CREATE TABLE customers ( - customer_id INTEGER PRIMARY KEY, -- Unique ID for each customer - name VARCHAR(50), -- Name of the customer - address VARCHAR(100) -- Mailing address of the customer -); - -CREATE TABLE salespeople ( - salesperson_id INTEGER PRIMARY KEY, -- Unique ID for each salesperson - name VARCHAR(50), -- Name of the salesperson - region VARCHAR(50) -- Geographic sales region -); - -CREATE TABLE sales ( - sale_id INTEGER PRIMARY KEY, -- Unique ID for each sale - product_id INTEGER, -- ID of product sold - customer_id INTEGER, -- ID of customer who made purchase - salesperson_id INTEGER, -- ID of salesperson who made the sale - sale_date DATE, -- Date the sale occurred - quantity INTEGER -- Quantity of product sold -); - -CREATE TABLE product_suppliers ( - supplier_id INTEGER PRIMARY KEY, -- Unique ID for each supplier - product_id INTEGER, -- Product ID supplied - supply_price DECIMAL(10,2) -- Unit price charged by supplier -); - --- sales.product_id can be joined with products.product_id --- sales.customer_id can be joined with customers.customer_id --- sales.salesperson_id can be joined with salespeople.salesperson_id --- product_suppliers.product_id can be joined with products.product_id -""" - - -def _sqlcoder_template_messages( - msgs: List[ChatMessage], schema: str = SQL_CODER_DEFAULT_SCHEMA -) -> str: - question = msgs[-1].content - return f"""\ -Your task is to convert a question into a SQL query, given a Postgres database schema. -Adhere to these rules: -- **Deliberately go through the question and database schema word by word** to appropriately answer the question -- **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`. -- When creating a ratio, always cast the numerator as float - -### Input: -Generate a SQL query that answers the question `{question}`. -This query will run on a database whose schema is represented in this string: -{schema} - -### Response: -Based on your instructions, here is the SQL query I have generated to answer the question `{question}`: -```sql -""" - - -def sqlcoder_template_messages(schema: str = SQL_CODER_DEFAULT_SCHEMA): - if schema in {"", ""}: - schema = SQL_CODER_DEFAULT_SCHEMA - - def fn(msgs): - return _sqlcoder_template_messages(msgs, schema=schema) - - fn.__name__ = "sqlcoder_template_messages" - return fn - - -def llama2_template_messages(msgs: List[ChatMessage]) -> str: - if len(msgs) == 0: - return "" - - if msgs[0].role == "assistant": - # These models aren't trained to handle assistant message coming first, - # and typically these are just introduction messages from Continue - msgs.pop(0) - - prompt = "" - has_system = msgs[0].role == "system" - - if has_system and msgs[0].content.strip() == "": - has_system = False - msgs = msgs[1:] - - if has_system: - system_message = dedent( - f"""\ - <> - {msgs[0].content} - <> - - """ - ) - if len(msgs) > 1: - prompt += f"[INST] {system_message}{msgs[1].content} [/INST]" - else: - prompt += f"[INST] {system_message} [/INST]" - return prompt - - for i in range(2 if has_system else 0, len(msgs)): - if msgs[i].role == "user": - prompt += f"[INST] {msgs[i].content} [/INST]" - else: - prompt += msgs[i].content + " " - - return prompt - - -def code_llama_template_messages(msgs: List[ChatMessage]) -> str: - return f"[INST] {msgs[-1].content}\n[/INST]" - - -def extra_space_template_messages(msgs: List[ChatMessage]) -> str: - return f" {msgs[-1].content}" - - -def code_llama_python_template_messages(msgs: List[ChatMessage]) -> str: - return dedent( - f"""\ - [INST] - You are an expert Python programmer and personal assistant, here is your task: {msgs[-1].content} - Your answer should start with a [PYTHON] tag and end with a [/PYTHON] tag. - [/INST]""" - ) diff --git a/archive/server/continuedev/libs/llm/prompts/edit.py b/archive/server/continuedev/libs/llm/prompts/edit.py deleted file mode 100644 index 06d5da953..000000000 --- a/archive/server/continuedev/libs/llm/prompts/edit.py +++ /dev/null @@ -1,143 +0,0 @@ -from textwrap import dedent - -from ....models.llm import PromptTemplate - -simplified_edit_prompt = dedent( - """\ - Consider the following code: - ``` - {{{code_to_edit}}} - ``` - Edit the code to perfectly satisfy the following user request: - {{{user_input}}} - Output nothing except for the code. No code block, no English explanation, no start/end tags.""" -) - -simplest_edit_prompt = dedent( - """\ - Here is the code before editing: - ``` - {{{code_to_edit}}} - ``` - - Here is the edit requested: - "{{{user_input}}}" - - Here is the code after editing:""" -) - -codellama_infill_edit_prompt = "{{file_prefix}}{{file_suffix}}" - -_codellama_edit_prompt = dedent( - """\ - [CODE] - {{{code_to_edit}}} - [/CODE] - [INST] - You are an expert programmer and personal assistant, here is your task: "Rewrite the above code in order to {{{user_input}}}" - - Your answer should start with a [CODE] tag and end with a [/CODE] tag. - [/INST] Sure! Here's the code you requested: - [CODE]""" -) - -_alpaca_edit_prompt = dedent( - """\ - Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. - - ### Instruction: Rewrite the code to satisfy this request: "{{{user_input}}}" - - ### Input: - - ``` - {{{code_to_edit}}} - ``` - - ### Response: - - Sure! Here's the code you requested: - ``` - """ -) - -_phind_edit_prompt = dedent( - """\ - ### System Prompt - You are an expert programmer and write code on the first attempt without any errors or fillers. - - ### User Message: - Rewrite the code to satisfy this request: "{{{user_input}}}" - - ``` - {{{code_to_edit}}} - ``` - - ### Assistant: - Sure! Here's the code you requested: - - ``` - """ -) - -_deepseek_edit_prompt = dedent( - """\ - ### System Prompt - You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer. - ### Instruction: - Rewrite the code to satisfy this request: "{{{user_input}}}" - - ``` - {{{code_to_edit}}} - ```<|EOT|> - ### Response: - Sure! Here's the code you requested: - - ``` - """ -) - -_zephyr_edit_prompt = dedent( - """\ - <|system|> - You are an expert programmer and write code on the first attempt without any errors or fillers. - <|user|> - Rewrite the code to satisfy this request: "{{{user_input}}}" - - ``` - {{{code_to_edit}}} - ``` - <|assistant|> - Sure! Here's the code you requested: - - ``` - """ -) - -_neuralchat_edit_prompt = dedent( - """\ - ### System: - You are an expert programmer and write code on the first attempt without any errors or fillers. - ### User: - Rewrite the code to satisfy this request: "{{{user_input}}}" - - ``` - {{{code_to_edit}}} - ``` - ### Assistant: - Sure! Here's the code you requested: - - ``` - """ -) - - -codellama_edit_prompt = PromptTemplate( - prompt=_codellama_edit_prompt, raw=True, stop=["[/CODE]"] -) -alpaca_edit_prompt = PromptTemplate(prompt=_alpaca_edit_prompt, raw=True, stop=["```"]) -phind_edit_prompt = PromptTemplate(prompt=_phind_edit_prompt, raw=True, stop=["```"]) -zephyr_edit_prompt = PromptTemplate(prompt=_zephyr_edit_prompt, raw=True, stop=["```"]) -deepseek_edit_prompt = PromptTemplate( - prompt=_deepseek_edit_prompt, raw=True, stop=["```"] -) -neuralchat_edit_prompt = PromptTemplate(prompt=_neuralchat_edit_prompt, raw=True, stop=["```"]) \ No newline at end of file diff --git a/archive/server/continuedev/libs/llm/proxy_server.py b/archive/server/continuedev/libs/llm/proxy_server.py deleted file mode 100644 index 3e18005d3..000000000 --- a/archive/server/continuedev/libs/llm/proxy_server.py +++ /dev/null @@ -1,109 +0,0 @@ -import asyncio -import json -from typing import List - -from pydantic import validator - -from ...core.main import ChatMessage -from ..util.count_tokens import CONTEXT_LENGTH_FOR_MODEL -from ..util.errors import format_exc -from ..util.telemetry import posthog_logger -from .base import LLM - -# SERVER_URL = "http://127.0.0.1:8080" -SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app" - - -class ProxyServer(LLM): - class Config: - arbitrary_types_allowed = True - - def start( - self, - **kwargs, - ): - super().start(**kwargs) - self.context_length = CONTEXT_LENGTH_FOR_MODEL[self.model] - - def get_headers(self): - return {"unique_id": self.unique_id or "None"} - - @validator("context_length") - def context_length_for_model(cls, v, values): - return CONTEXT_LENGTH_FOR_MODEL.get(values["model"], 4096) - - async def _complete(self, prompt: str, options): - args = self.collect_args(options) - - async with self.create_client_session() as session: - async with session.post( - f"{SERVER_URL}/complete", - json={"messages": [{"role": "user", "content": prompt}], **args}, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - resp_text = await resp.text() - if resp.status != 200: - raise Exception(resp_text) - - return resp_text - - async def _stream_chat(self, messages: List[ChatMessage], options): - args = self.collect_args(options) - async with self.create_client_session() as session: - async with session.post( - f"{SERVER_URL}/stream_chat", - json={"messages": [msg.to_dict() for msg in messages], **args}, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - if resp.status != 200: - raise Exception(await resp.text()) - - async for line in resp.content.iter_chunks(): - if line[1]: - try: - json_chunk = line[0].decode("utf-8") - json_chunk = "{}" if json_chunk == "" else json_chunk - chunks = json_chunk.split("\n") - for chunk in chunks: - if chunk.strip() != "": - loaded_chunk = json.loads(chunk) - yield ChatMessage( - role="assistant", - content=loaded_chunk.get("content", ""), - ) - - 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", - { - "error_title": "Proxy server stream_chat parsing failed", - "error_message": format_exc(e), - }, - ) - else: - break - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - async with self.create_client_session() as session: - async with session.post( - f"{SERVER_URL}/stream_complete", - json={"messages": [{"role": "user", "content": prompt}], **args}, - headers=self.get_headers(), - proxy=self.request_options.proxy, - ) as resp: - if resp.status != 200: - raise Exception(await resp.text()) - - async for line in resp.content.iter_any(): - if line: - decoded_line = line.decode("utf-8") - yield decoded_line diff --git a/archive/server/continuedev/libs/llm/queued.py b/archive/server/continuedev/libs/llm/queued.py deleted file mode 100644 index ff7d08814..000000000 --- a/archive/server/continuedev/libs/llm/queued.py +++ /dev/null @@ -1,77 +0,0 @@ -import asyncio -from typing import Any, List, Union - -from pydantic import Field - -from ...core.main import ChatMessage -from .base import LLM, CompletionOptions - - -class QueuedLLM(LLM): - """ - QueuedLLM exists to make up for LLM servers that cannot handle multiple requests at once. It uses a lock to ensure that only one request is being processed at a time. - - If you are already using another LLM class and are experiencing this problem, you can just wrap it with the QueuedLLM class like this: - - ```python title="~/.continue/config.py" - from continuedev.libs.llm.queued import QueuedLLM - - config = ContinueConfig( - ... - models=Models( - default=QueuedLLM(llm=) - ) - ) - ``` - """ - - llm: LLM = Field(..., description="The LLM to wrap with a lock") - _lock: asyncio.Lock - - model: str = "queued" - - def dict(self, **kwargs): - return self.llm.dict(**kwargs) - - def start(self, *args, **kwargs): - super().start(*args, **kwargs) - self.llm.start(*args, **kwargs) - self._lock = asyncio.Lock() - self.model = self.llm.model - self.template_messages = self.llm.template_messages - self.prompt_templates = self.llm.prompt_templates - self.context_length = self.llm.context_length - - async def stop(self): - await self.llm.stop() - - def collect_args(self, options: CompletionOptions): - return self.llm.collect_args(options) - - def compile_chat_messages( - self, - options: CompletionOptions, - msgs: List[ChatMessage], - functions: Union[List[Any], None] = None, - ): - return self.llm.compile_chat_messages(options, msgs, functions) - - def template_prompt_like_messages(self, prompt: str) -> str: - return self.llm.template_prompt_like_messages(prompt) - - async def _complete(self, prompt: str, options: CompletionOptions): - async with self._lock: - resp = await self.llm._complete(prompt, options) - return resp - - async def _stream_complete(self, prompt: str, options: CompletionOptions): - async with self._lock: - async for chunk in self.llm._stream_complete(prompt, options): - yield chunk - - async def _stream_chat( - self, messages: List[ChatMessage], options: CompletionOptions - ): - async with self._lock: - async for chunk in self.llm._stream_chat(messages, options): - yield chunk diff --git a/archive/server/continuedev/libs/llm/replicate.py b/archive/server/continuedev/libs/llm/replicate.py deleted file mode 100644 index 05c7bb6d4..000000000 --- a/archive/server/continuedev/libs/llm/replicate.py +++ /dev/null @@ -1,81 +0,0 @@ -import concurrent.futures -from typing import List - -import replicate -from pydantic import Field - -from ...core.main import ChatMessage -from .base import LLM - - -class ReplicateLLM(LLM): - """ - Replicate is a great option for newly released language models or models that you've deployed through their platform. Sign up for an account [here](https://replicate.ai/), copy your API key, and then select any model from the [Replicate Streaming List](https://replicate.com/collections/streaming-language-models). Change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Replicate CodeLLama", - "provider": "replicate", - "model": "codellama-13b", - "api_key": "YOUR_API_KEY" - }] - } - ``` - - If you don't specify the `model` parameter, it will default to `replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781`. - """ - - api_key: str = Field(..., description="Replicate API key") - - model: str = "replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781" - - @property - def _client(self) -> replicate.Client: - return replicate.Client(api_token=self.api_key) - - def get_model_name(self): - return { - "codellama-7b": "meta/codellama-7b-instruct:6527b83e01e41412db37de5110a8670e3701ee95872697481a355e05ce12af0e", - "codellama-13b": "meta/codellama-13b-instruct:1f01a52ff933873dff339d5fb5e1fd6f24f77456836f514fa05e91c1a42699c7", - "codellama-34b": "meta/codellama-34b-instruct:8281a5c610f6e88237ff3ddaf3c33b56f60809e2bdd19fbec2fda742aa18167e", - "llama2-7b": "meta/llama-2-7b-chat:8e6975e5ed6174911a6ff3d60540dfd4844201974602551e10e9e87ab143d81e", - "llama2-13b": "meta/llama-2-13b-chat:f4e2de70d66816a838a89eeeb621910adffb0dd0baba3976c96980970978018d", - "zephyr-7b": "nateraw/zephyr-7b-beta:b79f33de5c6c4e34087d44eaea4a9d98ce5d3f3a09522f7328eea0685003a931", - "mistral-7b": "mistralai/mistral-7b-instruct-v0.1:83b6a56e7c828e667f21fd596c338fd4f0039b46bcfa18d973e8e70e455fda70", - "wizardcoder-34b": "andreasjansson/wizardcoder-python-34b-v1-gguf:67eed332a5389263b8ede41be3ee7dc119fa984e2bde287814c4abed19a45e54", - "neural-chat-7b": "tomasmcm/neural-chat-7b-v3-1:acb450496b49e19a1e410b50c574a34acacd54820bc36c19cbfe05148de2ba57", - }.get(self.model, self.model) - - async def _complete(self, prompt: str, options): - def helper(): - output = self._client.run( - self.get_model_name(), input={"message": prompt, "prompt": prompt} - ) - completion = "" - for item in output: - completion += item - - return completion - - with concurrent.futures.ThreadPoolExecutor() as executor: - future = executor.submit(helper) - completion = future.result() - - return completion - - async def _stream_complete(self, prompt, options): - for item in self._client.run( - self.get_model_name(), input={"message": prompt, "prompt": prompt} - ): - yield item - - async def _stream_chat(self, messages: List[ChatMessage], options): - for item in self._client.run( - self.get_model_name(), - input={ - "message": messages[-1].content, - "prompt": messages[-1].content, - }, - ): - yield ChatMessage(role="assistant", content=item) diff --git a/archive/server/continuedev/libs/llm/text_gen_webui.py b/archive/server/continuedev/libs/llm/text_gen_webui.py deleted file mode 100644 index 21c1e03d4..000000000 --- a/archive/server/continuedev/libs/llm/text_gen_webui.py +++ /dev/null @@ -1,111 +0,0 @@ -import json -from typing import Any, AsyncGenerator, List, Optional - -import websockets -from pydantic import Field - -from ...core.main import ChatMessage -from .base import LLM - - -class TextGenWebUI(LLM): - """ - TextGenWebUI is a comprehensive, open-source language model UI and local server. You can set it up with an OpenAI-compatible server plugin, but if for some reason that doesn't work, you can use this class like so: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Text Generation WebUI", - "provider": "text-gen-webui", - "model": "MODEL_NAME" - }] - } - ``` - """ - - model: str = "text-gen-webui" - api_base: Optional[str] = Field( - "http://127.0.0.1:5000", description="URL of your TextGenWebUI server" - ) - streaming_url: Optional[str] = Field( - "http://127.0.0.1:5005", - description="URL of your TextGenWebUI streaming server (separate from main server URL)", - ) - - class Config: - arbitrary_types_allowed = True - - def collect_args(self, options) -> Any: - args = super().collect_args(options) - args = {**args, "max_new_tokens": options.max_tokens} - args.pop("max_tokens", None) - return args - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - if self.streaming_url is None: - raise Exception("TextGenWebUI streaming server URL was set to None.") - - ws_url = f"{self.streaming_url.replace('http://', 'ws://').replace('https://', 'wss://')}" - payload = json.dumps({"prompt": prompt, "stream": True, **args}) - async with websockets.connect( - f"{ws_url}/api/v1/stream", ping_interval=None - ) as websocket: - await websocket.send(payload) - - while True: - incoming_data = await websocket.recv() - incoming_data = json.loads(incoming_data) - - incoming_data_event = incoming_data["event"] - - if incoming_data_event == "text_stream": - yield incoming_data["text"] - elif incoming_data_event == "stream_end": - break - - async def _stream_chat( - self, messages: List[ChatMessage], options - ) -> AsyncGenerator[ChatMessage, None]: - args = self.collect_args(options) - - async def generator(): - if self.streaming_url is None: - raise Exception("TextGenWebUI streaming server URL was set to None.") - - ws_url = f"{self.streaming_url.replace('http://', 'ws://').replace('https://', 'wss://')}" - history = list(map(lambda x: x.content, messages)) - payload = json.dumps( - { - "user_input": messages[-1].content, - "history": {"internal": [history], "visible": [history]}, - "stream": True, - **args, - } - ) - async with websockets.connect( - f"{ws_url}/api/v1/chat-stream", ping_interval=None - ) as websocket: - await websocket.send(payload) - - prev = "" - while True: - incoming_data = await websocket.recv() - incoming_data = json.loads(incoming_data) - - incoming_data_event = incoming_data["event"] - - if incoming_data_event == "text_stream": - visible = incoming_data["history"]["visible"][-1] - if len(visible) > 0: - yield ChatMessage( - role="assistant", content=visible[-1].replace(prev, "") - ) - - prev = visible[-1] - elif incoming_data_event == "stream_end": - break - - async for chunk in generator(): - yield chunk diff --git a/archive/server/continuedev/libs/llm/together.py b/archive/server/continuedev/libs/llm/together.py deleted file mode 100644 index 6d9951c32..000000000 --- a/archive/server/continuedev/libs/llm/together.py +++ /dev/null @@ -1,129 +0,0 @@ -import json -from typing import Any, Dict, Optional - -from pydantic import Field, validator - -from continuedev.models.llm import CompletionOptions - -from ...core.main import ContinueCustomException -from ..util.logging import logger -from .base import LLM - - -class TogetherLLM(LLM): - """ - The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/models-inference). Change `~/.continue/config.json` to look like this: - - ```json title="~/.continue/config.json" - { - "models": [{ - "title": "Together CodeLlama", - "provider": "together", - "model": "codellama-13b", - "api_key": "YOUR_API_KEY" - }] - } - ``` - """ - - api_key: str = Field(..., description="Together API key") - - model: str = "togethercomputer/RedPajama-INCITE-7B-Instruct" - api_base: Optional[str] = Field( - "https://api.together.xyz", - description="The base URL for your Together API instance", - ) - - @validator("api_base", pre=True, always=True) - def set_api_base(cls, api_base): - return api_base or "https://api.together.xyz" - - def collect_args(self, options: CompletionOptions) -> Dict[str, Any]: - args = super().collect_args(options) - args["model"] = { - "codellama-7b": "togethercomputer/CodeLlama-7b-Instruct", - "codellama-13b": "togethercomputer/CodeLlama-13b-Instruct", - "codellama-34b": "togethercomputer/CodeLlama-34b-Instruct", - "llama2-7b": "togethercomputer/llama-2-7b-chat", - "llama2-13b": "togethercomputer/llama-2-13b-chat", - "llama2-70b": "togethercomputer/llama-2-70b-chat", - "mistral-7b": "mistralai/Mistral-7B-Instruct-v0.1", - "phind-codellama-34b": "Phind/Phind-CodeLlama-34B-v2" - }.get(self.model, self.model) - return args - - async def _stream_complete(self, prompt, options): - args = self.collect_args(options) - - async with self.create_client_session() as session: - async with session.post( - f"{self.api_base}/inference", - json={ - "prompt": prompt, - "stream_tokens": True, - **args, - }, - headers={"Authorization": f"Bearer {self.api_key}"}, - proxy=self.request_options.proxy, - ) as resp: - async for line in resp.content.iter_chunks(): - if line[1]: - json_chunk = line[0].decode("utf-8") - if json_chunk.startswith(": ping - ") or json_chunk.startswith( - "data: [DONE]" - ): - continue - - chunks = json_chunk.split("\n") - for chunk in chunks: - if chunk.strip() != "": - if chunk.startswith("data: "): - chunk = chunk[6:] - if chunk == "[DONE]": - break - try: - json_chunk = json.loads(chunk) - except Exception as e: - logger.warning( - f"Invalid JSON chunk: {chunk}\n\n{e}" - ) - continue - if "error" in json_chunk: - raise ContinueCustomException( - message=json_chunk["error"], - title="Together API Error", - ) - elif "choices" in json_chunk: - yield json_chunk["choices"][0]["text"] - - async def _complete(self, prompt: str, options): - args = self.collect_args(options) - - async with self.create_client_session() as session: - async with session.post( - f"{self.api_base}/inference", - json={"prompt": prompt, **args}, - headers={"Authorization": f"Bearer {self.api_key}"}, - proxy=self.request_options.proxy, - ) as resp: - text = await resp.text() - j = json.loads(text) - try: - if "choices" not in j["output"]: - raise Exception(text) - if "output" in j: - return j["output"]["choices"][0]["text"] - except Exception as e: - j = await resp.json() - if "error" in j: - if j["error"].startswith("invalid hexlify value"): - raise ContinueCustomException( - message=f"Invalid Together API key:\n\n{j['error']}", - title="Together API Error", - ) - else: - raise ContinueCustomException( - message=j["error"], title="Together API Error" - ) - - raise e diff --git a/archive/server/continuedev/libs/util/calculate_diff.py b/archive/server/continuedev/libs/util/calculate_diff.py deleted file mode 100644 index 99301ae77..000000000 --- a/archive/server/continuedev/libs/util/calculate_diff.py +++ /dev/null @@ -1,154 +0,0 @@ -import difflib -from typing import List - -from ...models.filesystem import FileEdit -from ...models.main import Position, Range - - -def calculate_diff(filepath: str, original: str, updated: str) -> List[FileEdit]: - s = difflib.SequenceMatcher(None, original, updated) - offset = 0 # The indices are offset by previous deletions/insertions - edits = [] - for tag, i1, i2, j1, j2 in s.get_opcodes(): - i1, i2, j1, j2 = i1 + offset, i2 + offset, j1 + offset, j2 + offset - replacement = updated[j1:j2] - if tag == "equal": - pass - elif tag == "delete": - edits.append( - FileEdit.from_deletion(filepath, Range.from_indices(original, i1, i2)) - ) - offset -= i2 - i1 - elif tag == "insert": - edits.append( - FileEdit.from_insertion( - filepath, Position.from_index(original, i1), replacement - ) - ) - offset += j2 - j1 - elif tag == "replace": - edits.append( - FileEdit( - filepath=filepath, - range=Range.from_indices(original, i1, i2), - replacement=replacement, - ) - ) - offset += (j2 - j1) - (i2 - i1) - else: - raise Exception("Unexpected difflib.SequenceMatcher tag: " + tag) - - return edits - - -def calculate_diff2(filepath: str, original: str, updated: str) -> List[FileEdit]: - # original_lines = original.splitlines() - # updated_lines = updated.splitlines() - # offset = 0 - # while len(original_lines) and len(updated_lines) and original_lines[0] == updated_lines[0]: - # original_lines = original_lines[1:] - # updated_lines = updated_lines[1:] - - # while len(original_lines) and len(updated_lines) and original_lines[-1] == updated_lines[-1]: - # original_lines = original_lines[:-1] - # updated_lines = updated_lines[:-1] - - # original = "\n".join(original_lines) - # updated = "\n".join(updated_lines) - - edits = [] - max_iterations = 1000 - i = 0 - while not original == updated: - # TODO - For some reason it can't handle a single newline at the end of the file? - s = difflib.SequenceMatcher(None, original, updated) - opcodes = s.get_opcodes() - for edit_index in range(len(opcodes)): - tag, i1, i2, j1, j2 = s.get_opcodes()[edit_index] - replacement = updated[j1:j2] - if tag == "equal": - continue # ;) - elif tag == "delete": - edits.append( - FileEdit.from_deletion( - filepath, Range.from_indices(original, i1, i2) - ) - ) - elif tag == "insert": - edits.append( - FileEdit.from_insertion( - filepath, Position.from_index(original, i1), replacement - ) - ) - elif tag == "replace": - edits.append( - FileEdit( - filepath=filepath, - range=Range.from_indices(original, i1, i2), - replacement=replacement, - ) - ) - else: - raise Exception("Unexpected difflib.SequenceMatcher tag: " + tag) - break - - original = apply_edit_to_str(original, edits[-1]) - - i += 1 - if i > max_iterations: - raise Exception("Max iterations reached") - - return edits - - -def read_range_in_str(s: str, r: Range) -> str: - lines = s.splitlines()[r.start.line : r.end.line + 1] - if len(lines) == 0: - return "" - - lines[0] = lines[0][r.start.character :] - lines[-1] = lines[-1][: r.end.character + 1] - return "\n".join(lines) - - -def apply_edit_to_str(s: str, edit: FileEdit) -> str: - read_range_in_str(s, edit.range) - - # Split lines and deal with some edge cases (could obviously be nicer) - lines = s.splitlines() - if s.startswith("\n"): - lines.insert(0, "") - if s.endswith("\n"): - lines.append("") - - if len(lines) == 0: - lines = [""] - - end = Position(line=edit.range.end.line, character=edit.range.end.character) - if edit.range.end.line == len(lines) and edit.range.end.character == 0: - end = Position( - line=edit.range.end.line - 1, - character=len(lines[min(len(lines) - 1, edit.range.end.line - 1)]), - ) - - before_lines = lines[: edit.range.start.line] - after_lines = lines[end.line + 1 :] - between_str = ( - lines[min(len(lines) - 1, edit.range.start.line)][: edit.range.start.character] - + edit.replacement - + lines[min(len(lines) - 1, end.line)][end.character + 1 :] - ) - - Range( - start=edit.range.start, - end=Position( - line=edit.range.start.line + len(edit.replacement.splitlines()) - 1, - character=edit.range.start.character - + len(edit.replacement.splitlines()[-1]) - if edit.replacement != "" - else 0, - ), - ) - - lines = before_lines + between_str.splitlines() + after_lines - return "\n".join(lines) diff --git a/archive/server/continuedev/libs/util/commonregex.py b/archive/server/continuedev/libs/util/commonregex.py deleted file mode 100644 index f9b39a948..000000000 --- a/archive/server/continuedev/libs/util/commonregex.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding: utf-8 -import re -from typing import Any - -date = re.compile( - "(?:(?]+[^\s`!()\[\]{};:'\".,<>?\xab\xbb\u201c\u201d\u2018\u2019])?)", - re.IGNORECASE, -) -email = re.compile( - "([a-z0-9!#$%&'*+\/=?^_`{|.}~-]+@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)", - re.IGNORECASE, -) -ip = re.compile( - "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)", - re.IGNORECASE, -) -ipv6 = re.compile( - "\s*(?!.*::.*::)(?:(?!:)|:(?=:))(?:[0-9a-f]{0,4}(?:(?<=::)|(?", - "times": "