diff --git "a/LLM_v2_module_5_large_embedding.ipynb" "b/LLM_v2_module_5_large_embedding.ipynb"
deleted file mode 100644--- "a/LLM_v2_module_5_large_embedding.ipynb"
+++ /dev/null
@@ -1,1969 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "f7gr5j8iDEva"
- },
- "outputs": [],
- "source": [
- "!pip install sentence_transformers openai unstructured\n",
- "!pip install plotly\n",
- "!pip install langchain\n",
- "!pip install tiktoken\n",
- "!pip install matplotlib\n",
- "%pip install -Uqqq rich openai tiktoken wandb langchain unstructured tabulate pdf2image chromadb gradio faiss-gpu\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "eCDxucPBGp5g",
- "outputId": "b7c353ee-c376-4fb7-f700-961e3dd56781"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "Requirement already satisfied: linkify-it-py in /usr/local/lib/python3.10/dist-packages (2.0.2)\n",
- "Requirement already satisfied: uc-micro-py in /usr/local/lib/python3.10/dist-packages (from linkify-it-py) (1.0.2)\n"
- ]
- }
- ],
- "source": [
- "!pip install linkify-it-py"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "u4zmuvSp7WVI"
- },
- "outputs": [],
- "source": [
- "import numpy as np\n",
- "import os, random\n",
- "from pathlib import Path\n",
- "import tiktoken\n",
- "from getpass import getpass\n",
- "from rich.markdown import Markdown\n",
- "from langchain.chains.qa_with_sources import load_qa_with_sources_chain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "EVxVIwh87WVJ",
- "outputId": "51abb5db-4535-4362-c94e-ef93e9c1485a"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "131072"
- ]
- },
- "metadata": {},
- "execution_count": 4
- }
- ],
- "source": [
- "import torch\n",
- "import sys\n",
- "import csv\n",
- "\n",
- "csv.field_size_limit(sys.maxsize)\n",
- "\n",
- "# torch.has_mps"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "_1AdkW1kFB20"
- },
- "outputs": [],
- "source": [
- "# os.environ[\"OPENAI_API_KEY\"] = getpass(\"\")\n",
- "#os.environ[\"OPENAI_API_KEY\"] = “API KEY”"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "5SuSwwcx7WVK",
- "outputId": "7a126930-89db-4f6e-ee91-7f7300e79457"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "··········\n",
- "OpenAI API key configured\n"
- ]
- }
- ],
- "source": [
- "\n",
- "if os.getenv(\"OPENAI_API_KEY\") is None:\n",
- " if any(['VSCODE' in x for x in os.environ.keys()]):\n",
- " print('Please enter password in the VS Code prompt at the top of your VS Code window!')\n",
- " os.environ[\"OPENAI_API_KEY\"] = getpass(\"\")\n",
- "\n",
- "assert os.getenv(\"OPENAI_API_KEY\", \"\").startswith(\"sk-\"), \"This doesn't look like a valid OpenAI API key\"\n",
- "print(\"OpenAI API key configured\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "6fLvsQcLEW0K"
- },
- "source": [
- "#Chunking and RAG"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "Qgn9BzjX7WVK",
- "outputId": "3d37d4b9-846f-4539-b46e-56837544dd7d"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stderr",
- "text": [
- "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
- "[nltk_data] Unzipping tokenizers/punkt.zip.\n"
- ]
- }
- ],
- "source": [
- "from langchain.embeddings.openai import OpenAIEmbeddings\n",
- "import nltk\n",
- "nltk.download('punkt')\n",
- "from langchain.text_splitter import CharacterTextSplitter\n",
- "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
- "from langchain.vectorstores import Chroma\n",
- "from langchain.document_loaders import TextLoader\n",
- "from langchain.chat_models import ChatOpenAI\n",
- "from langchain import PromptTemplate\n",
- "from langchain.chains import LLMChain\n",
- "from langchain.chains.qa_with_sources import load_qa_with_sources_chain\n",
- "from langchain.llms import OpenAI\n",
- "from langchain.vectorstores import FAISS"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "cgh0f__69Qse"
- },
- "outputs": [],
- "source": [
- "MODEL_NAME = \"text-embedding-3-small\"\n",
- "# MODEL_NAME = \"gpt-4\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "28-76KUp9TdA"
- },
- "outputs": [],
- "source": [
- "# from langchain.document_loaders import DirectoryLoader\n",
- "\n",
- "# def find_md_files(directory):\n",
- "# \"Find all markdown files in a directory and return a LangChain Document\"\n",
- "# dl = DirectoryLoader(directory, \"**/*.txt\")\n",
- "# return dl.load()\n",
- "\n",
- "# documents = find_md_files('data')\n",
- "# len(documents)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "MLiFbXx1-hAv"
- },
- "outputs": [],
- "source": [
- "# documents"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "FznW3HMpD4f_"
- },
- "source": [
- "#upload files"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "wtENHSIWEf9K"
- },
- "outputs": [],
- "source": [
- "import pandas as pd"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "c3Edx6229xs3"
- },
- "outputs": [],
- "source": [
- "from langchain.document_loaders.csv_loader import CSVLoader\n",
- "# from langchain.docstore.document import Document\n",
- "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
- "from langchain.document_loaders import DirectoryLoader"
- ]
- },
- {
- "cell_type": "code",
- "source": [
- "url='https://drive.google.com/file/d/1gl7WAkJr6Nyke7YckzXxdL-iM4UjhLGX/view?usp=sharing'\n",
- "url='https://drive.google.com/uc?id=' + url.split('/')[-2]\n",
- "df = pd.read_csv(url)"
- ],
- "metadata": {
- "id": "logMHfgiSen2"
- },
- "execution_count": null,
- "outputs": []
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 556
- },
- "id": "1jr0ZaWqvSPQ",
- "outputId": "b9c06fdc-5d0b-44ce-f1c0-3a8bee0028f2"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- " _id \\\n",
- "0 63927168098523fa9d5ef047 \n",
- "1 652b21ec754471a9795c291a \n",
- "2 6529cfaff59ed61396db838c \n",
- "3 6529d030f59ed61396db8398 \n",
- "4 6529d072f59ed61396db839e \n",
- "\n",
- " title author \\\n",
- "0 Are The Democrats Screwed In The Senate After ... Nate Silver \n",
- "1 Beyond the Narrative Sam Freedman \n",
- "2 Ballot Measures: A Preview Walter Olson \n",
- "3 Trump’s Only Real Worldview Is Pettiness David A. Graham \n",
- "4 The COVID Bailout of State and Local Governmen... Eric Boehm \n",
- "\n",
- " description publish_date \\\n",
- "0 \\nAre The Democrats Screwed In The Senate Afte... 1.670516e+12 \n",
- "1 NaN 1.697272e+12 \n",
- "2 NaN 1.697227e+12 \n",
- "3 NaN 1.697214e+12 \n",
- "4 NaN 1.697212e+12 \n",
- "\n",
- " full_text \\\n",
- "0 \\n\\n\\n\\n2028 Election\\nAre The Democrats Screw... \n",
- "1 We are told before every party conference that... \n",
- "2 Walter Olson Voters will go to the polls soon... \n",
- "3 Let no one say that Donald Trump has lost his ... \n",
- "4 Two years after Congress authorized a h... \n",
- "\n",
- " url categories \n",
- "0 https://fivethirtyeight.com/features/democrats... ['news'] \n",
- "1 https://samf.substack.com/p/beyond-the-narrative ['news'] \n",
- "2 https://www.cato.org/blog/ballot-measures-preview ['news'] \n",
- "3 tag:theatlantic.com,2023:50-675637 ['news'] \n",
- "4 https://reason.com/2023/10/13/the-covid-bailou... ['news'] "
- ],
- "text/html": [
- "\n",
- "
\n",
- "
\n",
- "\n",
- "
\n",
- " \n",
- " \n",
- " | \n",
- " _id | \n",
- " title | \n",
- " author | \n",
- " description | \n",
- " publish_date | \n",
- " full_text | \n",
- " url | \n",
- " categories | \n",
- "
\n",
- " \n",
- " \n",
- " \n",
- " 0 | \n",
- " 63927168098523fa9d5ef047 | \n",
- " Are The Democrats Screwed In The Senate After ... | \n",
- " Nate Silver | \n",
- " \\nAre The Democrats Screwed In The Senate Afte... | \n",
- " 1.670516e+12 | \n",
- " \\n\\n\\n\\n2028 Election\\nAre The Democrats Screw... | \n",
- " https://fivethirtyeight.com/features/democrats... | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 1 | \n",
- " 652b21ec754471a9795c291a | \n",
- " Beyond the Narrative | \n",
- " Sam Freedman | \n",
- " NaN | \n",
- " 1.697272e+12 | \n",
- " We are told before every party conference that... | \n",
- " https://samf.substack.com/p/beyond-the-narrative | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 2 | \n",
- " 6529cfaff59ed61396db838c | \n",
- " Ballot Measures: A Preview | \n",
- " Walter Olson | \n",
- " NaN | \n",
- " 1.697227e+12 | \n",
- " Walter Olson Voters will go to the polls soon... | \n",
- " https://www.cato.org/blog/ballot-measures-preview | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 3 | \n",
- " 6529d030f59ed61396db8398 | \n",
- " Trump’s Only Real Worldview Is Pettiness | \n",
- " David A. Graham | \n",
- " NaN | \n",
- " 1.697214e+12 | \n",
- " Let no one say that Donald Trump has lost his ... | \n",
- " tag:theatlantic.com,2023:50-675637 | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 4 | \n",
- " 6529d072f59ed61396db839e | \n",
- " The COVID Bailout of State and Local Governmen... | \n",
- " Eric Boehm | \n",
- " NaN | \n",
- " 1.697212e+12 | \n",
- " Two years after Congress authorized a h... | \n",
- " https://reason.com/2023/10/13/the-covid-bailou... | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- "
\n",
- "
\n",
- "
\n",
- "
\n"
- ]
- },
- "metadata": {},
- "execution_count": 11
- }
- ],
- "source": [
- "df.head()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "l-Rjki2Yvq01",
- "outputId": "68972d9a-1c04-483c-93d1-ac65e3d065ec"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "(3327, 8)"
- ]
- },
- "metadata": {},
- "execution_count": 12
- }
- ],
- "source": [
- "df.shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "lA4AoU3f4dJH"
- },
- "outputs": [],
- "source": [
- "!mkdir data"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "nsvUBcPJCV_m"
- },
- "outputs": [],
- "source": [
- "df[:100].to_csv('data/df_embed.csv',index=False)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "Kwy9kXLzYEu7"
- },
- "outputs": [],
- "source": []
- },
- {
- "cell_type": "markdown",
- "source": [
- "1. Step 1: Read the data"
- ],
- "metadata": {
- "id": "5WYH_AC18qes"
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 157
- },
- "id": "T6LiGVc4LREH",
- "outputId": "819bda32-1735-4f6b-9ab5-d6696d641082"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "'We are told before every party conference that the leader will be making perhaps their “most important speech yet”. In reality, unless they are going into the conference with the word “beleaguered” regularly appearing in front of their name, they’ll almost certainly be fine. For struggling leaders a bad speech might sink them, but if they are 20 points ahead in the polls, and coming off a huge by-election win, then they are unlikely to be derailed.It’s even less likely to be a problem if your opponents are noisily falling apart. I wasn’t at the Tory conference but all of the several dozen journalists, politicians and business people I spoke to who had, were unanimous that it was even more shambolic than it appeared on TV. Even hacks from right-wing papers were shaking their heads at the sheer incoherence of it all. It’s hard to be a client journalist when your political masters can’t figure out what they want you to say.You can see how the Tories got into such a mess. There is no record to run on and Sunak doesn’t want to take the blame for the failures of his predecessors. It is, though, always going to be extremely hard to run a “change” message as the governing party. Boris Johnson managed it in 2019 by promising to spend a lot of money and attaching his personal brand to Brexit. But Sunak doesn’t want to spend money and any hope associated with leaving the EU has faded. He has nothing else. A rag-bag of random policy announcements about A-levels and smoking certainly won’t cut it.Even worse than the confusion of the official platform was the circus around it. There was a general consensus, amongst attendees, that it felt more like the conference a party has after it’s lost an election rather than the one before, with all the focus on leadership jockeying and indulging in ideological fantasies.So the lobby arrived at the Labour conference – which I did go to – primed to write positively about the contrast. As long as Starmer and team could look vaguely professional and serious, then they were going to get good coverage. The narrative is in their favour and that makes politics a lot easier. Announcements that would get ripped to pieces if the lobby were moving in for a kill get left unscrutinised. Dull speeches are lauded as triumphs. You’ve got to enjoy it while it lasts. \\xa0\\xa0I don’t want to be churlish about this. Seeming professional and serious might not seem like a high bar but it’s one plenty of Labour conferences have failed to meet in the past. We shouldn’t begrudge weary Labour folk their raptures at a leadership that can tie their own shoelaces. Starmer’s team are competent, well organised, extremely thorough in their voter research and message design, and ruthless when it comes to keeping the hard left out. As a Jew I was highly conscious of how different the conference would have felt last week with the old guard in charge, and don’t underestimate what it took to achieve that transformation.But Labour still haven’t begun to resolve, or even acknowledge, the fundamental contradiction in their current position.Let’s be clear as to what the problem is. It’s not that Starmer “doesn’t have a vision” or “doesn’t stand for anything”. Labour’s “missions” might be a poor campaigning tool (as predicted) but if you bother to read them they’re entirely clear about the country they want to build. And that country is Denmark. Literally in the case of the “opportunity mission” which cites Danish social mobility as the (implausible) goal. Starmer and his team are soft left Labour and want a high-growth, social democratic country with better worker rights, more state direction, and less inequality. They want us to be Scandinavian. Which as visions go seems reasonable enough.Nor is the problem that “they don’t have any policies”. They have far too many fiddly policies. No one who doesn’t spend their time reading policy documents and going to conferences will have heard of them. Did you know Labour is planning a £2.4k retention bonus for teachers completing the early years framework? I doubt it. Their bigger pledges on housebuilding, planning, and electricity infrastructure are substantive and important, albeit lacking in detail. But that will always be true of opposition parties, who have limited resources. The civil service is much maligned but you do need them to do the work on these complex policies.No, the problem is very specific. They have no substantive policies that would involve having to spend any taxpayer money. Starmer’s holding position that he wishes to run “a reforming state, not a cheque-book state” is transparent nonsense, an example of what Duncan Robinson at the Economist calls “Reform Fairy” thinking:“Both main parties agree that although the British state requires a total overhaul, it does not need much more cash. In its bid to move away from the Magic Money Tree, British politics has fallen under the spell of another mythical being: the Reform Fairy. The Magic Money Tree could generate cash at will; the Reform Fairy can apparently improve public services without spending political or financial capital.”I am always surprised at politicians’ capacity to believe things that happen to be convenient for them at any given time, but I just don’t buy they really believe in the Reform Fairy. For a start when it comes to health, welfare and education – the three departments that account for 60% of all spending – they have no proposals for significant reform. I watched a succession of junior shadow ministers struggle through fringe events on each of these issues, acknowledging the terrible state of things right now, promising a decade of transformation, but unable to fill in any of the steps that might get us there. \\xa0 \\xa0The reasons for this are obvious. They are absolutely determined to stop the Tories running a “same old Labour” campaign, or at least not one that seems credible. From an electoral point of view it will work because neither the Tories nor the right-wing press are going to attack them for not pledging to spend enough money. Plus the power of the narrative will protect them from scrutiny. On top of that, it’s now so clear they’re going to win that every media outlet, business, trade union and sector lobbying group wants to be on good terms.It is, though, going to make those first few years in government much harder because they can’t do any serious thinking about reform that goes beyond the very conceptual stage, without getting into costings.That doesn’t mean I left the conference without hope. The first big positive was that Rachel Reeves’ team are doing an extremely canny job at shouting loudly about fiscal discipline while ensuring they keep their room for manoeuvre open post-election. There were hints that investment spending could be excluded from Labour’s headline rule on debt reduction (as it was in Boris Johnson’s first two years as Prime Minister). Reeves may have an “iron-clad commitment” to sticking to fiscal rules but there is still definitional space about what exactly they would be. She also managed to get through conference without ruling out any other tax cuts. My biggest worry for Labour is that at some point over the next year their poll lead dips, the narrative shifts a bit (as journalists get bored) and they get panicked into reducing their fiscal space to zero.My second positive is that Labour adjacent wonks, who have plausible deniability, are starting to think through some ways through these problems. The centre-left think-tank IPPR published a report that was subtitled, in a direct response to Duncan Robinson’s challenge, “Between the Reform Fairy and the Magic Money Tree”. It acknowledges that spending will be needed, and the short-termist scorecard approach taken by the Treasury is a major impediment to a well-functioning state. Also that the standard “new public management” model of public service reform – with its focus entirely on targets and extrinsic incentives – has run out of road with no obvious alternative offering itself.I don’t agree with all their solutions. For instance, they propose creating a new category of “prevention investment expenditure” to ensure money designed for long-term preventative interventions on, say public health or reducing reoffending,\\xa0is better protected. I get the objective but the fuzziness of the line over what counts as prevention worries me. I do, though, like their idea of treating priority social policy objectives in the same way as fiscal ones, with independent measurement as to whether, for example, the government is reducing waiting lists or building more houses. Tying the Treasury into those metrics could help balance the obsession with the spending scorecard. It is also good to see Labour engaging with these ideas. So there are positive signs, but not yet quite the sense of urgency I’d like to see. While, of course, Labour are aware the country is in a bad way, I’m not sure they yet appreciate quite how much of a challenge it’s going to be. Just in the last few weeks we’ve heard that dozens of councils are approaching bankruptcy; that prisons are now full with those convicted of serious crimes unable to be incarcerated; and that hospitals are already declaring critical incidents before we get to winter. There is still a sense they are over-estimating how far being nicer and more competent that Tory ministers will get them. Its good to know, for instance, \\xa0that they won’t go ahead with the Rwanda deportations, as this will save time and money. But it’s not going to be nearly enough.The biggest panel event I spoke at was an online one organised by Citizens’ Advice on the cost of living crisis. Their stats, on foodbank use, homelessness and so on, are all dire. I was most struck, though, by the story of Sanna. A young woman living in a council flat who was already behind on her bills and then lost just under a third of her Universal Credit for a month, because she missed a job centre appointment and was sanctioned. This will push her further into debt. She is already struggling with anxiety and depression, which will now be exacerbated, making it harder to find work. I wouldn’t be surprised if she ended up joining the ballooning list of people classified as unable to work due to mental health problems. It was such a clear example of how our current approach to our biggest spending policy area is utterly broken – ruining lives and costing taxpayer money – with no party close to offering a solution.\\xa0We need that sense of urgency for Sanna’s sake.Comment is Freed is a reader supported publication. A monthly subscription is £3.50 and an annual one £35. It includes at least four subscriber only posts a month.This post is public so please share if you found it helpful.Share'"
- ],
- "application/vnd.google.colaboratory.intrinsic+json": {
- "type": "string"
- }
- },
- "metadata": {},
- "execution_count": 18
- }
- ],
- "source": [
- "df.full_text\t[1]"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 556
- },
- "id": "QV58YlrRYKIS",
- "outputId": "8dcd3fa1-420b-415e-ae7a-94714771cf72"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- " _id \\\n",
- "0 63927168098523fa9d5ef047 \n",
- "1 652b21ec754471a9795c291a \n",
- "2 6529cfaff59ed61396db838c \n",
- "3 6529d030f59ed61396db8398 \n",
- "4 6529d072f59ed61396db839e \n",
- "\n",
- " title author \\\n",
- "0 Are The Democrats Screwed In The Senate After ... Nate Silver \n",
- "1 Beyond the Narrative Sam Freedman \n",
- "2 Ballot Measures: A Preview Walter Olson \n",
- "3 Trump’s Only Real Worldview Is Pettiness David A. Graham \n",
- "4 The COVID Bailout of State and Local Governmen... Eric Boehm \n",
- "\n",
- " description publish_date \\\n",
- "0 \\nAre The Democrats Screwed In The Senate Afte... 1.670516e+12 \n",
- "1 NaN 1.697272e+12 \n",
- "2 NaN 1.697227e+12 \n",
- "3 NaN 1.697214e+12 \n",
- "4 NaN 1.697212e+12 \n",
- "\n",
- " full_text \\\n",
- "0 \\n\\n\\n\\n2028 Election\\nAre The Democrats Screw... \n",
- "1 We are told before every party conference that... \n",
- "2 Walter Olson Voters will go to the polls soon... \n",
- "3 Let no one say that Donald Trump has lost his ... \n",
- "4 Two years after Congress authorized a h... \n",
- "\n",
- " url categories \n",
- "0 https://fivethirtyeight.com/features/democrats... ['news'] \n",
- "1 https://samf.substack.com/p/beyond-the-narrative ['news'] \n",
- "2 https://www.cato.org/blog/ballot-measures-preview ['news'] \n",
- "3 tag:theatlantic.com,2023:50-675637 ['news'] \n",
- "4 https://reason.com/2023/10/13/the-covid-bailou... ['news'] "
- ],
- "text/html": [
- "\n",
- " \n",
- "
\n",
- "\n",
- "
\n",
- " \n",
- " \n",
- " | \n",
- " _id | \n",
- " title | \n",
- " author | \n",
- " description | \n",
- " publish_date | \n",
- " full_text | \n",
- " url | \n",
- " categories | \n",
- "
\n",
- " \n",
- " \n",
- " \n",
- " 0 | \n",
- " 63927168098523fa9d5ef047 | \n",
- " Are The Democrats Screwed In The Senate After ... | \n",
- " Nate Silver | \n",
- " \\nAre The Democrats Screwed In The Senate Afte... | \n",
- " 1.670516e+12 | \n",
- " \\n\\n\\n\\n2028 Election\\nAre The Democrats Screw... | \n",
- " https://fivethirtyeight.com/features/democrats... | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 1 | \n",
- " 652b21ec754471a9795c291a | \n",
- " Beyond the Narrative | \n",
- " Sam Freedman | \n",
- " NaN | \n",
- " 1.697272e+12 | \n",
- " We are told before every party conference that... | \n",
- " https://samf.substack.com/p/beyond-the-narrative | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 2 | \n",
- " 6529cfaff59ed61396db838c | \n",
- " Ballot Measures: A Preview | \n",
- " Walter Olson | \n",
- " NaN | \n",
- " 1.697227e+12 | \n",
- " Walter Olson Voters will go to the polls soon... | \n",
- " https://www.cato.org/blog/ballot-measures-preview | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 3 | \n",
- " 6529d030f59ed61396db8398 | \n",
- " Trump’s Only Real Worldview Is Pettiness | \n",
- " David A. Graham | \n",
- " NaN | \n",
- " 1.697214e+12 | \n",
- " Let no one say that Donald Trump has lost his ... | \n",
- " tag:theatlantic.com,2023:50-675637 | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- " 4 | \n",
- " 6529d072f59ed61396db839e | \n",
- " The COVID Bailout of State and Local Governmen... | \n",
- " Eric Boehm | \n",
- " NaN | \n",
- " 1.697212e+12 | \n",
- " Two years after Congress authorized a h... | \n",
- " https://reason.com/2023/10/13/the-covid-bailou... | \n",
- " ['news'] | \n",
- "
\n",
- " \n",
- "
\n",
- "
\n",
- "
\n",
- "
\n"
- ]
- },
- "metadata": {},
- "execution_count": 15
- }
- ],
- "source": [
- "df.head()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "QSOiVXVxekH_"
- },
- "outputs": [],
- "source": [
- "path= 'data/df_embed.csv'\n",
- "loader = CSVLoader(file_path=path,source_column=\"title\")\n",
- "\n",
- "data = loader.load()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "Q2dWBLgyEy_n",
- "outputId": "3c5b0017-13ac-4420-b787-89971f592925"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "page_content=\"_id: 63927168098523fa9d5ef047\\ntitle: Are The Democrats Screwed In The Senate After 2024?\\nauthor: Nate Silver\\ndescription: Are The Democrats Screwed In The Senate After 2024?\\nNo, but the party faces an uphill battlee\\n\\n\\nI’m not that impressed by long-term projections of Democratic doom in the Senate. Mostly that’s because I’m not that impressed by long-term political projections in general. Political coalitions change; not many people would have had it on their bingo card that Democrats would obtain a Senate majority in 2020 by winning two runoffs in Georgia, and then would actually expand on that majority in 2022 following another runoff in Georgia despite their party controlling the White House.\\nWith that said, while I don’t think we can say very much about what politics will look like 10 or 20 years from now, a medium-term look-ahead is possible. Do Democrats have a reasonable hope of regaining a trifecta — control of the House, Senate and presidency — at any point in the near future (2024, 2026 or 2028)? And how long will they hold onto control of the Senate and the presidency, allowing them to appoint Supreme Court justices without Republican help?\\nMy colleague Geoffrey Skelley already took an initial look at the 2024 Senate map, which is bad for Democrats, but I wanted to dig slightly deeper and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the Senate, because that’s the weakest link in Democrats’ effort to win back the trifecta. Despite some disadvantages in the Electoral College, Democrats obviously have no trouble winning the presidency. And they nearly held onto the House this year despite losing the popular vote for the House. The current House map doesn’t have much — if any — of a Republican skew, and Democrats should be able to win back the House if the national political environment is reasonably good for them.\\nSo let’s look at the 2024, 2026 and 2028 Senate maps (yes, 2028 features the same map as the midterm we just finished; I just can’t let go, I guess). We’ll classify races into bronze, silver, gold and platinum “tiers” in terms of how feasible they are as pickup opportunities. I’m deliberately using this goofy metallurgical theme as opposed to the categories FiveThirtyEight typically uses (e.g., “toss-up,” “lean Republican”) so you’ll recognize these as being back-of-the-envelope suppositions rather than any sort of official race ratings. \\nIn general, these ratings lean heavily on looking at how close a race was the last time it was contested, with some subjective adjustments for candidate quality. I’m also considering how the electoral environment has shifted within the state — Florida has gotten redder since Rick Scott was elected in 2018, for instance — although it is definitely not always safe to assume a state will continue trending in the same direction.\\n2024\\nRepublican pickup opportunities\\nPlatinum tier: West Virginia (Manchin), Montana (Tester), Ohio (Brown), \\nGold tier: Arizona (Sinema), Nevada (Rosen)\\nSilver tier: Wisconsin (Baldwin), Michigan (Stabenow), Pennsylvania (Casey)\\nBronze tier: New Jersey (Menendez), Virginia (Kaine)\\nAs Geoffrey noted, the platinum-tier states listed here are the Democrats’ main problem. They have three senators up for reelection in states that Donald Trump carried by 8 (Ohio), 16 (Montana) and 39 (West Virginia!) percentage points in 2020. Each of those Democratic senators won reelection in 2018, of course, but that was a strong Democratic year, and there’s been further movement of white voters without college degrees — a key part of the electorate in these states — toward Republicans since then.\\xa0\\nI don’t want to focus too much on any one individual race, but it’s probably safe to assume that Joe Manchin has the toughest reelection campaign of all. Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats also run the risk of retirements here; neither Manchin nor Jon Tester has officially yet announced they will seek reelection.\\nBeyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is likely to face a serious primary challenge. Democrats keep winning close races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and will likely be fine in the event of a decent-to-good Democratic year, but if 2024 turns into a good Republican year, they could be in trouble.\\nDemocratic pickup opportunities\\nPlatinum tier: None\\nGold tier: None\\nSilver tier: Texas (Cruz), Florida (Scott)\\nBronze tier: None\\nConversely, it’s very slim pickings for Democrats. On paper, you’d think that Texas might be close — Ted Cruz won by less than 3 percentage points there in 2018 and Texas is more competitive than it once was — but the erosion of the Democratic vote in South Texas has prevented Texas from turning truly purple. And although Scott won by only 0.12 percentage points in 2018, Republicans did so well in Florida in 2020 and 2022 that I was tempted to demote his race all the way to the bronze tier. Plus, there’s a good chance that the GOP’s 2024 nominee will be either Florida Gov. Ron DeSantis or Florida resident Donald Trump, which could help drive Republican turnout.\\nBeyond that, any other races look like an extreme stretch for Democrats. Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type environment, but that’s less likely in a presidential year and Hawley’s approval rating isn’t that bad. Put him in the “honorable mention” tier, I guess.\\nGiven all this, I’d imagine the modal outcome from 2024 is something like Republicans picking up about three Senate seats. There’s uncertainty around that; it’s surely within the realm of possibility that Democrats hold the Senate, but it’s also possible that Republicans could wind up with 54 or 55 seats. And of course, all of these races are correlated. If the GOP is doing well enough to win the presidency in 2024, they should have no trouble also winning the Senate.9\\n2026\\nRepublican pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Georgia (Ossoff), Michigan (Peters)\\nSilver tier: New Hampshire (Shaheen)\\nBronze tier: Minnesota (Smith), Virginia (Warner)\\nThe 2026 map is more balanced. Democrats undoubtedly feel pretty good about how they’ve performed in Georgia and Michigan in the past two cycles, but Jon Ossoff and Gary Peters won by extremely narrow margins in 2020 and it would be a mistake to assume they’re safe. It’s not a particularly deep set of pickup opportunities for Republicans, though if Democrats retain the presidency in 2024, you’d expect Republicans to have good midterms in 2026, and New Hampshire and perhaps even Minnesota and Virginia could potentially be in play.\\xa0\\nDemocratic pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Maine (Collins), North Carolina (Tillis)\\nSilver tier: Alaska (Sullivan)\\nBronze tier: Texas (Cornyn), Iowa (Ernst)\\nMeanwhile, Democrats will try again in the two states that were most disappointing to them in 2020: Maine and North Carolina. Given all the focus on Georgia, I wonder if North Carolina hasn’t become underrated as a place where Democrats could gain ground in the future; the states are fairly similar demographically and it wouldn’t take that much of a shift for Democrats to go from narrowly losing races in North Carolina to narrowly winning them. Susan Collins will be 74 years old in 2026, meanwhile, an age at which there’s typically some chance of retirement.\\nDemocrats also have a below-the-radar pickup opportunity in Alaska, where Mary Peltola was elected to a full term in the U.S. House10 last month by a 10-point margin after ranked-choice votes were tabulated. GOP incumbent Dan Sullivan has a mediocre approval rating and a Peltola-Sullivan race would potentially be competitive.\\nSuppose, though, that Democrats win the presidency but lose the Senate in 2024. It’s really not as crazy as it sounds. If every state votes identically to how it did in the 2020 presidential election — and every Senate race follows the presidential vote — then Democrats would come out of 2024 with the presidency but only 48 Senate seats after losing West Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from the GOP in the 2026 midterm while controlling the presidency? Unlikely — but then again, Democrats gaining Senate seats this year seemed unlikely and they did it.\\n2028\\nRepublican pickup opportunities\\nPlatinum tier: None\\nGold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), Georgia (Warnock) \\nSilver tier: New Hampshire (Hassan)\\nBronze tier: Oregon (Wyden)\\nAll right, now we’re literally coming full circle to consider the races that were just contested in last month’s midterm. So we’ll keep it pretty brief. Yes, Democrats have to feel pretty good about their wins in Nevada, Pennsylvania, Arizona and Georgia — especially given that the overall political environment wasn’t that great for Democrats this year. But they were narrow wins, and (with the possible exception of Nevada) they came against a mediocre set of GOP opponents. Maybe some of these races are toward the silver end of the gold tier, but more likely than not they’ll be competitive again.\\nAnd since we’re projecting a full six years out, I’m going to be a little bit more creative about considering long-shot opportunities in the bronze tier. Although the Senate races in Washington and Colorado received attention this year (Republicans spent a lot of money on both, only to lose by double digits), they wound up coming just as close in Oregon with a QAnon candidate as part of a comparatively strong year for the GOP in the Beaver State. Could a more mainstream GOP nominee have made it a race? Oregon is quite white, it has fewer people with college degrees than the “Portlandia” stereotype might make you assume, and Democratic incumbent Ron Wyden will be 79 years old in 2028 …\\nDemocratic pickup opportunities\\nPlatinum tier: None\\nGold tier: Wisconsin (Johnson), North Carolina (Budd)\\nSilver tier: Vance (Ohio)\\nBronze tier: Alaska (Murkowski), Florida (Rubio), Utah (Lee), Iowa (Grassley)\\nAgain, we’re mostly just rehashing this year’s map. Ron Johnson, who originally hadn’t planned on running in 2020, is another retirement threat in 2026 — and he barely won reelection anyway. In Ohio, Sherrod Brown could seek to return to the Senate if he loses in 2024 by challenging J.D. Vance. And 2028 is far enough from now that I wouldn’t want to rule out Democrats being competitive in states as far-flung as Utah, where independent Evan McMullin ran a fairly competitive race against Mike Lee this year.\\n\\nEven with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.\\nThat bleak picture may shape the next few years of political maneuvering. When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats have their Senate majority and be replaced by younger justices, it didn’t go over well. But it’s a perfectly rational suggestion if Democrats don’t feel like gambling with their judicial future. (Consider how consequential Ruth Bader Ginsburg’s decision not to retire has been for liberals.) Democrats have a narrow path to Senate control after 2024, but it’s narrow indeed, and one that might require the GOP continuing to nominate bad candidates — and a fair share of luck.\\npublish_date: 1670515535000.0\\nfull_text: 2028 Election\\nAre The Democrats Screwed In The Senate After 2024?\\nNo, but the party faces an uphill battle.\\n\\n\\n\\nBy Nate Silver\\n\\n\\nDec. 8, 2022, at 11:05 AM\\t\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nSamuel Corum / Getty Images\\n\\n\\n\\n\\nI’m not that impressed by long-term projections of Democratic doom in the Senate. Mostly that’s because I’m not that impressed by long-term political projections in general. Political coalitions change; not many people would have had it on their bingo card that Democrats would obtain a Senate majority in 2020 by winning two runoffs in Georgia, and then would actually expand on that majority in 2022 following another runoff in Georgia despite their party controlling the White House.\\nWith that said, while I don’t think we can say very much about what politics will look like 10 or 20 years from now, a medium-term look-ahead is possible. Do Democrats have a reasonable hope of regaining a trifecta — control of the House, Senate and presidency — at any point in the near future (2024, 2026 or 2028)? And how long will they hold onto control of the Senate and the presidency, allowing them to appoint Supreme Court justices without Republican help?\\nMy colleague Geoffrey Skelley already took an initial look at the 2024 Senate map, which is bad for Democrats, but I wanted to dig slightly deeper and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the Senate, because that’s the weakest link in Democrats’ effort to win back the trifecta. Despite some disadvantages in the Electoral College, Democrats obviously have no trouble winning the presidency. And they nearly held onto the House this year despite losing the popular vote for the House. The current House map doesn’t have much — if any — of a Republican skew, and Democrats should be able to win back the House if the national political environment is reasonably good for them.\\nSo let’s look at the 2024, 2026 and 2028 Senate maps (yes, 2028 features the same map as the midterm we just finished; I just can’t let go, I guess). We’ll classify races into bronze, silver, gold and platinum “tiers” in terms of how feasible they are as pickup opportunities. I’m deliberately using this goofy metallurgical theme as opposed to the categories FiveThirtyEight typically uses (e.g., “toss-up,” “lean Republican”) so you’ll recognize these as being back-of-the-envelope suppositions rather than any sort of official race ratings. \\nIn general, these ratings lean heavily on looking at how close a race was the last time it was contested, with some subjective adjustments for candidate quality. I’m also considering how the electoral environment has shifted within the state — Florida has gotten redder since Rick Scott was elected in 2018, for instance — although it is definitely not always safe to assume a state will continue trending in the same direction.\\n2024\\nRepublican pickup opportunities\\nPlatinum tier: West Virginia (Manchin), Montana (Tester), Ohio (Brown), \\nGold tier: Arizona (Sinema), Nevada (Rosen)\\nSilver tier: Wisconsin (Baldwin), Michigan (Stabenow), Pennsylvania (Casey)\\nBronze tier: New Jersey (Menendez), Virginia (Kaine)\\nAs Geoffrey noted, the platinum-tier states listed here are the Democrats’ main problem. They have three senators up for reelection in states that Donald Trump carried by 8 (Ohio), 16 (Montana) and 39 (West Virginia!) percentage points in 2020. Each of those Democratic senators won reelection in 2018, of course, but that was a strong Democratic year, and there’s been further movement of white voters without college degrees — a key part of the electorate in these states — toward Republicans since then.\\xa0\\nI don’t want to focus too much on any one individual race, but it’s probably safe to assume that Joe Manchin has the toughest reelection campaign of all. Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats also run the risk of retirements here; neither Manchin nor Jon Tester has officially yet announced they will seek reelection.\\nBeyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is likely to face a serious primary challenge. Democrats keep winning close races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and will likely be fine in the event of a decent-to-good Democratic year, but if 2024 turns into a good Republican year, they could be in trouble.\\nDemocratic pickup opportunities\\nPlatinum tier: None\\nGold tier: None\\nSilver tier: Texas (Cruz), Florida (Scott)\\nBronze tier: None\\nConversely, it’s very slim pickings for Democrats. On paper, you’d think that Texas might be close — Ted Cruz won by less than 3 percentage points there in 2018 and Texas is more competitive than it once was — but the erosion of the Democratic vote in South Texas has prevented Texas from turning truly purple. And although Scott won by only 0.12 percentage points in 2018, Republicans did so well in Florida in 2020 and 2022 that I was tempted to demote his race all the way to the bronze tier. Plus, there’s a good chance that the GOP’s 2024 nominee will be either Florida Gov. Ron DeSantis or Florida resident Donald Trump, which could help drive Republican turnout.\\nBeyond that, any other races look like an extreme stretch for Democrats. Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type environment, but that’s less likely in a presidential year and Hawley’s approval rating isn’t that bad. Put him in the “honorable mention” tier, I guess.\\nGiven all this, I’d imagine the modal outcome from 2024 is something like Republicans picking up about three Senate seats. There’s uncertainty around that; it’s surely within the realm of possibility that Democrats hold the Senate, but it’s also possible that Republicans could wind up with 54 or 55 seats. And of course, all of these races are correlated. If the GOP is doing well enough to win the presidency in 2024, they should have no trouble also winning the Senate.9\\n2026\\nRepublican pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Georgia (Ossoff), Michigan (Peters)\\nSilver tier: New Hampshire (Shaheen)\\nBronze tier: Minnesota (Smith), Virginia (Warner)\\nThe 2026 map is more balanced. Democrats undoubtedly feel pretty good about how they’ve performed in Georgia and Michigan in the past two cycles, but Jon Ossoff and Gary Peters won by extremely narrow margins in 2020 and it would be a mistake to assume they’re safe. It’s not a particularly deep set of pickup opportunities for Republicans, though if Democrats retain the presidency in 2024, you’d expect Republicans to have good midterms in 2026, and New Hampshire and perhaps even Minnesota and Virginia could potentially be in play.\\xa0\\nDemocratic pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Maine (Collins), North Carolina (Tillis)\\nSilver tier: Alaska (Sullivan)\\nBronze tier: Texas (Cornyn), Iowa (Ernst)\\nMeanwhile, Democrats will try again in the two states that were most disappointing to them in 2020: Maine and North Carolina. Given all the focus on Georgia, I wonder if North Carolina hasn’t become underrated as a place where Democrats could gain ground in the future; the states are fairly similar demographically and it wouldn’t take that much of a shift for Democrats to go from narrowly losing races in North Carolina to narrowly winning them. Susan Collins will be 74 years old in 2026, meanwhile, an age at which there’s typically some chance of retirement.\\nDemocrats also have a below-the-radar pickup opportunity in Alaska, where Mary Peltola was elected to a full term in the U.S. House10 last month by a 10-point margin after ranked-choice votes were tabulated. GOP incumbent Dan Sullivan has a mediocre approval rating and a Peltola-Sullivan race would potentially be competitive.\\nSuppose, though, that Democrats win the presidency but lose the Senate in 2024. It’s really not as crazy as it sounds. If every state votes identically to how it did in the 2020 presidential election — and every Senate race follows the presidential vote — then Democrats would come out of 2024 with the presidency but only 48 Senate seats after losing West Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from the GOP in the 2026 midterm while controlling the presidency? Unlikely — but then again, Democrats gaining Senate seats this year seemed unlikely and they did it.\\n2028\\nRepublican pickup opportunities\\nPlatinum tier: None\\nGold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), Georgia (Warnock) \\nSilver tier: New Hampshire (Hassan)\\nBronze tier: Oregon (Wyden)\\nAll right, now we’re literally coming full circle to consider the races that were just contested in last month’s midterm. So we’ll keep it pretty brief. Yes, Democrats have to feel pretty good about their wins in Nevada, Pennsylvania, Arizona and Georgia — especially given that the overall political environment wasn’t that great for Democrats this year. But they were narrow wins, and (with the possible exception of Nevada) they came against a mediocre set of GOP opponents. Maybe some of these races are toward the silver end of the gold tier, but more likely than not they’ll be competitive again.\\nAnd since we’re projecting a full six years out, I’m going to be a little bit more creative about considering long-shot opportunities in the bronze tier. Although the Senate races in Washington and Colorado received attention this year (Republicans spent a lot of money on both, only to lose by double digits), they wound up coming just as close in Oregon with a QAnon candidate as part of a comparatively strong year for the GOP in the Beaver State. Could a more mainstream GOP nominee have made it a race? Oregon is quite white, it has fewer people with college degrees than the “Portlandia” stereotype might make you assume, and Democratic incumbent Ron Wyden will be 79 years old in 2028 …\\nDemocratic pickup opportunities\\nPlatinum tier: None\\nGold tier: Wisconsin (Johnson), North Carolina (Budd)\\nSilver tier: Vance (Ohio)\\nBronze tier: Alaska (Murkowski), Florida (Rubio), Utah (Lee), Iowa (Grassley)\\nAgain, we’re mostly just rehashing this year’s map. Ron Johnson, who originally hadn’t planned on running in 2020, is another retirement threat in 2026 — and he barely won reelection anyway. In Ohio, Sherrod Brown could seek to return to the Senate if he loses in 2024 by challenging J.D. Vance. And 2028 is far enough from now that I wouldn’t want to rule out Democrats being competitive in states as far-flung as Utah, where independent Evan McMullin ran a fairly competitive race against Mike Lee this year.\\n\\nEven with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.\\nThat bleak picture may shape the next few years of political maneuvering. When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats have their Senate majority and be replaced by younger justices, it didn’t go over well. But it’s a perfectly rational suggestion if Democrats don’t feel like gambling with their judicial future. (Consider how consequential Ruth Bader Ginsburg’s decision not to retire has been for liberals.) Democrats have a narrow path to Senate control after 2024, but it’s narrow indeed, and one that might require the GOP continuing to nominate bad candidates — and a fair share of luck.\\nurl: https://fivethirtyeight.com/features/democrats-senate-chances-2024-and-beyond/\\ncategories: ['news']\" metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}\n"
- ]
- }
- ],
- "source": [
- "print(data[0])"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "9OlS2Kx8FlVx",
- "outputId": "8e891267-6921-46ad-961c-ddd0a2d33760"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "You have 100 document(s) in your data\n",
- "There are 23887 words in your document\n"
- ]
- }
- ],
- "source": [
- "print (f'You have {len(data)} document(s) in your data')\n",
- "print (f'There are {len(data[0].page_content)} words in your document')"
- ]
- },
- {
- "cell_type": "markdown",
- "source": [
- "2. Breakdown data - Chunking Process"
- ],
- "metadata": {
- "id": "Vm0lO--f80NZ"
- }
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "FOUcWZF3Gk8n"
- },
- "outputs": [],
- "source": [
- "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n",
- "texts = text_splitter.split_documents(data)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "xdJDpvcBGnp3",
- "outputId": "3c129195-32d6-4df8-b0d2-1e49a74f1609"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "1192"
- ]
- },
- "metadata": {},
- "execution_count": 24
- }
- ],
- "source": [
- "len(texts)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "jaRsK0qaZ9Fk",
- "outputId": "91bf63db-9e03-4db0-8506-f4303d5fe782"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "You now have 1192 document(s) in your data\n",
- "There are 951 characters in your document\n"
- ]
- }
- ],
- "source": [
- "print (f'You now have {len(texts)} document(s) in your data')\n",
- "print (f'There are {len(texts[1].page_content)} characters in your document')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "qaFGDzkjMRJG",
- "outputId": "9249d2ba-1070-4de0-df11-0dfc1a7c8160"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "Document(page_content='Suppose, though, that Democrats win the presidency but lose the Senate in 2024. It’s really not as crazy as it sounds. If every state votes identically to how it did in the 2020 presidential election — and every Senate race follows the presidential vote — then Democrats would come out of 2024 with the presidency but only 48 Senate seats after losing West Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from the GOP in the 2026 midterm while controlling the presidency? Unlikely — but then again, Democrats gaining Senate seats this year seemed unlikely and they did it.\\n2028\\nRepublican pickup opportunities\\nPlatinum tier: None\\nGold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), Georgia (Warnock) \\nSilver tier: New Hampshire (Hassan)\\nBronze tier: Oregon (Wyden)', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0})"
- ]
- },
- "metadata": {},
- "execution_count": 26
- }
- ],
- "source": [
- "texts[10]"
- ]
- },
- {
- "cell_type": "code",
- "source": [
- "!pip install -U langchain-openai\n",
- "from langchain_openai import OpenAIEmbeddings\n",
- "from langchain_openai import ChatOpenAI"
- ],
- "metadata": {
- "id": "O-acByeSuScf",
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "outputId": "d6deb120-c4a2-4b21-b4cb-536c783c774f"
- },
- "execution_count": null,
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "Collecting langchain-openai\n",
- " Downloading langchain_openai-0.0.5-py3-none-any.whl (29 kB)\n",
- "Requirement already satisfied: langchain-core<0.2,>=0.1.16 in /usr/local/lib/python3.10/dist-packages (from langchain-openai) (0.1.18)\n",
- "Requirement already satisfied: numpy<2,>=1 in /usr/local/lib/python3.10/dist-packages (from langchain-openai) (1.23.5)\n",
- "Requirement already satisfied: openai<2.0.0,>=1.10.0 in /usr/local/lib/python3.10/dist-packages (from langchain-openai) (1.11.0)\n",
- "Requirement already satisfied: tiktoken<0.6.0,>=0.5.2 in /usr/local/lib/python3.10/dist-packages (from langchain-openai) (0.5.2)\n",
- "Requirement already satisfied: PyYAML>=5.3 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (6.0.1)\n",
- "Requirement already satisfied: anyio<5,>=3 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (3.7.1)\n",
- "Requirement already satisfied: jsonpatch<2.0,>=1.33 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (1.33)\n",
- "Requirement already satisfied: langsmith<0.1,>=0.0.83 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (0.0.86)\n",
- "Requirement already satisfied: packaging<24.0,>=23.2 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (23.2)\n",
- "Requirement already satisfied: pydantic<3,>=1 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (2.6.0)\n",
- "Requirement already satisfied: requests<3,>=2 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (2.31.0)\n",
- "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in /usr/local/lib/python3.10/dist-packages (from langchain-core<0.2,>=0.1.16->langchain-openai) (8.2.3)\n",
- "Requirement already satisfied: distro<2,>=1.7.0 in /usr/lib/python3/dist-packages (from openai<2.0.0,>=1.10.0->langchain-openai) (1.7.0)\n",
- "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.10.0->langchain-openai) (0.26.0)\n",
- "Requirement already satisfied: sniffio in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.10.0->langchain-openai) (1.3.0)\n",
- "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.10.0->langchain-openai) (4.66.1)\n",
- "Requirement already satisfied: typing-extensions<5,>=4.7 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.10.0->langchain-openai) (4.9.0)\n",
- "Requirement already satisfied: regex>=2022.1.18 in /usr/local/lib/python3.10/dist-packages (from tiktoken<0.6.0,>=0.5.2->langchain-openai) (2023.12.25)\n",
- "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.10/dist-packages (from anyio<5,>=3->langchain-core<0.2,>=0.1.16->langchain-openai) (3.6)\n",
- "Requirement already satisfied: exceptiongroup in /usr/local/lib/python3.10/dist-packages (from anyio<5,>=3->langchain-core<0.2,>=0.1.16->langchain-openai) (1.2.0)\n",
- "Requirement already satisfied: certifi in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.23.0->openai<2.0.0,>=1.10.0->langchain-openai) (2023.11.17)\n",
- "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.10/dist-packages (from httpx<1,>=0.23.0->openai<2.0.0,>=1.10.0->langchain-openai) (1.0.2)\n",
- "Requirement already satisfied: h11<0.15,>=0.13 in /usr/local/lib/python3.10/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai<2.0.0,>=1.10.0->langchain-openai) (0.14.0)\n",
- "Requirement already satisfied: jsonpointer>=1.9 in /usr/local/lib/python3.10/dist-packages (from jsonpatch<2.0,>=1.33->langchain-core<0.2,>=0.1.16->langchain-openai) (2.4)\n",
- "Requirement already satisfied: annotated-types>=0.4.0 in /usr/local/lib/python3.10/dist-packages (from pydantic<3,>=1->langchain-core<0.2,>=0.1.16->langchain-openai) (0.6.0)\n",
- "Requirement already satisfied: pydantic-core==2.16.1 in /usr/local/lib/python3.10/dist-packages (from pydantic<3,>=1->langchain-core<0.2,>=0.1.16->langchain-openai) (2.16.1)\n",
- "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain-core<0.2,>=0.1.16->langchain-openai) (3.3.2)\n",
- "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain-core<0.2,>=0.1.16->langchain-openai) (2.0.7)\n",
- "Installing collected packages: langchain-openai\n",
- "Successfully installed langchain-openai-0.0.5\n"
- ]
- }
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "ZV4m9sie7WVV"
- },
- "outputs": [],
- "source": [
- "embeddings = OpenAIEmbeddings()\n",
- "db = FAISS.from_documents(texts, embeddings)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "AMkkNB3U7WVV"
- },
- "outputs": [],
- "source": [
- "query = \"\"\"Why is it so bad for Democrats in Senate in 2024\"\"\""
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "tCaQyBkz7WVV"
- },
- "outputs": [],
- "source": [
- "def get_response_from_query(db, query, k=10):\n",
- " \"\"\"\n",
- "\n",
- " \"\"\"\n",
- "\n",
- " docs = db.similarity_search(query, k=k) # extremely important\n",
- "\n",
- " docs_page_content = \" \".join([d.page_content for d in docs])\n",
- "\n",
- " # llm = BardLLM()\n",
- " llm = ChatOpenAI(model_name=\"gpt-3.5-turbo-16k\",temperature=0)\n",
- "\n",
- " prompt = PromptTemplate(\n",
- " input_variables=[\"question\", \"docs\"],\n",
- " template=\"\"\"\n",
- " You are a bot that is open to discussions about different cultural, philosophical and political exchanges. I will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only.\n",
- " Answer the following question: {question}\n",
- " By searching the following articles: {docs}\n",
- "\n",
- " Only use the factual information from the documents. Make sure to mention key phrases from the articles.\n",
- "\n",
- " If you feel like you don't have enough information to answer the question, say \"I don't know\".\n",
- "\n",
- " \"\"\",\n",
- " )\n",
- "\n",
- " chain = LLMChain(llm=llm, prompt=prompt)\n",
- " # chain = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, prompt=prompt,\n",
- " # chain_type=\"stuff\", retriever=db.as_retriever(), return_source_documents=True)\n",
- "\n",
- " response = chain.run(question=query, docs=docs_page_content,return_source_documents=True)\n",
- " r_text = str(response)\n",
- "\n",
- " ##evaluation part\n",
- "\n",
- " prompt_eval = PromptTemplate(\n",
- " input_variables=[\"answer\", \"docs\"],\n",
- " template=\"\"\"\n",
- " You job is to evaluate if the response to a given context is faithful.\n",
- "\n",
- " for the following: {answer}\n",
- " By searching the following article: {docs}\n",
- "\n",
- " Give a reason why they are similar or not, start with a Yes or a No.\n",
- "\n",
- " \"\"\",\n",
- " )\n",
- "\n",
- " chain_part_2 = LLMChain(llm=llm, prompt=prompt_eval)\n",
- "\n",
- " evals = chain_part_2.run(answer=r_text, docs=docs_page_content)\n",
- "\n",
- "\n",
- " return response,docs,evals"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "twZ_ILhJ7WVV",
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "outputId": "8256686e-896c-40a0-aa72-e0c5cf4f2b2d"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stderr",
- "text": [
- "/usr/local/lib/python3.10/dist-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `run` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
- " warn_deprecated(\n"
- ]
- }
- ],
- "source": [
- "answer,sources,evals=get_response_from_query(db,query,15)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "Xaa84xr109s5",
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "outputId": "e0205d3c-a717-4d0f-97cb-b084e167a058"
- },
- "outputs": [
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": [
- "[Document(page_content='Even with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='Even with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='My colleague Geoffrey Skelley already took an initial look at the 2024 Senate map, which is bad for Democrats, but I wanted to dig slightly deeper and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the Senate, because that’s the weakest link in Democrats’ effort to win back the trifecta. Despite some disadvantages in the Electoral College, Democrats obviously have no trouble winning the presidency. And they nearly held onto the House this year despite losing the popular vote for the House. The current House map doesn’t have much — if any — of a Republican skew, and Democrats should be able to win back the House if the national political environment is reasonably good for them.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='My colleague Geoffrey Skelley already took an initial look at the 2024 Senate map, which is bad for Democrats, but I wanted to dig slightly deeper and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the Senate, because that’s the weakest link in Democrats’ effort to win back the trifecta. Despite some disadvantages in the Electoral College, Democrats obviously have no trouble winning the presidency. And they nearly held onto the House this year despite losing the popular vote for the House. The current House map doesn’t have much — if any — of a Republican skew, and Democrats should be able to win back the House if the national political environment is reasonably good for them.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='That bleak picture may shape the next few years of political maneuvering. When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats have their Senate majority and be replaced by younger justices, it didn’t go over well. But it’s a perfectly rational suggestion if Democrats don’t feel like gambling with their judicial future. (Consider how consequential Ruth Bader Ginsburg’s decision not to retire has been for liberals.) Democrats have a narrow path to Senate control after 2024, but it’s narrow indeed, and one that might require the GOP continuing to nominate bad candidates — and a fair share of luck.\\npublish_date: 1670515535000.0\\nfull_text: 2028 Election\\nAre The Democrats Screwed In The Senate After 2024?\\nNo, but the party faces an uphill battle.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='Suppose, though, that Democrats win the presidency but lose the Senate in 2024. It’s really not as crazy as it sounds. If every state votes identically to how it did in the 2020 presidential election — and every Senate race follows the presidential vote — then Democrats would come out of 2024 with the presidency but only 48 Senate seats after losing West Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from the GOP in the 2026 midterm while controlling the presidency? Unlikely — but then again, Democrats gaining Senate seats this year seemed unlikely and they did it.\\n2028\\nRepublican pickup opportunities\\nPlatinum tier: None\\nGold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), Georgia (Warnock) \\nSilver tier: New Hampshire (Hassan)\\nBronze tier: Oregon (Wyden)', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='Suppose, though, that Democrats win the presidency but lose the Senate in 2024. It’s really not as crazy as it sounds. If every state votes identically to how it did in the 2020 presidential election — and every Senate race follows the presidential vote — then Democrats would come out of 2024 with the presidency but only 48 Senate seats after losing West Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from the GOP in the 2026 midterm while controlling the presidency? Unlikely — but then again, Democrats gaining Senate seats this year seemed unlikely and they did it.\\n2028\\nRepublican pickup opportunities\\nPlatinum tier: None\\nGold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), Georgia (Warnock) \\nSilver tier: New Hampshire (Hassan)\\nBronze tier: Oregon (Wyden)', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='Beyond that, any other races look like an extreme stretch for Democrats. Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type environment, but that’s less likely in a presidential year and Hawley’s approval rating isn’t that bad. Put him in the “honorable mention” tier, I guess.\\nGiven all this, I’d imagine the modal outcome from 2024 is something like Republicans picking up about three Senate seats. There’s uncertainty around that; it’s surely within the realm of possibility that Democrats hold the Senate, but it’s also possible that Republicans could wind up with 54 or 55 seats. And of course, all of these races are correlated. If the GOP is doing well enough to win the presidency in 2024, they should have no trouble also winning the Senate.9\\n2026\\nRepublican pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Georgia (Ossoff), Michigan (Peters)\\nSilver tier: New Hampshire (Shaheen)\\nBronze tier: Minnesota (Smith), Virginia (Warner)', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='Beyond that, any other races look like an extreme stretch for Democrats. Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type environment, but that’s less likely in a presidential year and Hawley’s approval rating isn’t that bad. Put him in the “honorable mention” tier, I guess.\\nGiven all this, I’d imagine the modal outcome from 2024 is something like Republicans picking up about three Senate seats. There’s uncertainty around that; it’s surely within the realm of possibility that Democrats hold the Senate, but it’s also possible that Republicans could wind up with 54 or 55 seats. And of course, all of these races are correlated. If the GOP is doing well enough to win the presidency in 2024, they should have no trouble also winning the Senate.9\\n2026\\nRepublican pickup opportunities\\xa0\\nPlatinum tier: None\\nGold tier: Georgia (Ossoff), Michigan (Peters)\\nSilver tier: New Hampshire (Shaheen)\\nBronze tier: Minnesota (Smith), Virginia (Warner)', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='I’m not that impressed by long-term projections of Democratic doom in the Senate. Mostly that’s because I’m not that impressed by long-term political projections in general. Political coalitions change; not many people would have had it on their bingo card that Democrats would obtain a Senate majority in 2020 by winning two runoffs in Georgia, and then would actually expand on that majority in 2022 following another runoff in Georgia despite their party controlling the White House.\\nWith that said, while I don’t think we can say very much about what politics will look like 10 or 20 years from now, a medium-term look-ahead is possible. Do Democrats have a reasonable hope of regaining a trifecta — control of the House, Senate and presidency — at any point in the near future (2024, 2026 or 2028)? And how long will they hold onto control of the Senate and the presidency, allowing them to appoint Supreme Court justices without Republican help?', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='I’m not that impressed by long-term projections of Democratic doom in the Senate. Mostly that’s because I’m not that impressed by long-term political projections in general. Political coalitions change; not many people would have had it on their bingo card that Democrats would obtain a Senate majority in 2020 by winning two runoffs in Georgia, and then would actually expand on that majority in 2022 following another runoff in Georgia despite their party controlling the White House.\\nWith that said, while I don’t think we can say very much about what politics will look like 10 or 20 years from now, a medium-term look-ahead is possible. Do Democrats have a reasonable hope of regaining a trifecta — control of the House, Senate and presidency — at any point in the near future (2024, 2026 or 2028)? And how long will they hold onto control of the Senate and the presidency, allowing them to appoint Supreme Court justices without Republican help?', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content=\"That bleak picture may shape the next few years of political maneuvering. When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats have their Senate majority and be replaced by younger justices, it didn’t go over well. But it’s a perfectly rational suggestion if Democrats don’t feel like gambling with their judicial future. (Consider how consequential Ruth Bader Ginsburg’s decision not to retire has been for liberals.) Democrats have a narrow path to Senate control after 2024, but it’s narrow indeed, and one that might require the GOP continuing to nominate bad candidates — and a fair share of luck.\\nurl: https://fivethirtyeight.com/features/democrats-senate-chances-2024-and-beyond/\\ncategories: ['news']\", metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='_id: 63927168098523fa9d5ef047\\ntitle: Are The Democrats Screwed In The Senate After 2024?\\nauthor: Nate Silver\\ndescription: Are The Democrats Screwed In The Senate After 2024?\\nNo, but the party faces an uphill battlee', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='I don’t want to focus too much on any one individual race, but it’s probably safe to assume that Joe Manchin has the toughest reelection campaign of all. Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats also run the risk of retirements here; neither Manchin nor Jon Tester has officially yet announced they will seek reelection.\\nBeyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is likely to face a serious primary challenge. Democrats keep winning close races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and will likely be fine in the event of a decent-to-good Democratic year, but if 2024 turns into a good Republican year, they could be in trouble.\\nDemocratic pickup opportunities', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}),\n",
- " Document(page_content='I don’t want to focus too much on any one individual race, but it’s probably safe to assume that Joe Manchin has the toughest reelection campaign of all. Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats also run the risk of retirements here; neither Manchin nor Jon Tester has officially yet announced they will seek reelection.\\nBeyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is likely to face a serious primary challenge. Democrats keep winning close races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and will likely be fine in the event of a decent-to-good Democratic year, but if 2024 turns into a good Republican year, they could be in trouble.\\nDemocratic pickup opportunities', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0})]"
- ]
- },
- "metadata": {},
- "execution_count": 33
- }
- ],
- "source": [
- "sources"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "K7P30pL57WVV",
- "outputId": "928ac23c-0111-4520-ea8c-e1cbbff9e803"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "\n",
- "\n",
- "> Question:\n",
- "'Why is it so bad for Democrats in Senate in 2024'\n",
- "\n",
- "> Answer:\n",
- "('Based on the articles provided, it is suggested that the 2024 Senate map is '\n",
- " 'unfavorable for Democrats, making it difficult for them to maintain control '\n",
- " 'of the Senate. The articles mention that Democrats may face challenges in '\n",
- " 'the 2024 Senate races, potentially losing seats in states like West '\n",
- " 'Virginia, Montana, and Ohio. It is also mentioned that Democrats have a '\n",
- " 'narrow path to Senate control after 2024 and that their prospects might rely '\n",
- " 'on limiting the damage in 2024 to have a chance of regaining the Senate in '\n",
- " '2026 or 2028. The articles highlight the importance of the GOP nominating '\n",
- " 'bad candidates and luck for Democrats to have a better chance of regaining '\n",
- " 'the Senate. Overall, the articles suggest that the 2024 Senate map poses '\n",
- " 'challenges for Democrats and that it may be difficult for them to regain '\n",
- " 'control of the Senate before 2030 or 2032.')\n",
- "\n",
- "> Eval:\n",
- "('Yes, the response is faithful to the context. The response accurately '\n",
- " 'reflects the information provided in the articles about the challenges '\n",
- " 'Democrats may face in the 2024 Senate races and their narrow path to Senate '\n",
- " 'control after 2024. It also mentions the importance of the GOP nominating '\n",
- " 'bad candidates and luck for Democrats to have a better chance of regaining '\n",
- " 'the Senate.')\n",
- "----------------------------------SOURCE DOCUMENTS---------------------------\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Even with an additional senator going into 2023, the 2024 map is still so '\n",
- " 'bad for Democrats that keeping the Senate for years to come will be a fairly '\n",
- " 'tough order. The party’s prospects might rest more upon limiting the damage '\n",
- " 'in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a '\n",
- " 'bad 2024 could make it very difficult for Democrats to regain the Senate '\n",
- " 'before 2030 or 2032.')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Even with an additional senator going into 2023, the 2024 map is still so '\n",
- " 'bad for Democrats that keeping the Senate for years to come will be a fairly '\n",
- " 'tough order. The party’s prospects might rest more upon limiting the damage '\n",
- " 'in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a '\n",
- " 'bad 2024 could make it very difficult for Democrats to regain the Senate '\n",
- " 'before 2030 or 2032.')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('My colleague Geoffrey Skelley already took an initial look at the 2024 '\n",
- " 'Senate map, which is bad for Democrats, but I wanted to dig slightly deeper '\n",
- " 'and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the '\n",
- " 'Senate, because that’s the weakest link in Democrats’ effort to win back the '\n",
- " 'trifecta. Despite some disadvantages in the Electoral College, Democrats '\n",
- " 'obviously have no trouble winning the presidency. And they nearly held onto '\n",
- " 'the House this year despite losing the popular vote for the House. The '\n",
- " 'current House map doesn’t have much — if any — of a Republican skew, and '\n",
- " 'Democrats should be able to win back the House if the national political '\n",
- " 'environment is reasonably good for them.')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('My colleague Geoffrey Skelley already took an initial look at the 2024 '\n",
- " 'Senate map, which is bad for Democrats, but I wanted to dig slightly deeper '\n",
- " 'and also consider 2026 and 2028. Like Geoffrey, I’ll be focused on the '\n",
- " 'Senate, because that’s the weakest link in Democrats’ effort to win back the '\n",
- " 'trifecta. Despite some disadvantages in the Electoral College, Democrats '\n",
- " 'obviously have no trouble winning the presidency. And they nearly held onto '\n",
- " 'the House this year despite losing the popular vote for the House. The '\n",
- " 'current House map doesn’t have much — if any — of a Republican skew, and '\n",
- " 'Democrats should be able to win back the House if the national political '\n",
- " 'environment is reasonably good for them.')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('That bleak picture may shape the next few years of political maneuvering. '\n",
- " 'When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia '\n",
- " 'Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats '\n",
- " 'have their Senate majority and be replaced by younger justices, it didn’t go '\n",
- " 'over well. But it’s a perfectly rational suggestion if Democrats don’t feel '\n",
- " 'like gambling with their judicial future. (Consider how consequential Ruth '\n",
- " 'Bader Ginsburg’s decision not to retire has been for liberals.) Democrats '\n",
- " 'have a narrow path to Senate control after 2024, but it’s narrow indeed, and '\n",
- " 'one that might require the GOP continuing to nominate bad candidates — and a '\n",
- " 'fair share of luck.\\n'\n",
- " 'publish_date: 1670515535000.0\\n'\n",
- " 'full_text: 2028 Election\\n'\n",
- " 'Are The Democrats Screwed In The Senate After 2024?\\n'\n",
- " 'No, but the party faces an uphill battle.')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Suppose, though, that Democrats win the presidency but lose the Senate in '\n",
- " '2024. It’s really not as crazy as it sounds. If every state votes '\n",
- " 'identically to how it did in the 2020 presidential election — and every '\n",
- " 'Senate race follows the presidential vote — then Democrats would come out of '\n",
- " '2024 with the presidency but only 48 Senate seats after losing West '\n",
- " 'Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from '\n",
- " 'the GOP in the 2026 midterm while controlling the presidency? Unlikely — but '\n",
- " 'then again, Democrats gaining Senate seats this year seemed unlikely and '\n",
- " 'they did it.\\n'\n",
- " '2028\\n'\n",
- " 'Republican pickup opportunities\\n'\n",
- " 'Platinum tier: None\\n'\n",
- " 'Gold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), '\n",
- " 'Georgia (Warnock) \\n'\n",
- " 'Silver tier: New Hampshire (Hassan)\\n'\n",
- " 'Bronze tier: Oregon (Wyden)')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Suppose, though, that Democrats win the presidency but lose the Senate in '\n",
- " '2024. It’s really not as crazy as it sounds. If every state votes '\n",
- " 'identically to how it did in the 2020 presidential election — and every '\n",
- " 'Senate race follows the presidential vote — then Democrats would come out of '\n",
- " '2024 with the presidency but only 48 Senate seats after losing West '\n",
- " 'Virginia, Montana and Ohio. Could Democrats pick up two Senate seats from '\n",
- " 'the GOP in the 2026 midterm while controlling the presidency? Unlikely — but '\n",
- " 'then again, Democrats gaining Senate seats this year seemed unlikely and '\n",
- " 'they did it.\\n'\n",
- " '2028\\n'\n",
- " 'Republican pickup opportunities\\n'\n",
- " 'Platinum tier: None\\n'\n",
- " 'Gold tier: Nevada (Cortez Masto), Pennsylvania (Fetterman), Arizona (Kelly), '\n",
- " 'Georgia (Warnock) \\n'\n",
- " 'Silver tier: New Hampshire (Hassan)\\n'\n",
- " 'Bronze tier: Oregon (Wyden)')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Beyond that, any other races look like an extreme stretch for Democrats. '\n",
- " 'Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type '\n",
- " 'environment, but that’s less likely in a presidential year and Hawley’s '\n",
- " 'approval rating isn’t that bad. Put him in the “honorable mention” tier, I '\n",
- " 'guess.\\n'\n",
- " 'Given all this, I’d imagine the modal outcome from 2024 is something like '\n",
- " 'Republicans picking up about three Senate seats. There’s uncertainty around '\n",
- " 'that; it’s surely within the realm of possibility that Democrats hold the '\n",
- " 'Senate, but it’s also possible that Republicans could wind up with 54 or 55 '\n",
- " 'seats. And of course, all of these races are correlated. If the GOP is doing '\n",
- " 'well enough to win the presidency in 2024, they should have no trouble also '\n",
- " 'winning the Senate.9\\n'\n",
- " '2026\\n'\n",
- " 'Republican pickup opportunities\\xa0\\n'\n",
- " 'Platinum tier: None\\n'\n",
- " 'Gold tier: Georgia (Ossoff), Michigan (Peters)\\n'\n",
- " 'Silver tier: New Hampshire (Shaheen)\\n'\n",
- " 'Bronze tier: Minnesota (Smith), Virginia (Warner)')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('Beyond that, any other races look like an extreme stretch for Democrats. '\n",
- " 'Maybe Josh Hawley in Missouri could be vulnerable in a 2018-type '\n",
- " 'environment, but that’s less likely in a presidential year and Hawley’s '\n",
- " 'approval rating isn’t that bad. Put him in the “honorable mention” tier, I '\n",
- " 'guess.\\n'\n",
- " 'Given all this, I’d imagine the modal outcome from 2024 is something like '\n",
- " 'Republicans picking up about three Senate seats. There’s uncertainty around '\n",
- " 'that; it’s surely within the realm of possibility that Democrats hold the '\n",
- " 'Senate, but it’s also possible that Republicans could wind up with 54 or 55 '\n",
- " 'seats. And of course, all of these races are correlated. If the GOP is doing '\n",
- " 'well enough to win the presidency in 2024, they should have no trouble also '\n",
- " 'winning the Senate.9\\n'\n",
- " '2026\\n'\n",
- " 'Republican pickup opportunities\\xa0\\n'\n",
- " 'Platinum tier: None\\n'\n",
- " 'Gold tier: Georgia (Ossoff), Michigan (Peters)\\n'\n",
- " 'Silver tier: New Hampshire (Shaheen)\\n'\n",
- " 'Bronze tier: Minnesota (Smith), Virginia (Warner)')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('I’m not that impressed by long-term projections of Democratic doom in the '\n",
- " 'Senate. Mostly that’s because I’m not that impressed by long-term political '\n",
- " 'projections in general. Political coalitions change; not many people would '\n",
- " 'have had it on their bingo card that Democrats would obtain a Senate '\n",
- " 'majority in 2020 by winning two runoffs in Georgia, and then would actually '\n",
- " 'expand on that majority in 2022 following another runoff in Georgia despite '\n",
- " 'their party controlling the White House.\\n'\n",
- " 'With that said, while I don’t think we can say very much about what politics '\n",
- " 'will look like 10 or 20 years from now, a medium-term look-ahead is '\n",
- " 'possible. Do Democrats have a reasonable hope of regaining a trifecta — '\n",
- " 'control of the House, Senate and presidency — at any point in the near '\n",
- " 'future (2024, 2026 or 2028)? And how long will they hold onto control of the '\n",
- " 'Senate and the presidency, allowing them to appoint Supreme Court justices '\n",
- " 'without Republican help?')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('I’m not that impressed by long-term projections of Democratic doom in the '\n",
- " 'Senate. Mostly that’s because I’m not that impressed by long-term political '\n",
- " 'projections in general. Political coalitions change; not many people would '\n",
- " 'have had it on their bingo card that Democrats would obtain a Senate '\n",
- " 'majority in 2020 by winning two runoffs in Georgia, and then would actually '\n",
- " 'expand on that majority in 2022 following another runoff in Georgia despite '\n",
- " 'their party controlling the White House.\\n'\n",
- " 'With that said, while I don’t think we can say very much about what politics '\n",
- " 'will look like 10 or 20 years from now, a medium-term look-ahead is '\n",
- " 'possible. Do Democrats have a reasonable hope of regaining a trifecta — '\n",
- " 'control of the House, Senate and presidency — at any point in the near '\n",
- " 'future (2024, 2026 or 2028)? And how long will they hold onto control of the '\n",
- " 'Senate and the presidency, allowing them to appoint Supreme Court justices '\n",
- " 'without Republican help?')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('That bleak picture may shape the next few years of political maneuvering. '\n",
- " 'When Vox’s Dylan Matthews suggested on Twitter that liberal Justices Sonia '\n",
- " 'Sotomayor (age 68) and Elena Kagan (age 62) should retire while Democrats '\n",
- " 'have their Senate majority and be replaced by younger justices, it didn’t go '\n",
- " 'over well. But it’s a perfectly rational suggestion if Democrats don’t feel '\n",
- " 'like gambling with their judicial future. (Consider how consequential Ruth '\n",
- " 'Bader Ginsburg’s decision not to retire has been for liberals.) Democrats '\n",
- " 'have a narrow path to Senate control after 2024, but it’s narrow indeed, and '\n",
- " 'one that might require the GOP continuing to nominate bad candidates — and a '\n",
- " 'fair share of luck.\\n'\n",
- " 'url: '\n",
- " 'https://fivethirtyeight.com/features/democrats-senate-chances-2024-and-beyond/\\n'\n",
- " \"categories: ['news']\")\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('_id: 63927168098523fa9d5ef047\\n'\n",
- " 'title: Are The Democrats Screwed In The Senate After 2024?\\n'\n",
- " 'author: Nate Silver\\n'\n",
- " 'description: Are The Democrats Screwed In The Senate After 2024?\\n'\n",
- " 'No, but the party faces an uphill battlee')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('I don’t want to focus too much on any one individual race, but it’s probably '\n",
- " 'safe to assume that Joe Manchin has the toughest reelection campaign of all. '\n",
- " 'Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim '\n",
- " 'Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and '\n",
- " 'Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats '\n",
- " 'also run the risk of retirements here; neither Manchin nor Jon Tester has '\n",
- " 'officially yet announced they will seek reelection.\\n'\n",
- " 'Beyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is '\n",
- " 'likely to face a serious primary challenge. Democrats keep winning close '\n",
- " 'races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, '\n",
- " 'Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and '\n",
- " 'will likely be fine in the event of a decent-to-good Democratic year, but if '\n",
- " '2024 turns into a good Republican year, they could be in trouble.\\n'\n",
- " 'Democratic pickup opportunities')\n",
- "\n",
- "> Are The Democrats Screwed In The Senate After 2024?\n",
- "('I don’t want to focus too much on any one individual race, but it’s probably '\n",
- " 'safe to assume that Joe Manchin has the toughest reelection campaign of all. '\n",
- " 'Meanwhile, maybe Sherrod Brown can feel a bit more comfortable following Tim '\n",
- " 'Ryan’s relatively good performance in Ohio this year, but Ryan did lose, and '\n",
- " 'Brown may face a tougher opponent than Ryan did in J.D. Vance. Democrats '\n",
- " 'also run the risk of retirements here; neither Manchin nor Jon Tester has '\n",
- " 'officially yet announced they will seek reelection.\\n'\n",
- " 'Beyond the platinum tier, Democrats face some other risks. Kyrsten Sinema is '\n",
- " 'likely to face a serious primary challenge. Democrats keep winning close '\n",
- " 'races for Congress in Nevada but it’s a very purple state. Tammy Baldwin, '\n",
- " 'Debbie Stabenow and Bob Casey won by fairly comfortable margins in 2018 and '\n",
- " 'will likely be fine in the event of a decent-to-good Democratic year, but if '\n",
- " '2024 turns into a good Republican year, they could be in trouble.\\n'\n",
- " 'Democratic pickup opportunities')\n",
- "----------------------------------SOURCE DOCUMENTS---------------------------\n"
- ]
- }
- ],
- "source": [
- "from pprint import pprint\n",
- "\n",
- "# Print question, answer, and evaluations\n",
- "print(\"\\n\\n> Question:\")\n",
- "pprint(query)\n",
- "print(\"\\n> Answer:\")\n",
- "pprint(answer)\n",
- "print(\"\\n> Eval:\")\n",
- "pprint(evals)\n",
- "\n",
- "# Print the relevant sources used for the answer\n",
- "print(\"----------------------------------SOURCE DOCUMENTS---------------------------\")\n",
- "for document in sources:\n",
- " print(\"\\n> \" + document.metadata[\"source\"])\n",
- " pprint(document.page_content[:1000])\n",
- "print(\"----------------------------------SOURCE DOCUMENTS---------------------------\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "UV7_OQHg7WVW"
- },
- "outputs": [],
- "source": [
- "import gradio as gr"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "n1wKmRl37WVW"
- },
- "outputs": [],
- "source": [
- "def get_response_from_query(db, query, k=3):\n",
- "\n",
- "\n",
- " docs = db.similarity_search(query, k=k)\n",
- "\n",
- " docs_page_content = \" \".join([d.page_content for d in docs])\n",
- "\n",
- " # llm = BardLLM()\n",
- " llm = ChatOpenAI(model_name=\"gpt-3.5-turbo-16k\",temperature=0)\n",
- "\n",
- " prompt = PromptTemplate(\n",
- " input_variables=[\"question\", \"docs\"],\n",
- " template=\"\"\"\n",
- " A bot that is open to discussions about different cultural, philosophical and political exchanges. I will use do different analysis to the articles provided to me. Stay truthful and if you weren't provided any resources give your oppinion only.\n",
- " Answer the following question: {question}\n",
- " By searching the following articles: {docs}\n",
- "\n",
- " Only use the factual information from the documents. Make sure to mention key phrases from the articles.\n",
- "\n",
- " If you feel like you don't have enough information to answer the question, say \"I don't know\".\n",
- "\n",
- " \"\"\",\n",
- " )\n",
- "\n",
- " chain = LLMChain(llm=llm, prompt=prompt)\n",
- " # chain = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, prompt=prompt,\n",
- " # chain_type=\"stuff\", retriever=db.as_retriever(), return_source_documents=True)\n",
- "\n",
- " response = chain.run(question=query, docs=docs_page_content,return_source_documents=True)\n",
- " r_text = str(response)\n",
- "\n",
- " ##evaluation part\n",
- "\n",
- " prompt_eval = PromptTemplate(\n",
- " input_variables=[\"answer\", \"docs\"],\n",
- " template=\"\"\"\n",
- " You job is to evaluate if the response to a given context is faithful.\n",
- "\n",
- " for the following: {answer}\n",
- " By searching the following article: {docs}\n",
- "\n",
- " Give a reason why they are similar or not, start with a Yes or a No.\n",
- " \"\"\",\n",
- " )\n",
- "\n",
- " chain_part_2 = LLMChain(llm=llm, prompt=prompt_eval)\n",
- "\n",
- "\n",
- " evals = chain_part_2.run(answer=r_text, docs=docs_page_content)\n",
- "\n",
- " return response,docs,evals"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "7VMW3kDRG2lM"
- },
- "outputs": [],
- "source": [
- "from linkify_it import LinkifyIt"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "IdKyZMdyjQ1g"
- },
- "outputs": [],
- "source": [
- "#!pip list"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 610
- },
- "id": "YqMJNvrl7WVW",
- "outputId": "f22b7e2c-2372-4032-fefc-037a4f4d45c7"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "Colab notebook detected. To show errors in colab notebook, set debug=True in launch()\n",
- "Running on public URL: https://91a238021b8734d96f.gradio.live\n",
- "\n",
- "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
- ]
- },
- {
- "output_type": "display_data",
- "data": {
- "text/plain": [
- ""
- ],
- "text/html": [
- ""
- ]
- },
- "metadata": {}
- },
- {
- "output_type": "execute_result",
- "data": {
- "text/plain": []
- },
- "metadata": {},
- "execution_count": 38
- }
- ],
- "source": [
- "def greet(query):\n",
- "\n",
- " answer,sources,evals = get_response_from_query(db,query,2)\n",
- " return answer,sources,evals\n",
- "examples = [\n",
- " [\"How to be happy\"],\n",
- " [\"Climate Change Challenges in Europe\"],\n",
- " [\"Philosophy in the world of Minimalism\"],\n",
- " [\"Hate Speech vs Freedom of Speech\"],\n",
- " [\"Articles by Noam Chomsky on US Politics\"],\n",
- " [\"The importance of values and reflection\"]\n",
- " ]\n",
- "demo = gr.Interface(fn=greet, title=\"cicero-semantic-search\", inputs=\"text\",\n",
- " outputs=[gr.components.Textbox(lines=3, label=\"Response\"),\n",
- " gr.components.Textbox(lines=3, label=\"Source\"),\n",
- " gr.components.Textbox(lines=3, label=\"Evaluation\")],\n",
- " examples=examples)\n",
- "\n",
- "demo.launch(share=True)\n",
- "\n",
- "\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {
- "id": "UnjSpVxc7WVW",
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "outputId": "3e8b0fe4-de94-4cfb-d6f4-3d4f5b10ad41"
- },
- "outputs": [
- {
- "output_type": "stream",
- "name": "stdout",
- "text": [
- "Loaded as API: https://91a238021b8734d96f.gradio.live/ ✔\n",
- "(\"Based on the provided articles, the concerns of Democrats for the 2024 Senate seem to revolve around the challenging electoral map that they will face. The articles mention that even with an additional senator going into 2023, the 2024 map is still unfavorable for Democrats, making it difficult for them to keep the Senate for years to come. The party's prospects may rely on limiting the damage in 2024 to have a chance of regaining the Senate in 2026 or 2028. However, a bad outcome in 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.\\n\\nIn summary, the concerns of Democrats for the 2024 Senate primarily stem from the unfavorable electoral map and the potential long-term implications if they are unable to limit the damage in that election.\", \"[Document(page_content='Even with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0}), Document(page_content='Even with an additional senator going into 2023, the 2024 map is still so bad for Democrats that keeping the Senate for years to come will be a fairly tough order. The party’s prospects might rest more upon limiting the damage in 2024 so that it has a chance to regain the Senate in 2026 or 2028. But a bad 2024 could make it very difficult for Democrats to regain the Senate before 2030 or 2032.', metadata={'source': 'Are The Democrats Screwed In The Senate After 2024?', 'row': 0})]\", 'Yes, the response is faithful to the given context. The response accurately reflects the concerns of Democrats for the 2024 Senate, mentioning the unfavorable electoral map and the potential long-term implications if they are unable to limit the damage in that election. The response also includes similar language and structure as the provided articles.')\n"
- ]
- }
- ],
- "source": [
- "from gradio_client import Client\n",
- "\n",
- "client = Client(\"https://91a238021b8734d96f.gradio.live/\")\n",
- "result = client.predict(\n",
- "\t\t\"Can you tell me about the concerns of Democrats for 2024 Senate\",\t# str in 'query' Textbox component\n",
- "\t\tapi_name=\"/predict\"\n",
- ")\n",
- "print(result)"
- ]
- },
- {
- "cell_type": "code",
- "source": [],
- "metadata": {
- "id": "KcuKWqwj_AgQ"
- },
- "execution_count": null,
- "outputs": []
- }
- ],
- "metadata": {
- "accelerator": "GPU",
- "colab": {
- "provenance": []
- },
- "environment": {
- "kernel": "python3",
- "name": "pytorch-gpu.1-13.m108",
- "type": "gcloud",
- "uri": "gcr.io/deeplearning-platform-release/pytorch-gpu.1-13:m108"
- },
- "gpuClass": "standard",
- "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.10"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 0
-}
\ No newline at end of file