{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import asyncio\n", "import tiktoken\n", "from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "NAMESPACE = 'world_bank' # A relevant namespace to store our documents under." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Prepare Documents

\n" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZ9TCDDZAXHY6MQ2EM2P0WV", "metadata": {}, "outputs": [], "source": [ "with open('data/world_bank_articles.txt', encoding='utf-8') as f:\n", " texts = f.read()" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZ9R350F1RF5Z59XDZ18DSG", "metadata": {}, "outputs": [], "source": [ "separator = \"-\" * 150 # Defined earlier during webscraping\n", "\n", "# Necessary to limit the payload to and avoid a\n", "# 400: 'Request payload size exceeds the limit: 10000 bytes.'\n", "\n", "text_splitter = RecursiveCharacterTextSplitter(separators=[separator, \"\\n\\n\\n\", \"\\n\\n\", \"\\n\"], \n", " chunk_size=7000, # Empirically set from the output of CharacterTextSplitter\n", " chunk_overlap=0)\n", "docs = text_splitter.split_text(texts)\n", "len(docs)" ] }, { "cell_type": "code", "execution_count": null, "id": "01HYB6KQ7GA77RW1D4YRJQTNHM", "metadata": {}, "outputs": [], "source": [ "# TODO\n", "# Remove the separator to avoid filling retrieved context with distracting delimiters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Exploring Docs

" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZA60JDH7EZE8ZFCNVTPA1J", "metadata": {}, "outputs": [], "source": [ "def num_tokens_from_string(string: str, encoding_name: str) -> int:\n", " \"\"\"Returns the number of tokens in a text string.\"\"\"\n", " encoding = tiktoken.get_encoding(encoding_name)\n", " num_tokens = len(encoding.encode(string))\n", " return num_tokens" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZCET07B0AVHDV6RJX374JR", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "# Calculate the number of tokens for each document\n", "counts = [num_tokens_from_string(d, \"cl100k_base\") for d in docs]\n", "\n", "# Plotting the histogram of token counts\n", "plt.figure(figsize=(10, 6))\n", "plt.hist(counts, bins=30, color=\"blue\", edgecolor=\"black\", alpha=0.7)\n", "plt.title(\"Histogram of Token Counts\")\n", "plt.xlabel(\"Token Count\")\n", "plt.ylabel(\"Frequency\")\n", "plt.grid(axis=\"y\", alpha=0.75)\n", "\n", "# Display the histogram\n", "plt.show" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZCXXCRE80ZQDPY4SY0DH9N", "metadata": {}, "outputs": [], "source": [ "# Doc texts concat\n", "concatenated_content = \"\\n\\n\\n --- \\n\\n\\n\".join(docs)\n", "print(\n", " \"Num tokens in all context: %s\"\n", " % num_tokens_from_string(concatenated_content, \"cl100k_base\")\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Remarks\n", "Most of the documents are small ( < 2000 tokens ) though some are considerably longer at around 8000 tokens. The whole corpus is just shy of 90000 tokens. This is too large to fit in standard 32k context windows." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Define Model

" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from langchain_google_genai import ChatGoogleGenerativeAI" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = ChatGoogleGenerativeAI(google_api_key=os.getenv('GOOGLE_API_KEY'), model='gemini-pro')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Clustering

\n", "\n", "Now onto step two. Given the embeddings we have gotten we now cluster the texts. There are various well-researched techniques available to us." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from custom.gemini_async import async_embed # Custom module" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZCSYAH3C5ZV69EFX4938GC", "metadata": {}, "outputs": [], "source": [ "from typing import Dict, List, Optional, Tuple\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import umap\n", "from langchain.prompts import ChatPromptTemplate\n", "from langchain_core.output_parsers import StrOutputParser\n", "from sklearn.mixture import GaussianMixture\n", "\n", "RANDOM_SEED = 224 # Fixed seed for reproducibility\n", "\n", "\n", "def global_cluster_embeddings(\n", " embeddings: np.ndarray,\n", " dim: int,\n", " n_neighbors: Optional[int] = None,\n", " metric: str = \"cosine\",\n", ") -> np.ndarray:\n", " \"\"\"\n", " Perform global dimensionality reduction on the embeddings using UMAP.\n", "\n", " Parameters:\n", " - embeddings: The input embeddings as a numpy array.\n", " - dim: The target dimensionality for the reduced space.\n", " - n_neighbors: Optional; the number of neighbors to consider for each point.\n", " If not provided, it defaults to the square root of the number of embeddings.\n", " - metric: The distance metric to use for UMAP.\n", "\n", " Returns:\n", " - A numpy array of the embeddings reduced to the specified dimensionality.\n", " \"\"\"\n", " if n_neighbors is None:\n", " n_neighbors = int((len(embeddings) - 1) ** 0.5)\n", " return umap.UMAP(\n", " n_neighbors=n_neighbors, n_components=dim, metric=metric\n", " ).fit_transform(embeddings)\n", "\n", "\n", "def local_cluster_embeddings(\n", " embeddings: np.ndarray, dim: int, num_neighbors: int = 10, metric: str = \"cosine\"\n", ") -> np.ndarray:\n", " \"\"\"\n", " Perform local dimensionality reduction on the embeddings using UMAP, typically after global clustering.\n", "\n", " Parameters:\n", " - embeddings: The input embeddings as a numpy array.\n", " - dim: The target dimensionality for the reduced space.\n", " - num_neighbors: The number of neighbors to consider for each point.\n", " - metric: The distance metric to use for UMAP.\n", "\n", " Returns:\n", " - A numpy array of the embeddings reduced to the specified dimensionality.\n", " \"\"\"\n", " return umap.UMAP(\n", " n_neighbors=num_neighbors, n_components=dim, metric=metric\n", " ).fit_transform(embeddings)\n", "\n", "\n", "def get_optimal_clusters(\n", " embeddings: np.ndarray, max_clusters: int = 50, random_state: int = RANDOM_SEED\n", ") -> int:\n", " \"\"\"\n", " Determine the optimal number of clusters using the Bayesian Information Criterion (BIC) with a Gaussian Mixture Model.\n", "\n", " Parameters:\n", " - embeddings: The input embeddings as a numpy array.\n", " - max_clusters: The maximum number of clusters to consider.\n", " - random_state: Seed for reproducibility.\n", "\n", " Returns:\n", " - An integer representing the optimal number of clusters found.\n", " \"\"\"\n", " max_clusters = min(max_clusters, len(embeddings))\n", " n_clusters = np.arange(1, max_clusters)\n", " bics = []\n", " for n in n_clusters:\n", " gm = GaussianMixture(n_components=n, random_state=random_state)\n", " gm.fit(embeddings)\n", " bics.append(gm.bic(embeddings))\n", " return n_clusters[np.argmin(bics)]\n", "\n", "\n", "def GMM_cluster(embeddings: np.ndarray, threshold: float, random_state: int = 0):\n", " \"\"\"\n", " Cluster embeddings using a Gaussian Mixture Model (GMM) based on a probability threshold.\n", "\n", " Parameters:\n", " - embeddings: The input embeddings as a numpy array.\n", " - threshold: The probability threshold for assigning an embedding to a cluster.\n", " - random_state: Seed for reproducibility.\n", "\n", " Returns:\n", " - A tuple containing the cluster labels and the number of clusters determined.\n", " \"\"\"\n", " n_clusters = get_optimal_clusters(embeddings)\n", " gm = GaussianMixture(n_components=n_clusters, random_state=random_state)\n", " gm.fit(embeddings)\n", " probs = gm.predict_proba(embeddings)\n", " labels = [np.where(prob > threshold)[0] for prob in probs]\n", " return labels, n_clusters\n", "\n", "\n", "def perform_clustering(\n", " embeddings: np.ndarray,\n", " dim: int,\n", " threshold: float,\n", ") -> List[np.ndarray]:\n", " \"\"\"\n", " Perform clustering on the embeddings by first reducing their dimensionality globally, then clustering\n", " using a Gaussian Mixture Model, and finally performing local clustering within each global cluster.\n", "\n", " Parameters:\n", " - embeddings: The input embeddings as a numpy array.\n", " - dim: The target dimensionality for UMAP reduction.\n", " - threshold: The probability threshold for assigning an embedding to a cluster in GMM.\n", "\n", " Returns:\n", " - A list of numpy arrays, where each array contains the cluster IDs for each embedding.\n", " \"\"\"\n", " if len(embeddings) <= dim + 1:\n", " # Avoid clustering when there's insufficient data\n", " return [np.array([0]) for _ in range(len(embeddings))]\n", "\n", " # Global dimensionality reduction\n", " reduced_embeddings_global = global_cluster_embeddings(embeddings, dim)\n", " # Global clustering\n", " global_clusters, n_global_clusters = GMM_cluster(\n", " reduced_embeddings_global, threshold\n", " )\n", "\n", " all_local_clusters = [np.array([]) for _ in range(len(embeddings))]\n", " total_clusters = 0\n", "\n", " # Iterate through each global cluster to perform local clustering\n", " for i in range(n_global_clusters):\n", " # Extract embeddings belonging to the current global cluster\n", " global_cluster_embeddings_ = embeddings[\n", " np.array([i in gc for gc in global_clusters])\n", " ]\n", "\n", " if len(global_cluster_embeddings_) == 0:\n", " continue\n", " if len(global_cluster_embeddings_) <= dim + 1:\n", " # Handle small clusters with direct assignment\n", " local_clusters = [np.array([0]) for _ in global_cluster_embeddings_]\n", " n_local_clusters = 1\n", " else:\n", " # Local dimensionality reduction and clustering\n", " reduced_embeddings_local = local_cluster_embeddings(\n", " global_cluster_embeddings_, dim\n", " )\n", " local_clusters, n_local_clusters = GMM_cluster(\n", " reduced_embeddings_local, threshold\n", " )\n", "\n", " # Assign local cluster IDs, adjusting for total clusters already processed\n", " for j in range(n_local_clusters):\n", " local_cluster_embeddings_ = global_cluster_embeddings_[\n", " np.array([j in lc for lc in local_clusters])\n", " ]\n", " indices = np.where(\n", " (embeddings == local_cluster_embeddings_[:, None]).all(-1)\n", " )[1]\n", " for idx in indices:\n", " all_local_clusters[idx] = np.append(\n", " all_local_clusters[idx], j + total_clusters\n", " )\n", "\n", " total_clusters += n_local_clusters\n", "\n", " return all_local_clusters\n" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZF1JG63PCW32XKGWBB0813", "metadata": {}, "outputs": [], "source": [ "async def async_embed_with_postprocess(texts: list[str]) -> list[float]:\n", " \"\"\"Call custom async embedder and return embeddings with an (informal) interface acceptable to downstream operations\"\"\"\n", "\n", " # await the asynchronous embedding function\n", " # In a jupyter notebook trying to start an event loop with asyncio.run witll result in an error\n", " all_embeddings = await async_embed(texts)\n", "\n", " try:\n", " raw_embeddings = [sub_embedding['embedding']['values'] \n", " for sub_embedding in [embedding['embeddings'] \n", " for embedding in all_embeddings]]\n", " except KeyError:\n", " raise Exception(\"Possible HTTP CODE 400: 'Request payload size exceeds the limit: 10000 bytes. Documents may be too large\")\n", " return raw_embeddings" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# TODO\n", "# The summary prompts HAVE to be changed to make them generalized.\n", "# They are currently too specific to the use case of the authors.\n", "# Perhaps the user can specify the general topic to better guide the LLM." ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZDX8HD0G37BGK4KQH5712P", "metadata": {}, "outputs": [], "source": [ "async def embed_cluster_texts(texts: list[str]) -> pd.DataFrame:\n", " \"\"\"\n", " Embeds a list of texts and clusters them, returning a DataFrame with texts, their embeddings, and cluster labels.\n", "\n", " This function combines embedding generation and clustering into a single step. It assumes the existence\n", " of a previously defined `perform_clustering` function that performs clustering on the embeddings.\n", "\n", " Parameters:\n", " - texts: List[str], a list of text documents to be processed.\n", "\n", " Returns:\n", " - pandas.DataFrame: A DataFrame containing the original texts, their embeddings, and the assigned cluster labels.\n", " \"\"\"\n", " embed_list_2d = await async_embed_with_postprocess(texts) # Generate embeddings\n", " text_embeddings_np = np.array(embed_list_2d)\n", " \n", " cluster_labels = perform_clustering(\n", " text_embeddings_np, 10, 0.1\n", " ) # Perform clustering on the embeddings\n", " df = pd.DataFrame() # Initialize a DataFrame to store the results\n", " df[\"text\"] = texts # Store original texts\n", " df[\"embd\"] = list(text_embeddings_np) # Store embeddings as a list in the DataFrame\n", " df[\"cluster\"] = cluster_labels # Store cluster labels\n", " return df\n", "\n", "def fmt_txt(df: pd.DataFrame) -> str:\n", " \"\"\"\n", " Formats the text documents in a DataFrame into a single string.\n", "\n", " Parameters:\n", " - df: DataFrame containing the 'text' column with text documents to format.\n", "\n", " Returns:\n", " - A single string where all text documents are joined by a specific delimiter.\n", " \"\"\"\n", " unique_txt = df[\"text\"].tolist()\n", " return \"--- --- \\n --- --- \".join(unique_txt)\n", "\n", "async def embed_cluster_summarize_texts(\n", " texts: List[str], level: int\n", ") -> Tuple[pd.DataFrame, pd.DataFrame]:\n", " \"\"\"\n", " Embeds, clusters, and summarizes a list of texts. This function first generates embeddings for the texts,\n", " clusters them based on similarity, expands the cluster assignments for easier processing, and then summarizes\n", " the content within each cluster.\n", "\n", " Parameters:\n", " - texts: A list of text documents to be processed.\n", " - level: An integer parameter that could define the depth or detail of processing.\n", "\n", " Returns:\n", " - Tuple containing two DataFrames:\n", " 1. The first DataFrame (`df_clusters`) includes the original texts, their embeddings, and cluster assignments.\n", " 2. The second DataFrame (`df_summary`) contains summaries for each cluster, the specified level of detail,\n", " and the cluster identifiers.\n", " \"\"\"\n", "\n", " # Embed and cluster the texts, resulting in a DataFrame with 'text', 'embd', and 'cluster' columns\n", " df_clusters = await embed_cluster_texts(texts)\n", "\n", " # Prepare to expand the DataFrame for easier manipulation of clusters\n", " expanded_list = []\n", "\n", " # Expand DataFrame entries to document-cluster pairings for straightforward processing\n", " for index, row in df_clusters.iterrows():\n", " for cluster in row[\"cluster\"]:\n", " expanded_list.append(\n", " {\"text\": row[\"text\"], \"embd\": row[\"embd\"], \"cluster\": cluster}\n", " )\n", "\n", " # Create a new DataFrame from the expanded list\n", " expanded_df = pd.DataFrame(expanded_list)\n", "\n", " # Retrieve unique cluster identifiers for processing\n", " all_clusters = expanded_df[\"cluster\"].unique()\n", "\n", " print(f\"--Generated {len(all_clusters)} clusters--\")\n", "\n", " # Summarization\n", " template = \"\"\"\n", " This is a summarization task in 20 or so words\n", " Your goal is to be descriptive but concise.\n", " Create something like an abstract; a fitting summarization of the whole document.\n", " You are expected to summarize the following document:\n", " ```\n", " {context}\n", " ```\n", " \n", " \"\"\"\n", " prompt = ChatPromptTemplate.from_template(template)\n", " chain = prompt | model | StrOutputParser()\n", "\n", " # Format text within each cluster for summarization\n", " summaries = []\n", " for i in all_clusters:\n", " df_cluster = expanded_df[expanded_df[\"cluster\"] == i]\n", " formatted_txt = fmt_txt(df_cluster)\n", " summaries.append(chain.invoke({\"context\": formatted_txt}))\n", " await asyncio.sleep(2)\n", "\n", " # Create a DataFrame to store summaries with their corresponding cluster and level\n", " df_summary = pd.DataFrame(\n", " {\n", " \"summaries\": summaries,\n", " \"level\": [level] * len(summaries),\n", " \"cluster\": list(all_clusters),\n", " }\n", " )\n", "\n", " return df_clusters, df_summary\n", "\n", "async def recursive_embed_cluster_summarize(\n", " texts: List[str], level: int = 1, n_levels: int = 3\n", ") -> Dict[int, Tuple[pd.DataFrame, pd.DataFrame]]:\n", " \"\"\"\n", " Recursively embeds, clusters, and summarizes texts up to a specified level or until\n", " the number of unique clusters becomes 1, storing the results at each level.\n", "\n", " Parameters:\n", " - texts: List[str], texts to be processed.\n", " - level: int, current recursion level (starts at 1).\n", " - n_levels: int, maximum depth of recursion.\n", "\n", " Returns:\n", " - Dict[int, Tuple[pd.DataFrame, pd.DataFrame]], a dictionary where keys are the recursion\n", " levels and values are tuples containing the clusters DataFrame and summaries DataFrame at that level.\n", " \"\"\"\n", " results = {} # Dictionary to store results at each level\n", "\n", " # Perform embedding, clustering, and summarization for the current level\n", " df_clusters, df_summary = await embed_cluster_summarize_texts(texts, level)\n", "\n", " # Store the results of the current level\n", " results[level] = (df_clusters, df_summary)\n", "\n", " # Determine if further recursion is possible and meaningful\n", " unique_clusters = df_summary[\"cluster\"].nunique()\n", " if level < n_levels and unique_clusters > 1:\n", " # Use summaries as the input texts for the next level of recursion\n", " new_texts = df_summary[\"summaries\"].tolist()\n", " next_level_results = await recursive_embed_cluster_summarize(\n", " new_texts, level + 1, n_levels\n", " )\n", "\n", " # Merge the results from the next level into the current results dictionary\n", " results.update(next_level_results)\n", "\n", " return results" ] }, { "cell_type": "code", "execution_count": null, "id": "01HWZEDB0A0G7GT84R21S6RTVV", "metadata": {}, "outputs": [], "source": [ "# Build tree\n", "results = await recursive_embed_cluster_summarize(docs, # Leaf texts\n", " level=1, \n", " n_levels=3)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX44B793B2NBGPN2QSCT4A8W", "metadata": {}, "outputs": [], "source": [ "len(results)" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX44G8CT47PESNW3TR1B294T", "metadata": {}, "outputs": [], "source": [ "results[1][0]" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX44PP50EZ5T7W9PAX00HYAC", "metadata": {}, "outputs": [], "source": [ "results[1][0]['text'].tolist()\n", "results[1][0]['embd'].tolist()" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX445HS59D0WW7SE1604YB54", "metadata": {}, "outputs": [], "source": [ "# Extracting all summaries\n", "summaries: list[str] = []\n", "for level in sorted(results.keys()):\n", " summaries.extend(results[1][1]['summaries'].tolist())\n", "len(summaries)" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX44YEHJF6KHJTWPKE4A1QXA", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Remarks\n", "This mortly ensemble works! I have modified the original code to fit my use of asynchronous embeddings and I am glad they play well together.\n", "\n", "However, because of the payload limits imposed on us by the Gmeini API, we have had to resort to chunking our documents. This we inteded not to do, because the whole idea was to embed entire documents as they are and perform tree based RAG/ But the limitations of practical tools have forced a compromise upon us. We must make the best of it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Collapsed Tree Retrieval

\n", "\n", "> This involves flattening the tree structure into a single layer and then applying a k-nearest neighbors (kNN) search across all nodes simultaneously.\n", "\n", "It is reported to have the best performance.\n", "\n", "### Strategy\n", "\n", "We will have a two pronged strategy: upsert the texts and the summaries separately. They are flattened but we already have embeddings for the texts already. We got them during the clustering operation. There is no need to get them anew, that would be inefficient. We don't have the embeddings for the summaries though, these we get. Then we use the pinecone client to upsert them sequentially." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Pinecone CRUD Operations

\n", "\n", "We are going to go our own way in this section. Instead of using the absractions langchain provides us to interact with vectorstores, we will perform our operations using the `pinecone` client. This gives us finer control." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from pinecone import Pinecone\n", "import os, uuid" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pc = Pinecone(api_key=os.getenv('PINECONE_API_KEY'), environment='gcp-starter')\n", "\n", "# Pick an index at random\n", "index_ = pc.list_indexes()[0]\n", "index = pc.Index(index_['name'])\n", "\n", "# Check whether index matches our embedding dimension\n", "dim_a = index_['dimension']\n", "dim_b = len(results[1][0]['embd'][0]) # Pick any random embedding vector in our results\n", "\n", "if dim_a != dim_b:\n", " raise Exception(f\"Pinecone Index dimension: {dim_a} does not match Vector Embedding dimension {dim_b}\")\n", "\n", "# Delete namespace if found\n", "# Will be created anew when we upsert to it. Avoids duplication\n", "if NAMESPACE in index.describe_index_stats()['namespaces'].keys():\n", " index.delete(delete_all=True, namespace=NAMESPACE)\n", " index.describe_index_stats()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def pinecone_upsert(embeddings: list[float], texts: list[str], index: Pinecone.Index, namespace: str):\n", " \"\"\"Store embeddings and their corresponding text metadata in the pinecone vectorstore\"\"\"\n", " records = []\n", "\n", " for embedding, text in zip(embeddings, texts):\n", " records.append({\n", " 'id': str(uuid.uuid4().int),\n", " 'values': embedding,\n", " 'metadata': {\n", " 'text': text\n", " }\n", " })\n", "\n", " # Asynchronous upsert: Faster\n", " def chunker(seq, batch_size):\n", " return (seq[pos:pos + batch_size] for pos in range(0, len(seq), batch_size))\n", "\n", " async_results = [\n", " index.upsert(vectors=chunk, namespace=namespace, async_req=True)\n", " for chunk in chunker(records, batch_size=100)\n", " ]\n" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX4546ANV2QE9C934782AB8W", "metadata": {}, "outputs": [], "source": [ "# Iterate through the results to extract summaries from each level\n", "summaries: list[str] = []\n", "for level in sorted(results.keys()):\n", " summaries.extend(results[level][1]['summaries'].tolist())\n", "len(summaries)" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX457G9ZDARP0HZJ8V1PMHSD", "metadata": {}, "outputs": [], "source": [ "\n", "# Get summary embeddigs\n", "summary_embeddings = await async_embed(summaries)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Upsering summaries\n", "pinecone_upsert([vect['embeddings']['embedding']['values'] for vect in summary_embeddings],\n", " [txt['text_metadata'] for txt in summary_embeddings],\n", " index, \n", " NAMESPACE) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Upserting all texts\n", "pinecone_upsert(results[1][0]['embd'].tolist(),\n", " results[1][0]['text'].tolist(),\n", " index, \n", " NAMESPACE) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Remarks\n", "After a long process, we have been able to upsert our documments succesfully to pinecone. The moving parts don't fit very well and the construction is brittle. We move on but we will return to refactor." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "with open('data/sample_embeddings.json', \"w\") as file:\n", " json.dump(summary_embeddings, file, indent=4) # indent=4 for pretty printing" ] }, { "cell_type": "code", "execution_count": null, "id": "01HX4AB9X4ZRQ6Q39PYEX8W052", "metadata": {}, "outputs": [], "source": [ "# TODO\n", "# Scrape the whole page rather than the article only to include date and time and other references.\n", "# this may help with citation and grounding in time" ] }, { "cell_type": "code", "execution_count": null, "id": "01HYB6K630M45KV1KWWQHJ4V1K", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.10.4" } }, "nbformat": 4, "nbformat_minor": 2 }