{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Code search\n", "\n", "We index our own [openai-python code repository](https://github.com/openai/openai-python), and show how it can be searched. We implement a simple version of file parsing and extracting of functions from python files." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total number of py files: 51\n", "Total number of functions extracted: 97\n" ] } ], "source": [ "import os\n", "from glob import glob\n", "import pandas as pd\n", "\n", "def get_function_name(code):\n", " \"\"\"\n", " Extract function name from a line beginning with \"def \"\n", " \"\"\"\n", " assert code.startswith(\"def \")\n", " return code[len(\"def \"): code.index(\"(\")]\n", "\n", "def get_until_no_space(all_lines, i) -> str:\n", " \"\"\"\n", " Get all lines until a line outside the function definition is found.\n", " \"\"\"\n", " ret = [all_lines[i]]\n", " for j in range(i + 1, i + 10000):\n", " if j < len(all_lines):\n", " if len(all_lines[j]) == 0 or all_lines[j][0] in [\" \", \"\\t\", \")\"]:\n", " ret.append(all_lines[j])\n", " else:\n", " break\n", " return \"\\n\".join(ret)\n", "\n", "def get_functions(filepath):\n", " \"\"\"\n", " Get all functions in a Python file.\n", " \"\"\"\n", " whole_code = open(filepath).read().replace(\"\\r\", \"\\n\")\n", " all_lines = whole_code.split(\"\\n\")\n", " for i, l in enumerate(all_lines):\n", " if l.startswith(\"def \"):\n", " code = get_until_no_space(all_lines, i)\n", " function_name = get_function_name(code)\n", " yield {\"code\": code, \"function_name\": function_name, \"filepath\": filepath}\n", "\n", "\n", "# get user root directory\n", "root_dir = os.path.expanduser(\"~\")\n", "# note: for this code to work, the openai-python repo must be downloaded and placed in your root directory\n", "\n", "# path to code repository directory\n", "code_root = root_dir + \"/openai-python\"\n", "\n", "code_files = [y for x in os.walk(code_root) for y in glob(os.path.join(x[0], '*.py'))]\n", "print(\"Total number of py files:\", len(code_files))\n", "\n", "if len(code_files) == 0:\n", " print(\"Double check that you have downloaded the openai-python repo and set the code_root variable correctly.\")\n", "\n", "all_funcs = []\n", "for code_file in code_files:\n", " funcs = list(get_functions(code_file))\n", " for func in funcs:\n", " all_funcs.append(func)\n", "\n", "print(\"Total number of functions extracted:\", len(all_funcs))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
codefunction_namefilepathcode_embedding
0def _console_log_level():\\n if openai.log i..._console_log_level/openai/util.py[0.03389773145318031, -0.004390408284962177, 0...
1def log_debug(message, **params):\\n msg = l...log_debug/openai/util.py[-0.004034275189042091, 0.004895383026450872, ...
2def log_info(message, **params):\\n msg = lo...log_info/openai/util.py[0.004882764536887407, 0.0033515947870910168, ...
3def log_warn(message, **params):\\n msg = lo...log_warn/openai/util.py[0.002535992069169879, -0.010829543694853783, ...
4def logfmt(props):\\n def fmt(key, val):\\n ...logfmt/openai/util.py[0.016732551157474518, 0.017367802560329437, 0...
\n", "
" ], "text/plain": [ " code function_name \\\n", "0 def _console_log_level():\\n if openai.log i... _console_log_level \n", "1 def log_debug(message, **params):\\n msg = l... log_debug \n", "2 def log_info(message, **params):\\n msg = lo... log_info \n", "3 def log_warn(message, **params):\\n msg = lo... log_warn \n", "4 def logfmt(props):\\n def fmt(key, val):\\n ... logfmt \n", "\n", " filepath code_embedding \n", "0 /openai/util.py [0.03389773145318031, -0.004390408284962177, 0... \n", "1 /openai/util.py [-0.004034275189042091, 0.004895383026450872, ... \n", "2 /openai/util.py [0.004882764536887407, 0.0033515947870910168, ... \n", "3 /openai/util.py [0.002535992069169879, -0.010829543694853783, ... \n", "4 /openai/util.py [0.016732551157474518, 0.017367802560329437, 0... " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from openai.embeddings_utils import get_embedding\n", "\n", "df = pd.DataFrame(all_funcs)\n", "df['code_embedding'] = df['code'].apply(lambda x: get_embedding(x, engine='text-embedding-ada-002'))\n", "df['filepath'] = df['filepath'].apply(lambda x: x.replace(code_root, \"\"))\n", "df.to_csv(\"data/code_search_openai-python.csv\", index=False)\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/openai/tests/test_endpoints.py:test_completions score=0.826\n", "def test_completions():\n", " result = openai.Completion.create(prompt=\"This was a test\", n=5, engine=\"ada\")\n", " assert len(result.choices) == 5\n", "\n", "\n", "----------------------------------------------------------------------\n", "/openai/tests/test_endpoints.py:test_completions_model score=0.811\n", "def test_completions_model():\n", " result = openai.Completion.create(prompt=\"This was a test\", n=5, model=\"ada\")\n", " assert len(result.choices) == 5\n", " assert result.model.startswith(\"ada\")\n", "\n", "\n", "----------------------------------------------------------------------\n", "/openai/tests/test_endpoints.py:test_completions_multiple_prompts score=0.808\n", "def test_completions_multiple_prompts():\n", " result = openai.Completion.create(\n", " prompt=[\"This was a test\", \"This was another test\"], n=5, engine=\"ada\"\n", " )\n", " assert len(result.choices) == 10\n", "\n", "\n", "----------------------------------------------------------------------\n" ] } ], "source": [ "from openai.embeddings_utils import cosine_similarity\n", "\n", "def search_functions(df, code_query, n=3, pprint=True, n_lines=7):\n", " embedding = get_embedding(code_query, engine='text-embedding-ada-002')\n", " df['similarities'] = df.code_embedding.apply(lambda x: cosine_similarity(x, embedding))\n", "\n", " res = df.sort_values('similarities', ascending=False).head(n)\n", " if pprint:\n", " for r in res.iterrows():\n", " print(r[1].filepath+\":\"+r[1].function_name + \" score=\" + str(round(r[1].similarities, 3)))\n", " print(\"\\n\".join(r[1].code.split(\"\\n\")[:n_lines]))\n", " print('-'*70)\n", " return res\n", "\n", "res = search_functions(df, 'Completions API tests', n=3)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/openai/validators.py:format_inferrer_validator score=0.751\n", "def format_inferrer_validator(df):\n", " \"\"\"\n", " This validator will infer the likely fine-tuning format of the data, and display it to the user if it is classification.\n", " It will also suggest to use ada and explain train/validation split benefits.\n", " \"\"\"\n", " ft_type = infer_task_type(df)\n", " immediate_msg = None\n", "----------------------------------------------------------------------\n", "/openai/validators.py:get_validators score=0.748\n", "def get_validators():\n", " return [\n", " num_examples_validator,\n", " lambda x: necessary_column_validator(x, \"prompt\"),\n", " lambda x: necessary_column_validator(x, \"completion\"),\n", " additional_column_validator,\n", " non_empty_field_validator,\n", "----------------------------------------------------------------------\n", "/openai/validators.py:infer_task_type score=0.738\n", "def infer_task_type(df):\n", " \"\"\"\n", " Infer the likely fine-tuning task type from the data\n", " \"\"\"\n", " CLASSIFICATION_THRESHOLD = 3 # min_average instances of each class\n", " if sum(df.prompt.str.len()) == 0:\n", " return \"open-ended generation\"\n", "----------------------------------------------------------------------\n" ] } ], "source": [ "res = search_functions(df, 'fine-tuning input data validation logic', n=3)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/openai/validators.py:get_common_xfix score=0.793\n", "def get_common_xfix(series, xfix=\"suffix\"):\n", " \"\"\"\n", " Finds the longest common suffix or prefix of all the values in a series\n", " \"\"\"\n", " common_xfix = \"\"\n", " while True:\n", " common_xfixes = (\n", " series.str[-(len(common_xfix) + 1) :]\n", " if xfix == \"suffix\"\n", " else series.str[: len(common_xfix) + 1]\n", "----------------------------------------------------------------------\n", "/openai/validators.py:common_completion_suffix_validator score=0.778\n", "def common_completion_suffix_validator(df):\n", " \"\"\"\n", " This validator will suggest to add a common suffix to the completion if one doesn't already exist in case of classification or conditional generation.\n", " \"\"\"\n", " error_msg = None\n", " immediate_msg = None\n", " optional_msg = None\n", " optional_fn = None\n", "\n", " ft_type = infer_task_type(df)\n", "----------------------------------------------------------------------\n" ] } ], "source": [ "res = search_functions(df, 'find common suffix', n=2, n_lines=10)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/openai/cli.py:tools_register score=0.773\n", "def tools_register(parser):\n", " subparsers = parser.add_subparsers(\n", " title=\"Tools\", help=\"Convenience client side tools\"\n", " )\n", "\n", " def help(args):\n", " parser.print_help()\n", "\n", " parser.set_defaults(func=help)\n", "\n", " sub = subparsers.add_parser(\"fine_tunes.prepare_data\")\n", " sub.add_argument(\n", " \"-f\",\n", " \"--file\",\n", " required=True,\n", " help=\"JSONL, JSON, CSV, TSV, TXT or XLSX file containing prompt-completion examples to be analyzed.\"\n", " \"This should be the local file path.\",\n", " )\n", " sub.add_argument(\n", " \"-q\",\n", "----------------------------------------------------------------------\n" ] } ], "source": [ "res = search_functions(df, 'Command line interface for fine-tuning', n=1, n_lines=20)" ] } ], "metadata": { "interpreter": { "hash": "be4b5d5b73a21c599de40d6deb1129796d12dc1cc33a738f7bac13269cfcafe8" }, "kernelspec": { "display_name": "openai-cookbook", "language": "python", "name": "openai-cookbook" }, "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.9.6" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }