{ "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 }