Spaces:
Build error
Build error
File size: 139,049 Bytes
fdd8012 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 |
{
"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",
" <div id=\"df-7017ff2e-f2a2-4b31-b909-64ce1b83cc12\" class=\"colab-df-container\">\n",
" <div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>_id</th>\n",
" <th>title</th>\n",
" <th>author</th>\n",
" <th>description</th>\n",
" <th>publish_date</th>\n",
" <th>full_text</th>\n",
" <th>url</th>\n",
" <th>categories</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>63927168098523fa9d5ef047</td>\n",
" <td>Are The Democrats Screwed In The Senate After ...</td>\n",
" <td>Nate Silver</td>\n",
" <td>\\nAre The Democrats Screwed In The Senate Afte...</td>\n",
" <td>1.670516e+12</td>\n",
" <td>\\n\\n\\n\\n2028 Election\\nAre The Democrats Screw...</td>\n",
" <td>https://fivethirtyeight.com/features/democrats...</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>652b21ec754471a9795c291a</td>\n",
" <td>Beyond the Narrative</td>\n",
" <td>Sam Freedman</td>\n",
" <td>NaN</td>\n",
" <td>1.697272e+12</td>\n",
" <td>We are told before every party conference that...</td>\n",
" <td>https://samf.substack.com/p/beyond-the-narrative</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>6529cfaff59ed61396db838c</td>\n",
" <td>Ballot Measures: A Preview</td>\n",
" <td>Walter Olson</td>\n",
" <td>NaN</td>\n",
" <td>1.697227e+12</td>\n",
" <td>Walter Olson Voters will go to the polls soon...</td>\n",
" <td>https://www.cato.org/blog/ballot-measures-preview</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>6529d030f59ed61396db8398</td>\n",
" <td>Trump’s Only Real Worldview Is Pettiness</td>\n",
" <td>David A. Graham</td>\n",
" <td>NaN</td>\n",
" <td>1.697214e+12</td>\n",
" <td>Let no one say that Donald Trump has lost his ...</td>\n",
" <td>tag:theatlantic.com,2023:50-675637</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>6529d072f59ed61396db839e</td>\n",
" <td>The COVID Bailout of State and Local Governmen...</td>\n",
" <td>Eric Boehm</td>\n",
" <td>NaN</td>\n",
" <td>1.697212e+12</td>\n",
" <td>Two years after Congress authorized a h...</td>\n",
" <td>https://reason.com/2023/10/13/the-covid-bailou...</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>\n",
" <div class=\"colab-df-buttons\">\n",
"\n",
" <div class=\"colab-df-container\">\n",
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-7017ff2e-f2a2-4b31-b909-64ce1b83cc12')\"\n",
" title=\"Convert this dataframe to an interactive table.\"\n",
" style=\"display:none;\">\n",
"\n",
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
" </svg>\n",
" </button>\n",
"\n",
" <style>\n",
" .colab-df-container {\n",
" display:flex;\n",
" gap: 12px;\n",
" }\n",
"\n",
" .colab-df-convert {\n",
" background-color: #E8F0FE;\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: #1967D2;\n",
" height: 32px;\n",
" padding: 0 0 0 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-convert:hover {\n",
" background-color: #E2EBFA;\n",
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: #174EA6;\n",
" }\n",
"\n",
" .colab-df-buttons div {\n",
" margin-bottom: 4px;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert {\n",
" background-color: #3B4455;\n",
" fill: #D2E3FC;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert:hover {\n",
" background-color: #434B5C;\n",
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
" fill: #FFFFFF;\n",
" }\n",
" </style>\n",
"\n",
" <script>\n",
" const buttonEl =\n",
" document.querySelector('#df-7017ff2e-f2a2-4b31-b909-64ce1b83cc12 button.colab-df-convert');\n",
" buttonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
"\n",
" async function convertToInteractive(key) {\n",
" const element = document.querySelector('#df-7017ff2e-f2a2-4b31-b909-64ce1b83cc12');\n",
" const dataTable =\n",
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
" [key], {});\n",
" if (!dataTable) return;\n",
"\n",
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
" + ' to learn more about interactive tables.';\n",
" element.innerHTML = '';\n",
" dataTable['output_type'] = 'display_data';\n",
" await google.colab.output.renderOutput(dataTable, element);\n",
" const docLink = document.createElement('div');\n",
" docLink.innerHTML = docLinkHtml;\n",
" element.appendChild(docLink);\n",
" }\n",
" </script>\n",
" </div>\n",
"\n",
"\n",
"<div id=\"df-34e447ed-e678-4955-984c-06d42221f5ad\">\n",
" <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-34e447ed-e678-4955-984c-06d42221f5ad')\"\n",
" title=\"Suggest charts\"\n",
" style=\"display:none;\">\n",
"\n",
"<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
" width=\"24px\">\n",
" <g>\n",
" <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
" </g>\n",
"</svg>\n",
" </button>\n",
"\n",
"<style>\n",
" .colab-df-quickchart {\n",
" --bg-color: #E8F0FE;\n",
" --fill-color: #1967D2;\n",
" --hover-bg-color: #E2EBFA;\n",
" --hover-fill-color: #174EA6;\n",
" --disabled-fill-color: #AAA;\n",
" --disabled-bg-color: #DDD;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-quickchart {\n",
" --bg-color: #3B4455;\n",
" --fill-color: #D2E3FC;\n",
" --hover-bg-color: #434B5C;\n",
" --hover-fill-color: #FFFFFF;\n",
" --disabled-bg-color: #3B4455;\n",
" --disabled-fill-color: #666;\n",
" }\n",
"\n",
" .colab-df-quickchart {\n",
" background-color: var(--bg-color);\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: var(--fill-color);\n",
" height: 32px;\n",
" padding: 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-quickchart:hover {\n",
" background-color: var(--hover-bg-color);\n",
" box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: var(--button-hover-fill-color);\n",
" }\n",
"\n",
" .colab-df-quickchart-complete:disabled,\n",
" .colab-df-quickchart-complete:disabled:hover {\n",
" background-color: var(--disabled-bg-color);\n",
" fill: var(--disabled-fill-color);\n",
" box-shadow: none;\n",
" }\n",
"\n",
" .colab-df-spinner {\n",
" border: 2px solid var(--fill-color);\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" animation:\n",
" spin 1s steps(1) infinite;\n",
" }\n",
"\n",
" @keyframes spin {\n",
" 0% {\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" border-left-color: var(--fill-color);\n",
" }\n",
" 20% {\n",
" border-color: transparent;\n",
" border-left-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" }\n",
" 30% {\n",
" border-color: transparent;\n",
" border-left-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" border-right-color: var(--fill-color);\n",
" }\n",
" 40% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" }\n",
" 60% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" }\n",
" 80% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" border-bottom-color: var(--fill-color);\n",
" }\n",
" 90% {\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" }\n",
" }\n",
"</style>\n",
"\n",
" <script>\n",
" async function quickchart(key) {\n",
" const quickchartButtonEl =\n",
" document.querySelector('#' + key + ' button');\n",
" quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n",
" quickchartButtonEl.classList.add('colab-df-spinner');\n",
" try {\n",
" const charts = await google.colab.kernel.invokeFunction(\n",
" 'suggestCharts', [key], {});\n",
" } catch (error) {\n",
" console.error('Error during call to suggestCharts:', error);\n",
" }\n",
" quickchartButtonEl.classList.remove('colab-df-spinner');\n",
" quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
" }\n",
" (() => {\n",
" let quickchartButtonEl =\n",
" document.querySelector('#df-34e447ed-e678-4955-984c-06d42221f5ad button');\n",
" quickchartButtonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
" })();\n",
" </script>\n",
"</div>\n",
"\n",
" </div>\n",
" </div>\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",
" <div id=\"df-e0435ba1-01e3-4008-9219-1accd86c5d0a\" class=\"colab-df-container\">\n",
" <div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>_id</th>\n",
" <th>title</th>\n",
" <th>author</th>\n",
" <th>description</th>\n",
" <th>publish_date</th>\n",
" <th>full_text</th>\n",
" <th>url</th>\n",
" <th>categories</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>63927168098523fa9d5ef047</td>\n",
" <td>Are The Democrats Screwed In The Senate After ...</td>\n",
" <td>Nate Silver</td>\n",
" <td>\\nAre The Democrats Screwed In The Senate Afte...</td>\n",
" <td>1.670516e+12</td>\n",
" <td>\\n\\n\\n\\n2028 Election\\nAre The Democrats Screw...</td>\n",
" <td>https://fivethirtyeight.com/features/democrats...</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>652b21ec754471a9795c291a</td>\n",
" <td>Beyond the Narrative</td>\n",
" <td>Sam Freedman</td>\n",
" <td>NaN</td>\n",
" <td>1.697272e+12</td>\n",
" <td>We are told before every party conference that...</td>\n",
" <td>https://samf.substack.com/p/beyond-the-narrative</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>6529cfaff59ed61396db838c</td>\n",
" <td>Ballot Measures: A Preview</td>\n",
" <td>Walter Olson</td>\n",
" <td>NaN</td>\n",
" <td>1.697227e+12</td>\n",
" <td>Walter Olson Voters will go to the polls soon...</td>\n",
" <td>https://www.cato.org/blog/ballot-measures-preview</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>6529d030f59ed61396db8398</td>\n",
" <td>Trump’s Only Real Worldview Is Pettiness</td>\n",
" <td>David A. Graham</td>\n",
" <td>NaN</td>\n",
" <td>1.697214e+12</td>\n",
" <td>Let no one say that Donald Trump has lost his ...</td>\n",
" <td>tag:theatlantic.com,2023:50-675637</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>6529d072f59ed61396db839e</td>\n",
" <td>The COVID Bailout of State and Local Governmen...</td>\n",
" <td>Eric Boehm</td>\n",
" <td>NaN</td>\n",
" <td>1.697212e+12</td>\n",
" <td>Two years after Congress authorized a h...</td>\n",
" <td>https://reason.com/2023/10/13/the-covid-bailou...</td>\n",
" <td>['news']</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>\n",
" <div class=\"colab-df-buttons\">\n",
"\n",
" <div class=\"colab-df-container\">\n",
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-e0435ba1-01e3-4008-9219-1accd86c5d0a')\"\n",
" title=\"Convert this dataframe to an interactive table.\"\n",
" style=\"display:none;\">\n",
"\n",
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
" </svg>\n",
" </button>\n",
"\n",
" <style>\n",
" .colab-df-container {\n",
" display:flex;\n",
" gap: 12px;\n",
" }\n",
"\n",
" .colab-df-convert {\n",
" background-color: #E8F0FE;\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: #1967D2;\n",
" height: 32px;\n",
" padding: 0 0 0 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-convert:hover {\n",
" background-color: #E2EBFA;\n",
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: #174EA6;\n",
" }\n",
"\n",
" .colab-df-buttons div {\n",
" margin-bottom: 4px;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert {\n",
" background-color: #3B4455;\n",
" fill: #D2E3FC;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert:hover {\n",
" background-color: #434B5C;\n",
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
" fill: #FFFFFF;\n",
" }\n",
" </style>\n",
"\n",
" <script>\n",
" const buttonEl =\n",
" document.querySelector('#df-e0435ba1-01e3-4008-9219-1accd86c5d0a button.colab-df-convert');\n",
" buttonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
"\n",
" async function convertToInteractive(key) {\n",
" const element = document.querySelector('#df-e0435ba1-01e3-4008-9219-1accd86c5d0a');\n",
" const dataTable =\n",
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
" [key], {});\n",
" if (!dataTable) return;\n",
"\n",
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
" + ' to learn more about interactive tables.';\n",
" element.innerHTML = '';\n",
" dataTable['output_type'] = 'display_data';\n",
" await google.colab.output.renderOutput(dataTable, element);\n",
" const docLink = document.createElement('div');\n",
" docLink.innerHTML = docLinkHtml;\n",
" element.appendChild(docLink);\n",
" }\n",
" </script>\n",
" </div>\n",
"\n",
"\n",
"<div id=\"df-67a834e8-3806-4d57-822a-370719726ac5\">\n",
" <button class=\"colab-df-quickchart\" onclick=\"quickchart('df-67a834e8-3806-4d57-822a-370719726ac5')\"\n",
" title=\"Suggest charts\"\n",
" style=\"display:none;\">\n",
"\n",
"<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
" width=\"24px\">\n",
" <g>\n",
" <path d=\"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z\"/>\n",
" </g>\n",
"</svg>\n",
" </button>\n",
"\n",
"<style>\n",
" .colab-df-quickchart {\n",
" --bg-color: #E8F0FE;\n",
" --fill-color: #1967D2;\n",
" --hover-bg-color: #E2EBFA;\n",
" --hover-fill-color: #174EA6;\n",
" --disabled-fill-color: #AAA;\n",
" --disabled-bg-color: #DDD;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-quickchart {\n",
" --bg-color: #3B4455;\n",
" --fill-color: #D2E3FC;\n",
" --hover-bg-color: #434B5C;\n",
" --hover-fill-color: #FFFFFF;\n",
" --disabled-bg-color: #3B4455;\n",
" --disabled-fill-color: #666;\n",
" }\n",
"\n",
" .colab-df-quickchart {\n",
" background-color: var(--bg-color);\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: var(--fill-color);\n",
" height: 32px;\n",
" padding: 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-quickchart:hover {\n",
" background-color: var(--hover-bg-color);\n",
" box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: var(--button-hover-fill-color);\n",
" }\n",
"\n",
" .colab-df-quickchart-complete:disabled,\n",
" .colab-df-quickchart-complete:disabled:hover {\n",
" background-color: var(--disabled-bg-color);\n",
" fill: var(--disabled-fill-color);\n",
" box-shadow: none;\n",
" }\n",
"\n",
" .colab-df-spinner {\n",
" border: 2px solid var(--fill-color);\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" animation:\n",
" spin 1s steps(1) infinite;\n",
" }\n",
"\n",
" @keyframes spin {\n",
" 0% {\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" border-left-color: var(--fill-color);\n",
" }\n",
" 20% {\n",
" border-color: transparent;\n",
" border-left-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" }\n",
" 30% {\n",
" border-color: transparent;\n",
" border-left-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" border-right-color: var(--fill-color);\n",
" }\n",
" 40% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" border-top-color: var(--fill-color);\n",
" }\n",
" 60% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" }\n",
" 80% {\n",
" border-color: transparent;\n",
" border-right-color: var(--fill-color);\n",
" border-bottom-color: var(--fill-color);\n",
" }\n",
" 90% {\n",
" border-color: transparent;\n",
" border-bottom-color: var(--fill-color);\n",
" }\n",
" }\n",
"</style>\n",
"\n",
" <script>\n",
" async function quickchart(key) {\n",
" const quickchartButtonEl =\n",
" document.querySelector('#' + key + ' button');\n",
" quickchartButtonEl.disabled = true; // To prevent multiple clicks.\n",
" quickchartButtonEl.classList.add('colab-df-spinner');\n",
" try {\n",
" const charts = await google.colab.kernel.invokeFunction(\n",
" 'suggestCharts', [key], {});\n",
" } catch (error) {\n",
" console.error('Error during call to suggestCharts:', error);\n",
" }\n",
" quickchartButtonEl.classList.remove('colab-df-spinner');\n",
" quickchartButtonEl.classList.add('colab-df-quickchart-complete');\n",
" }\n",
" (() => {\n",
" let quickchartButtonEl =\n",
" document.querySelector('#df-67a834e8-3806-4d57-822a-370719726ac5 button');\n",
" quickchartButtonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
" })();\n",
" </script>\n",
"</div>\n",
"\n",
" </div>\n",
" </div>\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": [
"<IPython.core.display.HTML object>"
],
"text/html": [
"<div><iframe src=\"https://91a238021b8734d96f.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
]
},
"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
} |