Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

perf: Import smaller chuncks in AI Searcha

Clémence Lesné4c212c10a63c
diff --git a/examples/import-training.ipynb b/examples/import-training.ipynb
index a9228ed..463bbde 100644
--- a/examples/import-training.ipynb
+++ b/examples/import-training.ipynb
@@ -43,7 +43,7 @@
},
{
"cell_type": "code",
- "execution_count": 16,
+ "execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
@@ -142,15 +142,30 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 22,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[{'content': \"# Groupama ASSET MANAGEMENT docu d'inform cle === object le présent docu contient de inform essentiel sur le produit d'invest .il ne s'ag pas d'un docu à caracter commercial .\", 'id': 'dataset_be463817baf2441f9f5193fa10045711_msdoc_pdf-0', 'source_uri': 'dataset/be463817baf2441f9f5193fa10045711_msdoc.pdf', 'title': 'groupama asset management'}, {'content': \"# Groupama ASSET MANAGEMENT ce inform vous sont fourn conform à une oblig légal , afin de vous aid à comprendr en quoi consist ce produit et quel risqu , coût , gain et pert potentiel y sont associ , et de vous aid à le compar à d'autr produit .\", 'id': 'dataset_be463817baf2441f9f5193fa10045711_msdoc_pdf-1', 'source_uri': 'dataset/be463817baf2441f9f5193fa10045711_msdoc.pdf', 'title': 'groupama asset management'}, {'content': \"# GROUPAMA ULTRA SHORT TERM BOND Part E1 (C - EUR) Code ISIN : FR001400JH30 societ de gestion : sit internet : groupam asset manag http : //www .groupama-am .com/fr/ appel le 01 44 56 76 76 pour de plus ample inform .l'autor de march financi ( amf ) est charg du contrôl de groupam asset manag en ce qui concern ce docu d'inform clé .\", 'id': 'dataset_be463817baf2441f9f5193fa10045711_msdoc_pdf-2', 'source_uri': 'dataset/be463817baf2441f9f5193fa10045711_msdoc.pdf', 'title': 'groupama ultra short term bond part e1 c eur code isin fr001400jh30'}, {'content': \"# GROUPAMA ULTRA SHORT TERM BOND Part E1 (C - EUR) Code ISIN : FR001400JH30 groupam asset manag est agré en franc sous le nºgp9302 et réglement par l'amf .dat de derni révis du docu d'inform clé : 29 sept .\", 'id': 'dataset_be463817baf2441f9f5193fa10045711_msdoc_pdf-3', 'source_uri': 'dataset/be463817baf2441f9f5193fa10045711_msdoc.pdf', 'title': 'groupama ultra short term bond part e1 c eur code isin fr001400jh30'}, {'content': '# EN QUOI CONSISTE CE PRODUIT ? typ : organ de plac collect en valeur mobili ( opcvm ) , constitu sous form de fond commun de plac ( fcp ) de droit franc .dur : le produit a été initial cré pour une dur de 99 an .groupam asset manag a le droit de proced à la dissolu du produit de mani unilatéral .', 'id': 'dataset_be463817baf2441f9f5193fa10045711_msdoc_pdf-4', 'source_uri': 'dataset/be463817baf2441f9f5193fa10045711_msdoc.pdf', 'title': 'en quoi consiste ce produit'}]\n",
+ "Created 48111 chunks\n"
+ ]
+ }
+ ],
"source": [
"lang = \"french\"\n",
"stemmer = SnowballStemmer(lang)\n",
+ "sentence_r = r\"[^\\w\\s+\\-/'\\\",:;()@=]\"\n",
"\n",
"\n",
"def compress_and_clean(text: str) -> str:\n",
+ " \"\"\"\n",
+ " Compress and clean a text.\n",
+ "\n",
+ " Use the Snowball stemmer to stem words and remove all special characters, as the LLM does not give a damn.\n",
+ " \"\"\"\n",
" text = text.replace(\"\\\\\", \"\") # Remove all backslashes\n",
" text = re.sub(r\":[a-z]*:\", \"\", text) # Remove all :unselected: and :selected: tags\n",
" text = re.sub(r\"<!--[^<>]*-->\", \"\", text) # Remove all comments\n",
@@ -161,11 +176,16 @@
"\n",
"\n",
"def data(content: str, source_uri: str, title: str, iterator: int) -> dict[str, str]:\n",
+ " \"\"\"\n",
+ " Generate a data object for the search index.\n",
+ "\n",
+ " Use deterministic ID to avoid duplicates after a new run. Remove all special characters from title.\n",
+ " \"\"\"\n",
" return {\n",
- " \"content\": compress_and_clean(content),\n",
- " \"id\": f\"{'_'.join(re.sub('[^a-z0-9]', ' ', unidecode(source_uri).lower()).split())}-{iterator}\", # Use deterministic ID to avoid duplicates after a new run\n",
+ " \"content\": content,\n",
+ " \"id\": f\"{'_'.join(re.sub('[^a-z0-9]', ' ', unidecode(source_uri).lower()).split())}-{iterator}\",\n",
" \"source_uri\": unidecode(source_uri).lower(),\n",
- " \"title\": ' '.join(re.sub('[^a-z0-9]', ' ', unidecode(title).lower()).split()), # Remove all special characters\n",
+ " \"title\": ' '.join(re.sub('[^a-z0-9]', ' ', unidecode(title).lower()).split()),\n",
" }\n",
"\n",
"\n",
@@ -173,21 +193,43 @@
"iterator = 0\n",
"\n",
"for source, content in doc_results.items():\n",
+ " # Skip empty documents\n",
" if not content:\n",
" continue\n",
+ "\n",
+ " # Split the document into sections\n",
" for section in content.split(\"\\n#\"):\n",
" lines = section.split(\"\\n\")\n",
" title = lines[0].strip()\n",
" paragraph = \" \".join(lines[1:])\n",
+ "\n",
+ " # Skip empty sections\n",
" if not section:\n",
" continue\n",
- " chuncks.append(data(\n",
- " f\"# {title} {paragraph}\",\n",
- " source,\n",
- " title,\n",
- " iterator,\n",
- " ))\n",
- " iterator += 1\n",
+ "\n",
+ " # Split the paragraph into sentences and group them into groups of 300 characters\n",
+ " groups = []\n",
+ " group = \"\"\n",
+ " separators = re.findall(sentence_r, paragraph)\n",
+ " splits = re.split(sentence_r, paragraph)\n",
+ " for i, separator in enumerate(separators):\n",
+ " sentence = compress_and_clean(splits[i] + separator)\n",
+ " if len(group) + len(sentence) >= 300:\n",
+ " groups.append(group)\n",
+ " group = \"\"\n",
+ " group += sentence\n",
+ " if group:\n",
+ " groups.append(group)\n",
+ "\n",
+ " # Create a data object for each group\n",
+ " for group in groups:\n",
+ " chuncks.append(data(\n",
+ " f\"# {title} {group}\",\n",
+ " source,\n",
+ " title,\n",
+ " iterator,\n",
+ " ))\n",
+ " iterator += 1\n",
"\n",
"print(chuncks[:5])\n",
"print(f\"Created {len(chuncks)} chunks\")"
@@ -206,8 +248,14 @@
"metadata": {},
"outputs": [],
"source": [
- "print(f\"Uploading {len(chuncks)} documents to Azure Search\")\n",
- "search_client.merge_or_upload_documents(chuncks)\n",
+ "import_size = 10000\n",
+ "import_part = chuncks[:import_size]\n",
+ "while import_part:\n",
+ " print(f\"Uploading {len(import_part)} documents to Azure Search\")\n",
+ " search_client.merge_or_upload_documents(import_part)\n",
+ " chuncks = chuncks[import_size:]\n",
+ " import_part = chuncks[:import_size]\n",
+ "\n",
"print(f\"There are {search_client.get_document_count()} documents in the index\")"
]
},
@@ -227,7 +275,7 @@
},
{
"cell_type": "code",
- "execution_count": 26,
+ "execution_count": null,
"metadata": {},
"outputs": [],
"source": [
diff --git a/helpers/config_models/ai_search.py b/helpers/config_models/ai_search.py
index b87b6e8..b1b81c3 100644
--- a/helpers/config_models/ai_search.py
+++ b/helpers/config_models/ai_search.py
@@ -8,6 +8,4 @@ class AiSearchModel(BaseSettings):
expansion_k: int = 5
index: str
semantic_configuration: str
- top_k: int = (
- 5 # More than 5, responses latency is high (> 30 secs) with GPT-4 Turbo
- )
+ top_k: int = 15
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 4384ffa..33bb6be 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -20,6 +20,9 @@ class AiSearchSearch(ISearch):
def __init__(self, config: AiSearchModel):
_logger.info(f"Using AI Search {config.endpoint} with index {config.index}")
+ _logger.info(
+ f"Note: At 300 characters per document, each LLM call will use approx {300 * config.top_k * config.expansion_k / 4} tokens."
+ )
self._config = config
async def training_asearch_all(self, text: str) -> Optional[List[TrainingModel]]: