2022-03-11 02:08:53 +00:00
{
"cells": [
{
2022-12-13 23:28:39 +00:00
"attachments": {},
2022-03-11 02:08:53 +00:00
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code search\n",
"\n",
2022-12-13 23:28:39 +00:00
"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."
2022-03-11 02:08:53 +00:00
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-12-13 23:28:39 +00:00
"Total number of py files: 51\n",
"Total number of functions extracted: 97\n"
2022-03-11 02:08:53 +00:00
]
}
],
"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",
2022-12-13 23:28:39 +00:00
"# note: for this code to work, the openai-python repo must be downloaded and placed in your root directory\n",
2022-03-11 02:08:53 +00:00
"\n",
"# path to code repository directory\n",
"code_root = root_dir + \"/openai-python\"\n",
2022-12-13 23:28:39 +00:00
"\n",
2022-03-11 02:08:53 +00:00
"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",
2022-12-13 23:28:39 +00:00
"\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",
2022-03-11 02:08:53 +00:00
"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",
2022-12-13 23:28:39 +00:00
"print(\"Total number of functions extracted:\", len(all_funcs))"
2022-03-11 02:08:53 +00:00
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>code</th>\n",
" <th>function_name</th>\n",
" <th>filepath</th>\n",
" <th>code_embedding</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
2022-12-13 23:28:39 +00:00
" <td>def _console_log_level():\\n if openai.log i...</td>\n",
" <td>_console_log_level</td>\n",
" <td>/openai/util.py</td>\n",
" <td>[0.03389773145318031, -0.004390408284962177, 0...</td>\n",
2022-03-11 02:08:53 +00:00
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
2022-12-13 23:28:39 +00:00
" <td>def log_debug(message, **params):\\n msg = l...</td>\n",
" <td>log_debug</td>\n",
" <td>/openai/util.py</td>\n",
" <td>[-0.004034275189042091, 0.004895383026450872, ...</td>\n",
2022-03-11 02:08:53 +00:00
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
2022-12-13 23:28:39 +00:00
" <td>def log_info(message, **params):\\n msg = lo...</td>\n",
" <td>log_info</td>\n",
" <td>/openai/util.py</td>\n",
" <td>[0.004882764536887407, 0.0033515947870910168, ...</td>\n",
2022-03-11 02:08:53 +00:00
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
2022-12-13 23:28:39 +00:00
" <td>def log_warn(message, **params):\\n msg = lo...</td>\n",
" <td>log_warn</td>\n",
" <td>/openai/util.py</td>\n",
" <td>[0.002535992069169879, -0.010829543694853783, ...</td>\n",
2022-03-11 02:08:53 +00:00
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
2022-12-13 23:28:39 +00:00
" <td>def logfmt(props):\\n def fmt(key, val):\\n ...</td>\n",
" <td>logfmt</td>\n",
" <td>/openai/util.py</td>\n",
" <td>[0.016732551157474518, 0.017367802560329437, 0...</td>\n",
2022-03-11 02:08:53 +00:00
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
2022-12-13 23:28:39 +00:00
" 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",
2022-03-11 02:08:53 +00:00
"\n",
2022-12-13 23:28:39 +00:00
" 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... "
2022-03-11 02:08:53 +00:00
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from openai.embeddings_utils import get_embedding\n",
"\n",
"df = pd.DataFrame(all_funcs)\n",
2022-12-13 23:28:39 +00:00
"df['code_embedding'] = df['code'].apply(lambda x: get_embedding(x, engine='text-embedding-ada-002'))\n",
2022-03-11 02:08:53 +00:00
"df['filepath'] = df['filepath'].apply(lambda x: x.replace(code_root, \"\"))\n",
2022-12-13 23:28:39 +00:00
"df.to_csv(\"data/code_search_openai-python.csv\", index=False)\n",
2022-03-11 02:08:53 +00:00
"df.head()"
]
},
{
"cell_type": "code",
2022-12-13 23:28:39 +00:00
"execution_count": 3,
2022-03-11 02:08:53 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-12-13 23:28:39 +00:00
"/openai/tests/test_endpoints.py:test_completions score=0.826\n",
2022-03-11 02:08:53 +00:00
"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",
2022-12-13 23:28:39 +00:00
"/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",
2022-03-11 02:08:53 +00:00
"\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",
2022-12-13 23:28:39 +00:00
" embedding = get_embedding(code_query, engine='text-embedding-ada-002')\n",
2022-03-11 02:08:53 +00:00
" 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",
2022-12-13 23:28:39 +00:00
"\n",
"res = search_functions(df, 'Completions API tests', n=3)"
2022-03-11 02:08:53 +00:00
]
},
{
"cell_type": "code",
2022-12-13 23:28:39 +00:00
"execution_count": 4,
2022-03-11 02:08:53 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-12-13 23:28:39 +00:00
"/openai/validators.py:format_inferrer_validator score=0.751\n",
2022-03-11 02:08:53 +00:00
"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",
2022-12-13 23:28:39 +00:00
"/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",
2022-03-11 02:08:53 +00:00
"----------------------------------------------------------------------\n",
2022-12-13 23:28:39 +00:00
"/openai/validators.py:infer_task_type score=0.738\n",
"def infer_task_type(df):\n",
2022-03-11 02:08:53 +00:00
" \"\"\"\n",
2022-12-13 23:28:39 +00:00
" Infer the likely fine-tuning task type from the data\n",
2022-03-11 02:08:53 +00:00
" \"\"\"\n",
2022-12-13 23:28:39 +00:00
" CLASSIFICATION_THRESHOLD = 3 # min_average instances of each class\n",
" if sum(df.prompt.str.len()) == 0:\n",
" return \"open-ended generation\"\n",
2022-03-11 02:08:53 +00:00
"----------------------------------------------------------------------\n"
]
}
],
"source": [
"res = search_functions(df, 'fine-tuning input data validation logic', n=3)"
]
},
{
"cell_type": "code",
2022-12-13 23:28:39 +00:00
"execution_count": 5,
2022-03-11 02:08:53 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-12-13 23:28:39 +00:00
"/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",
2022-03-11 02:08:53 +00:00
"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",
2022-12-13 23:28:39 +00:00
"execution_count": 6,
2022-03-11 02:08:53 +00:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-12-13 23:28:39 +00:00
"/openai/cli.py:tools_register score=0.773\n",
2022-03-11 02:08:53 +00:00
"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": {
2022-12-13 23:28:39 +00:00
"display_name": "openai-cookbook",
"language": "python",
"name": "openai-cookbook"
2022-03-11 02:08:53 +00:00
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
2022-12-13 23:28:39 +00:00
"version": "3.9.6"
2022-03-11 02:08:53 +00:00
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}