💡 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 tabular pipeline, closes #136
davidmezzettifd5e450cfb2c
diff --git a/README.md b/README.mdindex 1641a68d..40682984 100644--- a/README.md+++ b/README.md@@ -114,6 +114,7 @@ NLP-backed data transformation pipelines and workflows.| [Transcribe audio to text](https://github.com/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) | Convert audio files to text | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) || [Translate text between languages](https://github.com/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) | Streamline machine translation and language detection | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) || [Run pipeline workflows](https://github.com/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) | Simple yet powerful constructs to efficiently process data | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) |+| [Transform tabular data with composable workflows](https://github.com/neuml/txtai/blob/master/examples/22_Transform_tabular_data_with_composable_workflows.ipynb) | Transform, index and search tabular data with workflows | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/22_Transform_tabular_data_with_composable_workflows.ipynb) |### Model Trainingdiff --git a/docs/examples.md b/docs/examples.mdindex 70335c8d..c355d186 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -31,6 +31,7 @@ NLP-backed data transformation pipelines and workflows.| [Transcribe audio to text](https://github.com/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) | Convert audio files to text | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/11_Transcribe_audio_to_text.ipynb) || [Translate text between languages](https://github.com/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) | Streamline machine translation and language detection | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/12_Translate_text_between_languages.ipynb) || [Run pipeline workflows](https://github.com/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) | Simple yet powerful constructs to efficiently process data | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/14_Run_pipeline_workflows.ipynb) |+| [Transform tabular data with composable workflows](https://github.com/neuml/txtai/blob/master/examples/22_Transform_tabular_data_with_composable_workflows.ipynb) | Transform, index and search tabular data with workflows | [](https://colab.research.google.com/github/neuml/txtai/blob/master/examples/22_Transform_tabular_data_with_composable_workflows.ipynb) |## Model Trainingdiff --git a/docs/workflows.md b/docs/workflows.mdindex 162c7340..c4c5bc61 100644--- a/docs/workflows.md+++ b/docs/workflows.md@@ -57,10 +57,14 @@ Task that processes image urlsTask that runs content against a http service+::: txtai.workflow.ServiceTask.__init__+### Storage TaskTask that expands a local directory or cloud storage bucket into a list of URLs to process+::: txtai.workflow.StorageTask.__init__+### URL TaskTask that processes urlsdiff --git a/examples/22_Transform_tabular_data_with_composable_workflows.ipynb b/examples/22_Transform_tabular_data_with_composable_workflows.ipynbnew file mode 100644index 00000000..f62073e3--- /dev/null+++ b/examples/22_Transform_tabular_data_with_composable_workflows.ipynb@@ -0,0 +1,819 @@+{+ "nbformat": 4,+ "nbformat_minor": 0,+ "metadata": {+ "accelerator": "GPU",+ "colab": {+ "name": "22 - Transform tabular data with composable workflows",+ "provenance": [],+ "collapsed_sections": []+ },+ "kernelspec": {+ "display_name": "Python 3",+ "name": "python3"+ }+ },+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "4Pjmz-RORV8E"+ },+ "source": [+ "# Transform tabular data with composable workflows\n",+ "\n",+ "txtai executes machine-learning workflows to transform data and build AI-powered semantic search applications. txtai has support for processing both unstructured and structured data. Structured or tabular data is grouped into rows and columns. This can be a spreadsheet, an API call that returns JSON or XML or even list of key-value pairs.\n",+ "\n",+ "This notebook will walk through examples on how to use workflows with the tabular pipeline to transform and index structured data.\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Dk31rbYjSTYm"+ },+ "source": [+ "# Install dependencies\n",+ "\n",+ "Install `txtai` and all dependencies. We will install the api, pipeline and workflow optional extras packages. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "XMQuuun2R06J"+ },+ "source": [+ "%%capture\n",+ "!pip install git+https://github.com/neuml/txtai#egg=txtai[api,pipeline,workflow]"+ ],+ "execution_count": 61,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "NSYrP0hjtR_E"+ },+ "source": [+ "# CSV Workflow\n",+ "\n",+ "The first example will transform and index a CSV file. The [COVID-19 Open Research Dataset](https://allenai.org/data/cord-19) (CORD-19) is a repository of medical articles covering COVID-19. This workflow reads the input CSV and builds a semantic search index.\n",+ "\n",+ "The first step is downloading the dataset locally."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "BoPJIKWoTibk"+ },+ "source": [+ "%%capture\n",+ "# Get CORD-19 metadata file\n",+ "!wget https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2021-11-01/metadata.csv\n",+ "!head -1 metadata.csv > input.csv\n",+ "!tail -10000 metadata.csv >> input.csv"+ ],+ "execution_count": 78,+ "outputs": []+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Q1ivX4eBuU8T"+ },+ "source": [+ "The next section creates a simple workflow consisting of a tabular pipeline. The tabular pipeline builds a list of (id, text, tag) tuples that can be easily loaded into an Embeddings index. For this example, we'll use the `url` column as the id and the `title` column as the text column. The textcolumns parameter takes a list of columns to support indexing text content from multiple columns. \n",+ "\n",+ "The file input.csv is processed and the first 5 rows are shown."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "-pi2QU3TSlM_",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "8f7b3807-fa98-46b3-b1c3-ca1de6e2de55"+ },+ "source": [+ "from txtai.pipeline import Tabular\n",+ "from txtai.workflow import Task, Workflow\n",+ "\n",+ "# Create tabular instance mapping input.csv fields\n",+ "tabular = Tabular(\"url\", [\"title\"])\n",+ "\n",+ "# Create workflow\n",+ "workflow = Workflow([Task(tabular)])\n",+ "\n",+ "# Print 5 rows of input.csv via workflow\n",+ "list(workflow([\"input.csv\"]))[:5]"+ ],+ "execution_count": 63,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "[('https://doi.org/10.1016/j.cmpb.2021.106469; https://www.ncbi.nlm.nih.gov/pubmed/34715516/',\n",+ " 'Computer simulation of the dynamics of a spatial susceptible-infected-recovered epidemic model with time delays in transmission and treatment.',\n",+ " None),\n",+ " ('https://www.ncbi.nlm.nih.gov/pubmed/34232002/; https://doi.org/10.36849/jdd.5544',\n",+ " 'Understanding the Potential Role of Abrocitinib in the Time of SARS-CoV-2',\n",+ " None),\n",+ " ('https://doi.org/10.1186/1471-2458-8-42; https://www.ncbi.nlm.nih.gov/pubmed/18234083/',\n",+ " \"Can the concept of Health Promoting Schools help to improve students' health knowledge and practices to combat the challenge of communicable diseases: Case study in Hong Kong?\",\n",+ " None),\n",+ " ('https://www.ncbi.nlm.nih.gov/pubmed/32983582/; https://www.sciencedirect.com/science/article/pii/S2095809920302514?v=s5; https://api.elsevier.com/content/article/pii/S2095809920302514; https://doi.org/10.1016/j.eng.2020.07.018',\n",+ " 'Buying time for an effective epidemic response: The impact of a public holiday for outbreak control on COVID-19 epidemic spread',\n",+ " None),\n",+ " ('https://doi.org/10.1093/pcmedi/pbab016',\n",+ " 'The SARS-CoV-2 spike L452R-E484Q variant in the Indian B.1.617 strain showed significant reduction in the neutralization activity of immune sera',\n",+ " None)]"+ ]+ },+ "metadata": {},+ "execution_count": 63+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "UYYKnwNhu0hv"+ },+ "source": [+ "Next, we take the workflow output, build an Embeddings index and run a search query."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "G7M34puLWeZm",+ "outputId": "3ce7f13c-3c87-4595-d41c-f972fb37379c"+ },+ "source": [+ "from txtai.embeddings import Embeddings\n",+ "\n",+ "# Embeddings with sentence-transformers backend\n",+ "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",+ "\n",+ "# Index subset of CORD-19 data\n",+ "data = list(workflow([\"input.csv\"]))\n",+ "embeddings.index(data)\n",+ "\n",+ "for uid, _ in embeddings.search(\"insulin\"):\n",+ " title = [text for url, text, _ in data if url == uid][0]\n",+ " print(title, uid)"+ ],+ "execution_count": 64,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Importance of diabetes management during the COVID-19 pandemic. https://doi.org/10.1080/00325481.2021.1978704; https://www.ncbi.nlm.nih.gov/pubmed/34602003/\n",+ "Position Statement on How to Manage Patients with Diabetes and COVID-19 https://www.ncbi.nlm.nih.gov/pubmed/33442169/; https://doi.org/10.15605/jafes.035.01.03\n",+ "Successful blood glucose management of a severe COVID-19 patient with diabetes: A case report https://www.ncbi.nlm.nih.gov/pubmed/32590779/; https://doi.org/10.1097/md.0000000000020844\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "vPQv7GJSu9Uq"+ },+ "source": [+ "The example searched for the term `insulin`. The top results mention diabetes and blood glucose which are a closely associated terms for diabetes."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "gzFmQDXfvniJ"+ },+ "source": [+ "# JSON Service Workflow\n",+ "\n",+ "The next example builds a workflow that runs a query against a remote URL, retrieves the results, then transforms and indexes the tabular data. This example gets the top results from the [Hacker News front page](https://news.ycombinator.com/). \n",+ "\n",+ "Below shows how to build the ServiceTask and prints the first JSON result. Details on how to configure the ServiceTask can be found in [txtai's documentation](https://neuml.github.io/txtai/workflows/)."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "bA8SihkeZqbJ",+ "outputId": "353814c6-a1f3-4952-df35-a601e4b12dd7"+ },+ "source": [+ "from txtai.workflow import ServiceTask\n",+ "\n",+ "service = ServiceTask(url=\"https://hn.algolia.com/api/v1/search\", method=\"get\", params={\"tags\": None}, batch=False, extract=\"hits\")\n",+ "workflow = Workflow([service])\n",+ "\n",+ "list(workflow([\"front_page\"]))[:1]"+ ],+ "execution_count": 65,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "[{'_highlightResult': {'author': {'matchLevel': 'none',\n",+ " 'matchedWords': [],\n",+ " 'value': 'withzombies'},\n",+ " 'title': {'matchLevel': 'none',\n",+ " 'matchedWords': [],\n",+ " 'value': 'An opinionated guide on how to reverse engineer software'},\n",+ " 'url': {'matchLevel': 'none',\n",+ " 'matchedWords': [],\n",+ " 'value': 'https://margin.re/media/an-opinionated-guide-on-how-to-reverse-engineer-software-part-1.aspx'}},\n",+ " '_tags': ['story', 'author_withzombies', 'story_29084716', 'front_page'],\n",+ " 'author': 'withzombies',\n",+ " 'comment_text': None,\n",+ " 'created_at': '2021-11-02T17:43:47.000Z',\n",+ " 'created_at_i': 1635875027,\n",+ " 'num_comments': 25,\n",+ " 'objectID': '29084716',\n",+ " 'parent_id': None,\n",+ " 'points': 254,\n",+ " 'story_id': None,\n",+ " 'story_text': None,\n",+ " 'story_title': None,\n",+ " 'story_url': None,\n",+ " 'title': 'An opinionated guide on how to reverse engineer software',\n",+ " 'url': 'https://margin.re/media/an-opinionated-guide-on-how-to-reverse-engineer-software-part-1.aspx'}]"+ ]+ },+ "metadata": {},+ "execution_count": 65+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "Lv_ybw1VwK1N"+ },+ "source": [+ "Next we'll map the JSON data using the tabular pipeline. `url` will be used as the id column and `title` as the text to index."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "YAbwhsaveKo1",+ "outputId": "286b19b4-3008-4a09-df95-87f3c1c9b44e"+ },+ "source": [+ "from txtai.workflow import Task\n",+ "\n",+ "# Recreate service applying the tabular pipeline to each result\n",+ "service = ServiceTask(action=tabular, url=\"https://hn.algolia.com/api/v1/search\", method=\"get\", params={\"tags\": None}, batch=False, extract=\"hits\")\n",+ "workflow = Workflow([service])\n",+ "\n",+ "list(workflow([\"front_page\"]))[:1]"+ ],+ "execution_count": 66,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "[('https://margin.re/media/an-opinionated-guide-on-how-to-reverse-engineer-software-part-1.aspx',\n",+ " 'An opinionated guide on how to reverse engineer software',\n",+ " None)]"+ ]+ },+ "metadata": {},+ "execution_count": 66+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "SbjMuN5lw63c"+ },+ "source": [+ "As we did previously, let's build an Embeddings index and run a search query."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "5lx9pa65e23E",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "036949d0-d2e0-45db-cad0-b5e5605682fd"+ },+ "source": [+ "# Embeddings with sentence-transformers backend\n",+ "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",+ "\n",+ "# Index Hacker News front page\n",+ "data = list(workflow([\"front_page\"]))\n",+ "embeddings.index(data)\n",+ "\n",+ "for uid, _ in embeddings.search(\"cloud\"):\n",+ " title = [text for url, text, _ in data if url == uid][0]\n",+ " print(title, uid)"+ ],+ "execution_count": 67,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "How Temporal Workload Shifting Can Reduce Carbon Emissions in the Cloud https://arxiv.org/abs/2110.13234\n",+ "Hetzner Cloud Goes US (Ashburn/VA) https://twitter.com/Hetzner_Online/status/1455837994259210242\n",+ "Hetzner cloud servers are now available in Ashburn USA https://www.hetzner.com/news/11-21-usa-cloud\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "yq26KqfgxJ6Q"+ },+ "source": [+ "# XML Service workflow\n",+ "\n",+ "txtai's ServiceTask can consume both JSON and XML. This example runs a query against the [arXiv API](https://arxiv.org/), transforms the results and indexes them for search.\n",+ "\n",+ "Below shows how to build the ServiceTask and prints the first XML result."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "K6CbS2QwltGi",+ "outputId": "5734d3a4-83eb-4a69-eb10-d1243809fbdd"+ },+ "source": [+ "service = ServiceTask(url=\"http://export.arxiv.org/api/query\", method=\"get\", params={\"search_query\": None, \"max_results\": 25}, batch=False, extract=[\"feed\", \"entry\"])\n",+ "workflow = Workflow([service])\n",+ "\n",+ "list(workflow([\"all:aliens\"]))[:1]"+ ],+ "execution_count": 68,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "[OrderedDict([('id', 'http://arxiv.org/abs/2102.01522v3'),\n",+ " ('updated', '2021-09-06T14:18:23Z'),\n",+ " ('published', '2021-02-01T18:27:12Z'),\n",+ " ('title',\n",+ " 'If Loud Aliens Explain Human Earliness, Quiet Aliens Are Also Rare'),\n",+ " ('summary',\n",+ " \"If life on Earth had to achieve n 'hard steps' to reach humanity's level,\\nthen the chance of this event rose as time to the n-th power. Integrating this\\nover habitable star formation and planet lifetime distributions predicts >99%\\nof advanced life appears after today, unless n<3 and max planet duration\\n<50Gyr. That is, we seem early. We offer this explanation: a deadline is set by\\n'loud' aliens who are born according to a hard steps power law, expand at a\\ncommon rate, change their volumes' appearances, and prevent advanced life like\\nus from appearing in their volumes. 'Quiet' aliens, in contrast, are much\\nharder to see. We fit this three-parameter model of loud aliens to data: 1)\\nbirth power from the number of hard steps seen in Earth history, 2) birth\\nconstant by assuming a inform distribution over our rank among loud alien birth\\ndates, and 3) expansion speed from our not seeing alien volumes in our sky. We\\nestimate that loud alien civilizations now control 40-50% of universe volume,\\neach will later control ~10^5 - 3x10^7 galaxies, and we could meet them in\\n~200Myr - 2Gyr. If loud aliens arise from quiet ones, a depressingly low\\ntransition chance (~10^-4) is required to expect that even one other quiet\\nalien civilization has ever been active in our galaxy. Which seems bad news for\\nSETI. But perhaps alien volume appearances are subtle, and their expansion\\nspeed lower, in which case we predict many long circular arcs to find in our\\nsky.\"),\n",+ " ('author',\n",+ " [OrderedDict([('name', 'Robin Hanson')]),\n",+ " OrderedDict([('name', 'Daniel Martin')]),\n",+ " OrderedDict([('name', 'Calvin McCarter')]),\n",+ " OrderedDict([('name', 'Jonathan Paulson')])]),\n",+ " ('arxiv:comment',\n",+ " OrderedDict([('@xmlns:arxiv', 'http://arxiv.org/schemas/atom'),\n",+ " ('#text', 'To appear in Astrophysical Journal')])),\n",+ " ('link',\n",+ " [OrderedDict([('@href', 'http://arxiv.org/abs/2102.01522v3'),\n",+ " ('@rel', 'alternate'),\n",+ " ('@type', 'text/html')]),\n",+ " OrderedDict([('@title', 'pdf'),\n",+ " ('@href', 'http://arxiv.org/pdf/2102.01522v3'),\n",+ " ('@rel', 'related'),\n",+ " ('@type', 'application/pdf')])]),\n",+ " ('arxiv:primary_category',\n",+ " OrderedDict([('@xmlns:arxiv', 'http://arxiv.org/schemas/atom'),\n",+ " ('@term', 'q-bio.OT'),\n",+ " ('@scheme', 'http://arxiv.org/schemas/atom')])),\n",+ " ('category',\n",+ " [OrderedDict([('@term', 'q-bio.OT'),\n",+ " ('@scheme', 'http://arxiv.org/schemas/atom')]),\n",+ " OrderedDict([('@term', 'physics.pop-ph'),\n",+ " ('@scheme',\n",+ " 'http://arxiv.org/schemas/atom')])])])]"+ ]+ },+ "metadata": {},+ "execution_count": 68+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "aWFwkxjQyscc"+ },+ "source": [+ "Next we'll map the XML data using the tabular pipeline. `id` will be used as the id column and `title` as the text to index."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "DyIetJ7OmJjP",+ "outputId": "fe98dbed-a7a1-4c36-f1b7-d2f81d632239"+ },+ "source": [+ "from txtai.workflow import Task\n",+ "\n",+ "# Create tablular pipeline with new mapping\n",+ "tabular = Tabular(\"id\", [\"title\"])\n",+ "\n",+ "# Recreate service applying the tabular pipeline to each result\n",+ "service = ServiceTask(action=tabular, url=\"http://export.arxiv.org/api/query\", method=\"get\", params={\"search_query\": None, \"max_results\": 25}, batch=False, extract=[\"feed\", \"entry\"])\n",+ "workflow = Workflow([service])\n",+ "\n",+ "list(workflow([\"all:aliens\"]))[:1]"+ ],+ "execution_count": 69,+ "outputs": [+ {+ "output_type": "execute_result",+ "data": {+ "text/plain": [+ "[('http://arxiv.org/abs/2102.01522v3',\n",+ " 'If Loud Aliens Explain Human Earliness, Quiet Aliens Are Also Rare',\n",+ " None)]"+ ]+ },+ "metadata": {},+ "execution_count": 69+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "7pFnW7mCyycy"+ },+ "source": [+ "As we did previously, let's build an Embeddings index and run a search query."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "NX2oR5dhm_99",+ "outputId": "2763cf1b-0c0f-4d46-9ae4-0646a8b178be"+ },+ "source": [+ "# Embeddings with sentence-transformers backend\n",+ "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",+ "\n",+ "# Index Hacker News front page\n",+ "data = list(workflow([\"all:aliens\"]))\n",+ "embeddings.index(data)\n",+ "\n",+ "for uid, _ in embeddings.search(\"alien radio signals\"):\n",+ " title = [text for url, text, _ in data if url == uid][0]\n",+ " print(title, uid)"+ ],+ "execution_count": 70,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Calculating the probability of detecting radio signals from alien\n",+ " civilizations http://arxiv.org/abs/0707.0011v2\n",+ "Field Trial of Alien Wavelengths on GARR Optical Network http://arxiv.org/abs/1805.04278v1\n",+ "Aliens on Earth. Are reports of close encounters correct? http://arxiv.org/abs/1203.6805v2\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "8xknLo2ey0vZ"+ },+ "source": [+ "# Build a workflow with no code!\n",+ "\n",+ "The next example shows how one of the same workflows above can be constructed via API configuration. This is a no-code way to build a txtai indexing workflow!"+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "1eF5IJlzpNbw",+ "outputId": "1814a2b8-855a-4945-dd3c-ee95a44c79a4"+ },+ "source": [+ "%%writefile workflow.yml\n",+ "# Index settings\n",+ "writable: true\n",+ "embeddings:\n",+ " path: sentence-transformers/nli-mpnet-base-v2\n",+ "\n",+ "# Tabular pipeline\n",+ "tabular:\n",+ " idcolumn: url\n",+ " textcolumns: \n",+ " - title\n",+ "\n",+ "# Workflow definitions\n",+ "workflow:\n",+ " index:\n",+ " tasks:\n",+ " - task: service\n",+ " action: tabular\n",+ " url: https://hn.algolia.com/api/v1/search\n",+ " method: get\n",+ " params:\n",+ " tags: null\n",+ " batch: false\n",+ " extract: hits\n",+ " - action: upsert"+ ],+ "execution_count": 71,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Overwriting workflow.yml\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "dxi5w3IezR7Q"+ },+ "source": [+ "This workflow connects to the Hacker News API, gets the data for the front page and indexes it. The workflow configures the same actions that were configured in Python previously. \n",+ "\n",+ "Let's start an API instance "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "id": "B1DQyB5ErIzr",+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "outputId": "20e62c95-4d85-45b8-e622-98ad200b3cb3"+ },+ "source": [+ "!killall -9 uvicorn\n",+ "!CONFIG=workflow.yml nohup uvicorn \"txtai.api:app\" &> api.log &\n",+ "!sleep 30\n",+ "!cat api.log"+ ],+ "execution_count": 72,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "INFO: Started server process [911]\n",+ "INFO: Waiting for application startup.\n",+ "INFO: Application startup complete.\n",+ "INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "45JaR7Nr0Zmg"+ },+ "source": [+ "Next we'll execute the workflow. txtai has API bindings for [JavaScript](https://github.com/neuml/txtai.js), [Java](https://github.com/neuml/txtai.java), [Rust](https://github.com/neuml/txtai.rs) and [Golang](https://github.com/neuml/txtai.go). But to keep things simple, we'll just run the commands via cURL. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "xt_qL6eA0SrS",+ "outputId": "b7d0c4cd-d612-461a-ddb1-c104882fa9fd"+ },+ "source": [+ "# Execute workflow via API call\n",+ "!curl -X POST \"http://localhost:8000/workflow\" -H \"accept: application/json\" -H \"Content-Type: application/json\" -d \"{\\\"name\\\":\\\"index\\\",\\\"elements\\\":[\\\"front_page\\\"]}\""+ ],+ "execution_count": 73,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[[\"https://margin.re/media/an-opinionated-guide-on-how-to-reverse-engineer-software-part-1.aspx\",\"An opinionated guide on how to reverse engineer software\",null],[\"https://jichu4n.com/posts/how-x-window-managers-work-and-how-to-write-one-part-i/\",\"How X Window Managers Work, and How to Write One (2014)\",null],[\"https://mattferraro.dev/posts/geometric-algebra\",\"What is the inverse of a vector?\",null],[\"https://www.hetzner.com/news/11-21-usa-cloud\",\"Hetzner cloud servers are now available in Ashburn USA\",null],[\"https://zigmonthly.org/letters/2021/october/\",\"Zig monthly, October 2021: Games, gamedev, Elixir, tools and more\",null],[\"https://twitter.com/Hetzner_Online/status/1455837994259210242\",\"Hetzner Cloud Goes US (Ashburn/VA)\",null],[\"https://zig.news/sobeston/using-zig-and-translate-c-to-understand-weird-c-code-4f8\",\"Using Zig's translate-C to understand weird C code\",null],[\"https://real-italian-coffee.herokuapp.com/home\",\"Show HN: A generator of Fake Italian Coffee names\",null],[\"https://www.sciencealert.com/useless-specks-of-dust-turn-out-to-be-ancient-building-blocks-of-all-vertebrate-genomes\",\"'Useless Specks of Dust' Turn Out to Be Building Blocks of All Vertebrate Genome\",null],[\"https://olivierlacan.com/posts/high-fidelity-remote-communication/\",\"High-fidelity remote communication\",null],[\"https://github.com/Qinti/nazca\",\"Nazca – New GUI for the Web\",null],[\"https://susam.in/blog/microcentury.html\",\"Microcentury (2020)\",null],[\"https://addons.mozilla.org/de/firefox/addon/downthemall/\",\"DownThemAll\",null],[\"https://arxiv.org/abs/2110.13234\",\"How Temporal Workload Shifting Can Reduce Carbon Emissions in the Cloud\",null],[\"https://ideas.krishnan.ca/are-daily-standups-hurting-your-team\",\"Are daily standups hurting your team?\",null],[\"https://sethkim.me/l/thesolutionspace/\",\"Automation != Leverage\",null],[\"https://www.listennotes.com/blog/the-boring-technology-behind-a-one-person-23/\",\"The boring technology behind a one-person Internet company\",null],[\"https://www.vox.com/the-goods/22725031/buying-less-supply-chain-holiday-shopping\",\"It’s time for Americans to buy less stuff\",null],[\"https://blog.ilograph.com/posts/beyond-whiteboarding-creating-expert-system-architecture-diagrams/\",\"Beyond Whiteboarding: Creating Expert System Architecture Diagrams\",null],[\"https://www.sciencemuseumgroup.org.uk/blog/covid19-effect-on-the-vaccinated/\",\"Covid-19: How the virus spreads among vaccinated people\",null]]"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "_bwn4KBt1Cos"+ },+ "source": [+ "The data is now indexed. Note that the index configuration has an `upsert` action. Each workflow call will insert new rows or update existing rows. This call could be scheduled with a system cron to execute periodically and build an index of top stories on Hacker News over time. \n",+ "\n",+ "Now that the index is ready, let's run a search."+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "qbteIueJ1Fds",+ "outputId": "c7dcbbc9-a9a9-4640-ea7e-d7dfcbefcc1a"+ },+ "source": [+ "# Run a search\n",+ "!curl -X GET \"http://localhost:8000/search?query=cloud&limit=3\" -H \"accept: application/json\""+ ],+ "execution_count": 74,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{\"id\":\"https://twitter.com/Hetzner_Online/status/1455837994259210242\",\"score\":0.475553035736084},{\"id\":\"https://arxiv.org/abs/2110.13234\",\"score\":0.3434651494026184},{\"id\":\"https://olivierlacan.com/posts/high-fidelity-remote-communication/\",\"score\":0.2550020217895508}]"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "C5_Tt6EA3Cxb"+ },+ "source": [+ "# Add a translation step to workflow\n",+ "\n",+ "Next we'll recreate the workflow, adding one additional step, translating the text into French before indexing. This workflow gets the top results from Hacker News, translates the results and builds an semantic index of titles in French. "+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "j8rBVl17293q",+ "outputId": "20ce444a-eb9c-4ac3-8edf-1d14c4b7b528"+ },+ "source": [+ "%%writefile workflow.yml\n",+ "# Index settings\n",+ "writable: true\n",+ "embeddings:\n",+ " path: sentence-transformers/nli-mpnet-base-v2\n",+ "\n",+ "# Tabular pipeline\n",+ "tabular:\n",+ " idcolumn: url\n",+ " textcolumns: \n",+ " - title\n",+ "\n",+ "# Translation pipeline\n",+ "translation:\n",+ "\n",+ "# Workflow definitions\n",+ "workflow:\n",+ " index:\n",+ " tasks:\n",+ " - task: service\n",+ " action: tabular\n",+ " url: https://hn.algolia.com/api/v1/search\n",+ " method: get\n",+ " params:\n",+ " tags: null\n",+ " batch: false\n",+ " extract: hits\n",+ " - action: translation\n",+ " args: [fr]\n",+ " - action: upsert"+ ],+ "execution_count": 75,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "Overwriting workflow.yml\n"+ ]+ }+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "UQWvvgb2CwgG",+ "outputId": "52a051a8-b3ae-4d59-8e37-034cc62b0c09"+ },+ "source": [+ "!killall -9 uvicorn\n",+ "!CONFIG=workflow.yml nohup uvicorn \"txtai.api:app\" &> api.log &\n",+ "!sleep 30\n",+ "!cat api.log"+ ],+ "execution_count": 76,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "INFO: Started server process [935]\n",+ "INFO: Waiting for application startup.\n",+ "INFO: Application startup complete.\n",+ "INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "v1y4heYx679i"+ },+ "source": [+ "Same as before, we'll run the index workflow and a search"+ ]+ },+ {+ "cell_type": "code",+ "metadata": {+ "colab": {+ "base_uri": "https://localhost:8080/"+ },+ "id": "npW3rjCw6_nx",+ "outputId": "b73ec9db-b42c-40fa-c5ec-84d2a1bcb674"+ },+ "source": [+ "# Execute workflow via API call\n",+ "!curl -s -X POST \"http://localhost:8000/workflow\" -H \"accept: application/json\" -H \"Content-Type: application/json\" -d \"{\\\"name\\\":\\\"index\\\",\\\"elements\\\":[\\\"front_page\\\"]}\" > /dev/null\n",+ "\n",+ "# Run a search\n",+ "!curl -X GET \"http://localhost:8000/search?query=nuage&limit=3\" -H \"accept: application/json\""+ ],+ "execution_count": 77,+ "outputs": [+ {+ "output_type": "stream",+ "name": "stdout",+ "text": [+ "[{\"id\":\"https://arxiv.org/abs/2110.13234\",\"score\":0.46083423495292664},{\"id\":\"https://twitter.com/Hetzner_Online/status/1455837994259210242\",\"score\":0.37807518243789673},{\"id\":\"https://jichu4n.com/posts/how-x-window-managers-work-and-how-to-write-one-part-i/\",\"score\":0.36641401052474976}]"+ ]+ }+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {+ "id": "EoQFEi_61P9O"+ },+ "source": [+ "# Wrapping up\n",+ "\n",+ "This notework demonstrated how to transform, index and search tabular data from a variety of sources. txtai offers maximum flexibility in building composable workflows to maximize the number of ways data can be indexed for semantic search. "+ ]+ }+ ]+}\ No newline at end of filediff --git a/test/python/testapi/testworkflow.py b/test/python/testapi/testworkflow.pyindex e10de19f..23bf066c 100644--- a/test/python/testapi/testworkflow.py+++ b/test/python/testapi/testworkflow.py@@ -166,7 +166,7 @@ class TestWorkflow(unittest.TestCase):self.assertEqual(len(results), 2)- def testServiceXML(self):+ def testServiceXml(self):"""Test workflow with ServiceTask GET via API and XML response."""