π‘ All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add notebook for prompt-driven search with LLMs, closes #418
davidmezzetti33110c12ba24
diff --git a/README.md b/README.mdindex 72f78e03..75a0dad8 100644--- a/README.md+++ b/README.md@@ -143,6 +143,7 @@ Build semantic/similarity/vector/neural search applications.| [Embeddings components](https://github.com/neuml/txtai/blob/master/examples/37_Embeddings_index_components.ipynb) | Composable search with vector, SQL and scoring components | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/37_Embeddings_index_components.ipynb) || [Semantic Graphs](https://github.com/neuml/txtai/blob/master/examples/38_Introducing_the_Semantic_Graph.ipynb) | Explore topics, data connectivity and run network analysis| [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/38_Introducing_the_Semantic_Graph.ipynb) || [Topic Modeling with BM25](https://github.com/neuml/txtai/blob/master/examples/39_Classic_Topic_Modeling_with_BM25.ipynb) | Topic modeling backed by a BM25 index | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/39_Classic_Topic_Modeling_with_BM25.ipynb) |+| [Prompt-driven search with LLMs](https://github.com/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) | Embeddings-guided and Prompt-driven search with Large Language Models (LLMs) | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) |### Pipelinesdiff --git a/docs/examples.md b/docs/examples.mdindex e0858d1e..b449d6e8 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -26,6 +26,7 @@ Build semantic/similarity/vector/neural search applications.| [Embeddings components](https://github.com/neuml/txtai/blob/master/examples/37_Embeddings_index_components.ipynb) | Composable search with vector, SQL and scoring components | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/37_Embeddings_index_components.ipynb) || [Semantic Graphs](https://github.com/neuml/txtai/blob/master/examples/38_Introducing_the_Semantic_Graph.ipynb) | Explore topics, data connectivity and run network analysis| [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/38_Introducing_the_Semantic_Graph.ipynb) || [Topic Modeling with BM25](https://github.com/neuml/txtai/blob/master/examples/39_Classic_Topic_Modeling_with_BM25.ipynb) | Topic modeling backed by a BM25 index | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/39_Classic_Topic_Modeling_with_BM25.ipynb) |+| [Prompt-driven search with LLMs](https://github.com/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) | Embeddings-guided and Prompt-driven search with Large Language Models (LLMs) | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) |## Pipelinesdiff --git a/docs/pipeline/text/extractor.md b/docs/pipeline/text/extractor.mdindex 80c16653..8f548c0f 100644--- a/docs/pipeline/text/extractor.md+++ b/docs/pipeline/text/extractor.md@@ -29,6 +29,7 @@ See the links below for more detailed examples.| [Extractive QA with txtai](https://github.com/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb) | Introduction to extractive question-answering with txtai | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/05_Extractive_QA_with_txtai.ipynb) || [Extractive QA with Elasticsearch](https://github.com/neuml/txtai/blob/master/examples/06_Extractive_QA_with_Elasticsearch.ipynb) | Run extractive question-answering queries with Elasticsearch | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/06_Extractive_QA_with_Elasticsearch.ipynb) || [Extractive QA to build structured data](https://github.com/neuml/txtai/blob/master/examples/20_Extractive_QA_to_build_structured_data.ipynb) | Build structured datasets using extractive question-answering | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/20_Extractive_QA_to_build_structured_data.ipynb) |+| [Prompt-driven search with LLMs](https://github.com/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) | Embeddings-guided and Prompt-driven search with Large Language Models (LLMs) | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/42_Prompt_driven_search_with_LLMs.ipynb) |## Configuration-driven examplediff --git a/examples/42_Prompt_driven_search_with_LLMs.ipynb b/examples/42_Prompt_driven_search_with_LLMs.ipynbnew file mode 100644index 00000000..76a115f8--- /dev/null+++ b/examples/42_Prompt_driven_search_with_LLMs.ipynb@@ -0,0 +1,558 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "colab": {+ "provenance": []+ },+ "kernelspec": {+ "name": "python3",+ "display_name": "Python 3"+ },+ "accelerator": "GPU",+ "gpuClass": "standard"+ },+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "vwELCooy4ljr"+ },+ "source": [+ "# Prompt-driven search with LLMs\n",+ "\n",+ "_This notebook is part of a tutorial series on [txtai](https://github.com/neuml/txtai), an AI-powered semantic search platform._\n",+ "\n",+ "\n",+ "[txtai](https://github.com/neuml/txtai) executes machine-learning workflows to transform data and build AI-powered semantic search applications.\n",+ "\n",+ "This notebook revisits the Extractor pipeline, which has been covered in a number of previous notebooks. This pipeline is a combination of a similarity instance (embeddings or similarity pipeline) to build a question context and a model that answers questions.\n",+ "\n",+ "The Extractor pipeline recently underwent a number of major upgrades to support the following.\n",+ "\n",+ "- Ability to run embeddings searches. Given that content is supported, text can be retrieved from the embeddings instance.\n",+ "- In addition to extractive qa, support text generation models, sequence to sequence models and custom pipelines\n",+ "\n",+ "These changes enable embeddings-guided and prompt-driven search with Large Language Models (LLMs) π₯π₯π₯"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "ew7orE2O441o"+ },+ "source": [+ "# Install dependencies\n",+ "\n",+ "Install `txtai` and all dependencies."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "LPQTb25tASIG"+ },+ "source": [+ "%%capture\n",+ "!pip install git+https://github.com/neuml/txtai datasets"+ ],+ "execution_count": 25,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_YnqorRKAbLu"+ },+ "source": [+ "# Create Embeddings and Extractor instances\n",+ "\n",+ "An Embeddings instance defines methods to represent text as vectors and build vector indexes for search.\n",+ "\n",+ "The Extractor pipeline is a combination of a similarity instance (embeddings or similarity pipeline) to build a question context and a model that answers questions. The model can be a prompt-driven large language model (LLM), an extractive question-answering model or a custom pipeline.\n",+ "\n",+ "Let's run a basic example.\n"+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "OUc9gqTyAYnm"+ },+ "source": [+ "%%capture\n",+ "\n",+ "from txtai.embeddings import Embeddings\n",+ "from txtai.pipeline import Extractor\n",+ "\n",+ "# Create embeddings model with content support\n",+ "embeddings = Embeddings({\"path\": \"sentence-transformers/all-MiniLM-L6-v2\", \"content\": True})\n",+ "\n",+ "# Create extractor instance\n",+ "extractor = Extractor(embeddings, \"google/flan-t5-base\")"+ ],+ "execution_count": 26,+ "outputs": []+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "4X5z3UjnAGe7",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "141284a7-83e3-4c28-bb14-cef9d47a7650"+ },+ "source": [+ "data = [\"Giants hit 3 HRs to down Dodgers\",\n",+ " \"Giants 5 Dodgers 4 final\",\n",+ " \"Dodgers drop Game 2 against the Giants, 5-4\",\n",+ " \"Blue Jays beat Red Sox final score 2-1\",\n",+ " \"Red Sox lost to the Blue Jays, 2-1\",\n",+ " \"Blue Jays at Red Sox is over. Score: 2-1\",\n",+ " \"Phillies win over the Braves, 5-0\",\n",+ " \"Phillies 5 Braves 0 final\",\n",+ " \"Final: Braves lose to the Phillies in the series opener, 5-0\",\n",+ " \"Lightning goaltender pulled, lose to Flyers 4-1\",\n",+ " \"Flyers 4 Lightning 1 final\",\n",+ " \"Flyers win 4-1\"]\n",+ "\n",+ "def prompt(question):\n",+ " return f\"\"\"\n",+ " Answer the following question using the context below.\n",+ " Question: {question}\n",+ " Context:\n",+ " \"\"\"\n",+ "\n",+ "questions = [\"What team won the game?\", \"What was score?\"]\n",+ "\n",+ "execute = lambda query: extractor([(question, query, prompt(question), False) for question in questions], data)\n",+ "\n",+ "for query in [\"Red Sox - Blue Jays\", \"Phillies - Braves\", \"Dodgers - Giants\", \"Flyers - Lightning\"]:\n",+ " print(\"----\", query, \"----\")\n",+ " for answer in execute(query):\n",+ " print(answer)\n",+ " print()"+ ],+ "execution_count": 27,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "---- Red Sox - Blue Jays ----\n",+ "('What team won the game?', 'Blue Jays')\n",+ "('What was score?', '2-1')\n",+ "\n",+ "---- Phillies - Braves ----\n",+ "('What team won the game?', 'Phillies')\n",+ "('What was score?', '5-0')\n",+ "\n",+ "---- Dodgers - Giants ----\n",+ "('What team won the game?', 'Giants')\n",+ "('What was score?', '5-4')\n",+ "\n",+ "---- Flyers - Lightning ----\n",+ "('What team won the game?', 'Flyers')\n",+ "('What was score?', '4-1')\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "This code runs a series of questions. First it runs an embeddings filtering query to find the most relevant text. For example, `Red Sox - Blue Jays` finds text related to those teams. Then `What team won the game?` and `What was the score?` are asked.\n",+ "\n",+ "This logic is the same logic found in Notebook 5 - Extractive QA with txtai but uses prompt-based QA vs extractive QA. "+ ],+ "metadata": {+ "id": "7AnPvSeM3N1Z"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "# Embeddings-guided and Prompt-driven Search\n",+ "\n",+ "Now for the fun stuff. Let's build an embeddings index for the `ag_news` dataset (a set of news stories from the mid 2000s). Then we'll use prompts to ask questions with embeddings results as the context."+ ],+ "metadata": {+ "id": "Aj8GoDk331cS"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "from datasets import load_dataset\n",+ "\n",+ "dataset = load_dataset(\"ag_news\", split=\"train\")\n",+ "\n",+ "# List of all text elements\n",+ "texts = dataset[\"text\"]\n",+ "\n",+ "# Create an embeddings index over the dataset\n",+ "embeddings = Embeddings({\"path\": \"sentence-transformers/all-MiniLM-L6-v2\", \"content\": True})\n",+ "embeddings.index((x, text, None) for x, text in enumerate(texts))\n",+ "\n",+ "# Create extractor instance\n",+ "extractor = Extractor(embeddings, \"google/flan-t5-large\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "yL716oEZ43t-",+ "outputId": "835a72bd-ab7e-48c5-96b1-66ab8da1e5b2"+ },+ "execution_count": 28,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stderr",+ "text": [+ "WARNING:datasets.builder:Found cached dataset ag_news (/root/.cache/huggingface/datasets/ag_news/default/0.0.0/bc2bcb40336ace1a0374767fc29bb0296cdaf8a6da7298436239c54d79180548)\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Now let's run a prompt-driven search!"+ ],+ "metadata": {+ "id": "Ifl8JwLDBL7k"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "def prompt(question):\n",+ " return f\"\"\"Answer the following question using only the context below. Say 'no answer' when the question can't be answered.\n",+ "Question: {question}\n",+ "Context: \"\"\"\n",+ "\n",+ "def search(query, question=None):\n",+ " # Default question to query if empty\n",+ " if not question:\n",+ " question = query\n",+ "\n",+ " return extractor([(\"answer\", query, prompt(question), False)])[0][1]\n",+ "\n",+ "question = \"Who won the 2004 presidential election?\"\n",+ "answer = search(question)\n",+ "print(question, answer)\n",+ "\n",+ "nquestion = \"Who did the candidate beat?\"\n",+ "print(nquestion, search(f\"{question} {answer}. {nquestion}\"))"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "5O1WBJ8153Mo",+ "outputId": "e60d5c1b-088c-4e50-da3a-d61781b9dd7c"+ },+ "execution_count": 29,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Who won the 2004 presidential election? George W. Bush\n",+ "Who did the candidate beat? John F. Kerry\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "And there are the answers. Let's unpack how this works.\n",+ "\n",+ "The first thing the Extractor pipeline does is run an embeddings search to find the most relevant text within the index. A context string is then built using those search results.\n",+ "\n",+ "After that, a prompt is generated, run and the answer printed. Let's see what a full prompt looks like."+ ],+ "metadata": {+ "id": "AhViFXH_BZSo"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "text = prompt(question)\n",+ "text += \"\\n\" + \"\\n\".join(x[\"text\"]for x in embeddings.search(question))\n",+ "print(text)"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "h7BsoJC3CFOq",+ "outputId": "9d522335-5f2f-4853-98cb-98ec09fcfcc4"+ },+ "execution_count": 30,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Answer the following question using only the context below. Say 'no answer' when the question can't be answered.\n",+ "Question: Who won the 2004 presidential election?\n",+ "Context: \n",+ "Right- and left-click politics The 2004 presidential race ended last week in a stunning defeat for Massachusetts Senator John F. Kerry, as incumbent President George W. Bush cruised to an easy victory.\n",+ "2004 Presidential Endorsements (AP) AP - Newspaper endorsements in the 2004 presidential campaign between President Bush, a Republican, and Sen. John Kerry, a Democrat.\n",+ "Presidential Campaign to Nov. 2, 2004 (Reuters) Reuters - The following diary of events\\leading up to the presidential election on Nov. 2.\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "The prompt has the information needed to determine the answers to the questions."+ ],+ "metadata": {+ "id": "4m9XketCty3m"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "# Additional examples\n",+ "\n",+ "Before moving on, a couple more example questions."+ ],+ "metadata": {+ "id": "JtDcVPdOB0Rv"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "question = \"Who won the World Series in 2004?\"\n",+ "answer = search(question)\n",+ "print(question, answer)\n",+ "\n",+ "nquestion = \"Who did they beat?\"\n",+ "print(nquestion, search(f\"{question} {answer}. {nquestion}\"))"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "0NNLBwC-83MM",+ "outputId": "6d3c926d-b0f1-4b62-d1d9-afd252a4c3bb"+ },+ "execution_count": 31,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Who won the World Series in 2004? Boston\n",+ "Who did they beat? St Louis\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "source": [+ "search(\"Tell me something interesting?\")"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/",+ "height": 36+ },+ "id": "1P0zqkTW9cZW",+ "outputId": "f1bd4a7c-5936-4cfd-d25d-23811c0a3abe"+ },+ "execution_count": 32,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "'herrings communicate by farting'"+ ],+ "application/vnd.google.colaboratory.intrinsic+json": {+ "type": "string"+ }+ },+ "metadata": {},+ "execution_count": 32+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Whhaaaattt??? Is this a model hallucination?\n",+ "\n",+ "Let's run an embeddings query and see if that text is in the results."+ ],+ "metadata": {+ "id": "ygFFcwWPGI9p"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "answer = \"herrings communicate by farting\"\n",+ "for x in embeddings.search(\"Tell me something interesting?\"):\n",+ " if answer in x[\"text\"]:\n",+ " start = x[\"text\"].find(answer)\n",+ " print(x[\"text\"][start:start + len(answer)])"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "qZPhLqSxGMbK",+ "outputId": "790dae79-ad76-4522-a434-c40238a3549b"+ },+ "execution_count": 33,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "herrings communicate by farting\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Sure enough it is. It appears that the FLAN-T5 model has a bit of an immature sense of humor π"+ ],+ "metadata": {+ "id": "IpgxMc1DZcds"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "# External API Integration\n",+ "\n",+ "In addition to support for Hugging Face models, the Extractor pipeline also supports custom question-answer models. This could be a call to the OpenAI API (GPT-3), Cohere API, Hugging Face API or using langchain to manage that. All that is needed is a Callable object or a function!\n",+ "\n",+ "Let's see an example that uses the Hugging Face API to answer questions. We'll use the original sports dataset to demonstrate."+ ],+ "metadata": {+ "id": "7bitjzeyYOqh"+ }+ },+ {+ "cell_type": "code",+ "source": [+ "import requests\n",+ "\n",+ "data = [\"Giants hit 3 HRs to down Dodgers\",\n",+ " \"Giants 5 Dodgers 4 final\",\n",+ " \"Dodgers drop Game 2 against the Giants, 5-4\",\n",+ " \"Blue Jays beat Red Sox final score 2-1\",\n",+ " \"Red Sox lost to the Blue Jays, 2-1\",\n",+ " \"Blue Jays at Red Sox is over. Score: 2-1\",\n",+ " \"Phillies win over the Braves, 5-0\",\n",+ " \"Phillies 5 Braves 0 final\",\n",+ " \"Final: Braves lose to the Phillies in the series opener, 5-0\",\n",+ " \"Lightning goaltender pulled, lose to Flyers 4-1\",\n",+ " \"Flyers 4 Lightning 1 final\",\n",+ " \"Flyers win 4-1\"]\n",+ "\n",+ "def prompt(question):\n",+ " return f\"\"\"\n",+ " Answer the following question using the context below.\n",+ " Question: {question}\n",+ " Context:\n",+ " \"\"\"\n",+ "\n",+ "# Submits a series of prompts to the Hugging Face API.\n",+ "# This call can easily be switched to use the OpenAI API (GPT-3), Cohere API or a library like langchain.\n",+ "def api(prompts):\n",+ " response = requests.post(\"https://api-inference.huggingface.co/models/google/flan-t5-base\",\n",+ " json={\"inputs\": prompts})\n",+ "\n",+ " return [x[\"generated_text\"] for x in response.json()]\n",+ "\n",+ "# Create embeddings model with content support\n",+ "embeddings = Embeddings({\"path\": \"sentence-transformers/all-MiniLM-L6-v2\", \"content\": True})\n",+ "\n",+ "# Create extractor instance, submit prompts to the Hugging Face inference API\n",+ "extractor = Extractor(embeddings, api)\n",+ "\n",+ "questions = [\"What team won the game?\", \"What was score?\"]\n",+ "\n",+ "execute = lambda query: extractor([(question, query, prompt(question), False) for question in questions], data)\n",+ "\n",+ "for query in [\"Red Sox - Blue Jays\", \"Phillies - Braves\", \"Dodgers - Giants\", \"Flyers - Lightning\"]:\n",+ " print(\"----\", query, \"----\")\n",+ " for answer in execute(query):\n",+ " print(answer)\n",+ " print()\n"+ ],+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "yYAa9N7EYm7E",+ "outputId": "4bbd59d7-4ade-41f0-86e2-882c1eef6a34"+ },+ "execution_count": 37,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "---- Red Sox - Blue Jays ----\n",+ "('What team won the game?', 'Blue Jays')\n",+ "('What was score?', '2-1')\n",+ "\n",+ "---- Phillies - Braves ----\n",+ "('What team won the game?', 'Phillies')\n",+ "('What was score?', '5-0')\n",+ "\n",+ "---- Dodgers - Giants ----\n",+ "('What team won the game?', 'Giants')\n",+ "('What was score?', '5-4')\n",+ "\n",+ "---- Flyers - Lightning ----\n",+ "('What team won the game?', 'Flyers')\n",+ "('What was score?', '4-1')\n",+ "\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "source": [+ "Everything matches with first example above in [Create Embeddings and Extractor instances](#Create-Embeddings-and-Extractor-instances) except the prompts are run as an external API call.\n",+ "\n",+ "The Embeddings instance can also swap out the vectorization, database and vector store components with external API services. Check out the [txtai documentation](https://neuml.github.io/txtai/embeddings/configuration/) documentation for more information.\n",+ "\n"+ ],+ "metadata": {+ "id": "Xh8UhC3NdsGf"+ }+ },+ {+ "cell_type": "markdown",+ "source": [+ "# Wrapping up\n",+ "\n",+ "This notebook covered how to run embeddings-guided and prompt-driven search with LLMs. This functionality is a major step forward towards `Generative Semantic Search` for txtai. More to come, stay tuned!"+ ],+ "metadata": {+ "id": "KqfvCXp2B3li"+ }+ }+ ]+}\ No newline at end of file