From dc1d937c3787d938d9fb175a06e1a6e647a85e49 Mon Sep 17 00:00:00 2001 From: Erick Friis Date: Thu, 4 Apr 2024 18:14:32 -0700 Subject: [PATCH] more standardize (#158) --- .github/scripts/check_diff.py | 48 + .github/scripts/get_min_versions.py | 65 ++ .github/workflows/_codespell.yml | 39 + .../workflows/_compile_integration_test.yml | 57 ++ .github/workflows/_lint.yml | 102 ++ .github/workflows/_test.yml | 58 ++ .github/workflows/check_diffs.yml | 89 ++ .github/workflows/prebuild.yml | 47 - LICENSE | 2 +- README.md | 42 +- docs/state_of_the_union.txt | 723 -------------- docs/vectorstores.ipynb | 921 ------------------ libs/weaviate/LICENSE | 21 + Makefile => libs/weaviate/Makefile | 0 libs/weaviate/README.md | 41 + .../weaviate/langchain_weaviate}/__init__.py | 0 .../weaviate/langchain_weaviate}/_math.py | 0 .../weaviate/langchain_weaviate}/py.typed | 0 .../weaviate/langchain_weaviate}/utils.py | 0 .../langchain_weaviate}/vectorstores.py | 0 poetry.lock => libs/weaviate/poetry.lock | 0 .../weaviate/pyproject.toml | 0 .../weaviate/scripts}/check_imports.py | 0 .../weaviate/scripts}/check_pydantic.sh | 0 .../weaviate/scripts}/lint_imports.sh | 0 {tests => libs/weaviate/tests}/__init__.py | 0 .../weaviate/tests}/docker-compose.yml | 0 .../tests}/integration_tests/__init__.py | 0 .../tests}/integration_tests/test_compile.py | 0 .../weaviate/tests}/unit_tests/__init__.py | 0 .../weaviate/tests}/unit_tests/fake_docs.json | 0 .../tests}/unit_tests/fake_embeddings.py | 0 .../weaviate/tests}/unit_tests/test__math.py | 0 .../test_vectorstores_integration.py | 0 .../unit_tests/test_vectorstores_unit.py | 0 release-please-config.json | 12 - 36 files changed, 524 insertions(+), 1743 deletions(-) create mode 100644 .github/scripts/check_diff.py create mode 100644 .github/scripts/get_min_versions.py create mode 100644 .github/workflows/_codespell.yml create mode 100644 .github/workflows/_compile_integration_test.yml create mode 100644 .github/workflows/_lint.yml create mode 100644 .github/workflows/_test.yml create mode 100644 .github/workflows/check_diffs.yml delete mode 100644 .github/workflows/prebuild.yml delete mode 100644 docs/state_of_the_union.txt delete mode 100644 docs/vectorstores.ipynb create mode 100644 libs/weaviate/LICENSE rename Makefile => libs/weaviate/Makefile (100%) create mode 100644 libs/weaviate/README.md rename {langchain_weaviate => libs/weaviate/langchain_weaviate}/__init__.py (100%) rename {langchain_weaviate => libs/weaviate/langchain_weaviate}/_math.py (100%) rename {langchain_weaviate => libs/weaviate/langchain_weaviate}/py.typed (100%) rename {langchain_weaviate => libs/weaviate/langchain_weaviate}/utils.py (100%) rename {langchain_weaviate => libs/weaviate/langchain_weaviate}/vectorstores.py (100%) rename poetry.lock => libs/weaviate/poetry.lock (100%) rename pyproject.toml => libs/weaviate/pyproject.toml (100%) rename {scripts => libs/weaviate/scripts}/check_imports.py (100%) rename {scripts => libs/weaviate/scripts}/check_pydantic.sh (100%) rename {scripts => libs/weaviate/scripts}/lint_imports.sh (100%) rename {tests => libs/weaviate/tests}/__init__.py (100%) rename {tests => libs/weaviate/tests}/docker-compose.yml (100%) rename {tests => libs/weaviate/tests}/integration_tests/__init__.py (100%) rename {tests => libs/weaviate/tests}/integration_tests/test_compile.py (100%) rename {tests => libs/weaviate/tests}/unit_tests/__init__.py (100%) rename {tests => libs/weaviate/tests}/unit_tests/fake_docs.json (100%) rename {tests => libs/weaviate/tests}/unit_tests/fake_embeddings.py (100%) rename {tests => libs/weaviate/tests}/unit_tests/test__math.py (100%) rename {tests => libs/weaviate/tests}/unit_tests/test_vectorstores_integration.py (100%) rename {tests => libs/weaviate/tests}/unit_tests/test_vectorstores_unit.py (100%) delete mode 100644 release-please-config.json diff --git a/.github/scripts/check_diff.py b/.github/scripts/check_diff.py new file mode 100644 index 0000000..72bfd3c --- /dev/null +++ b/.github/scripts/check_diff.py @@ -0,0 +1,48 @@ +import json +import sys +from typing import Dict + +LIB_DIRS = ["libs/weaviate"] + +if __name__ == "__main__": + files = sys.argv[1:] + + dirs_to_run: Dict[str, set] = { + "lint": set(), + "test": set(), + } + + if len(files) == 300: + # max diff length is 300 files - there are likely files missing + raise ValueError("Max diff reached. Please manually run CI on changed libs.") + + for file in files: + if any( + file.startswith(dir_) + for dir_ in ( + ".github/workflows", + ".github/tools", + ".github/actions", + ".github/scripts/check_diff.py", + ) + ): + # add all LANGCHAIN_DIRS for infra changes + dirs_to_run["test"].update(LIB_DIRS) + + if any(file.startswith(dir_) for dir_ in LIB_DIRS): + for dir_ in LIB_DIRS: + if file.startswith(dir_): + dirs_to_run["test"].add(dir_) + elif file.startswith("libs/"): + raise ValueError( + f"Unknown lib: {file}. check_diff.py likely needs " + "an update for this new library!" + ) + + outputs = { + "dirs-to-lint": list(dirs_to_run["lint"] | dirs_to_run["test"]), + "dirs-to-test": list(dirs_to_run["test"]), + } + for key, value in outputs.items(): + json_output = json.dumps(value) + print(f"{key}={json_output}") # noqa: T201 diff --git a/.github/scripts/get_min_versions.py b/.github/scripts/get_min_versions.py new file mode 100644 index 0000000..46e74c9 --- /dev/null +++ b/.github/scripts/get_min_versions.py @@ -0,0 +1,65 @@ +import sys + +import tomllib +from packaging.version import parse as parse_version +import re + +MIN_VERSION_LIBS = ["langchain-core"] + + +def get_min_version(version: str) -> str: + # case ^x.x.x + _match = re.match(r"^\^(\d+(?:\.\d+){0,2})$", version) + if _match: + return _match.group(1) + + # case >=x.x.x,=(\d+(?:\.\d+){0,2}),<(\d+(?:\.\d+){0,2})$", version) + if _match: + _min = _match.group(1) + _max = _match.group(2) + assert parse_version(_min) < parse_version(_max) + return _min + + # case x.x.x + _match = re.match(r"^(\d+(?:\.\d+){0,2})$", version) + if _match: + return _match.group(1) + + raise ValueError(f"Unrecognized version format: {version}") + + +def get_min_version_from_toml(toml_path: str): + # Parse the TOML file + with open(toml_path, "rb") as file: + toml_data = tomllib.load(file) + + # Get the dependencies from tool.poetry.dependencies + dependencies = toml_data["tool"]["poetry"]["dependencies"] + + # Initialize a dictionary to store the minimum versions + min_versions = {} + + # Iterate over the libs in MIN_VERSION_LIBS + for lib in MIN_VERSION_LIBS: + # Check if the lib is present in the dependencies + if lib in dependencies: + # Get the version string + version_string = dependencies[lib] + + # Use parse_version to get the minimum supported version from version_string + min_version = get_min_version(version_string) + + # Store the minimum version in the min_versions dictionary + min_versions[lib] = min_version + + return min_versions + + +# Get the TOML file path from the command line argument +toml_file = sys.argv[1] + +# Call the function to get the minimum versions +min_versions = get_min_version_from_toml(toml_file) + +print(" ".join([f"{lib}=={version}" for lib, version in min_versions.items()])) diff --git a/.github/workflows/_codespell.yml b/.github/workflows/_codespell.yml new file mode 100644 index 0000000..fc81ef7 --- /dev/null +++ b/.github/workflows/_codespell.yml @@ -0,0 +1,39 @@ +--- +name: make spell_check + +on: + workflow_call: + inputs: + working-directory: + required: true + type: string + description: "From which folder this pipeline executes" + +permissions: + contents: read + +jobs: + codespell: + name: (Check for spelling errors) + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Dependencies + run: | + pip install toml + + - name: Extract Ignore Words List + working-directory: ${{ inputs.working-directory }} + run: | + # Use a Python script to extract the ignore words list from pyproject.toml + python ../../.github/workflows/extract_ignored_words_list.py + id: extract_ignore_words + + - name: Codespell + uses: codespell-project/actions-codespell@v2 + with: + skip: guide_imports.json + ignore_words_list: ${{ steps.extract_ignore_words.outputs.ignore_words_list }} diff --git a/.github/workflows/_compile_integration_test.yml b/.github/workflows/_compile_integration_test.yml new file mode 100644 index 0000000..d8b5b9b --- /dev/null +++ b/.github/workflows/_compile_integration_test.yml @@ -0,0 +1,57 @@ +name: compile-integration-test + +on: + workflow_call: + inputs: + working-directory: + required: true + type: string + description: "From which folder this pipeline executes" + +env: + POETRY_VERSION: "1.7.1" + +jobs: + build: + defaults: + run: + working-directory: ${{ inputs.working-directory }} + runs-on: ubuntu-latest + strategy: + matrix: + python-version: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + name: "poetry run pytest -m compile tests/integration_tests #${{ matrix.python-version }}" + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + Poetry ${{ env.POETRY_VERSION }} + uses: "./.github/actions/poetry_setup" + with: + python-version: ${{ matrix.python-version }} + poetry-version: ${{ env.POETRY_VERSION }} + working-directory: ${{ inputs.working-directory }} + cache-key: compile-integration + + - name: Install integration dependencies + shell: bash + run: poetry install --with=test_integration,test + + - name: Check integration tests compile + shell: bash + run: poetry run pytest -m compile tests/integration_tests + + - name: Ensure the tests did not create any additional files + shell: bash + run: | + set -eu + + STATUS="$(git status)" + echo "$STATUS" + + # grep will exit non-zero if the target message isn't found, + # and `set -e` above will cause the step to fail. + echo "$STATUS" | grep 'nothing to commit, working tree clean' diff --git a/.github/workflows/_lint.yml b/.github/workflows/_lint.yml new file mode 100644 index 0000000..78baea7 --- /dev/null +++ b/.github/workflows/_lint.yml @@ -0,0 +1,102 @@ +name: lint + +on: + workflow_call: + inputs: + working-directory: + required: true + type: string + description: "From which folder this pipeline executes" + +env: + POETRY_VERSION: "1.7.1" + WORKDIR: ${{ inputs.working-directory == '' && '.' || inputs.working-directory }} + + # This env var allows us to get inline annotations when ruff has complaints. + RUFF_OUTPUT_FORMAT: github + +jobs: + build: + name: "make lint #${{ matrix.python-version }}" + runs-on: ubuntu-latest + strategy: + matrix: + # Only lint on the min and max supported Python versions. + # It's extremely unlikely that there's a lint issue on any version in between + # that doesn't show up on the min or max versions. + # + # GitHub rate-limits how many jobs can be running at any one time. + # Starting new jobs is also relatively slow, + # so linting on fewer versions makes CI faster. + python-version: + - "3.8" + - "3.11" + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + Poetry ${{ env.POETRY_VERSION }} + uses: "./.github/actions/poetry_setup" + with: + python-version: ${{ matrix.python-version }} + poetry-version: ${{ env.POETRY_VERSION }} + working-directory: ${{ inputs.working-directory }} + cache-key: lint-with-extras + + - name: Check Poetry File + shell: bash + working-directory: ${{ inputs.working-directory }} + run: | + poetry check + + - name: Check lock file + shell: bash + working-directory: ${{ inputs.working-directory }} + run: | + poetry lock --check + + - name: Install dependencies + # Also installs dev/lint/test/typing dependencies, to ensure we have + # type hints for as many of our libraries as possible. + # This helps catch errors that require dependencies to be spotted, for example: + # https://github.com/langchain-ai/langchain/pull/10249/files#diff-935185cd488d015f026dcd9e19616ff62863e8cde8c0bee70318d3ccbca98341 + # + # If you change this configuration, make sure to change the `cache-key` + # in the `poetry_setup` action above to stop using the old cache. + # It doesn't matter how you change it, any change will cause a cache-bust. + working-directory: ${{ inputs.working-directory }} + run: | + poetry install --with lint,typing + + - name: Get .mypy_cache to speed up mypy + uses: actions/cache@v4 + env: + SEGMENT_DOWNLOAD_TIMEOUT_MIN: "2" + with: + path: | + ${{ env.WORKDIR }}/.mypy_cache + key: mypy-lint-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }}-${{ inputs.working-directory }}-${{ hashFiles(format('{0}/poetry.lock', inputs.working-directory)) }} + + + - name: Analysing the code with our lint + working-directory: ${{ inputs.working-directory }} + run: | + make lint_package + + - name: Install unit+integration test dependencies + working-directory: ${{ inputs.working-directory }} + run: | + poetry install --with test,test_integration + + - name: Get .mypy_cache_test to speed up mypy + uses: actions/cache@v4 + env: + SEGMENT_DOWNLOAD_TIMEOUT_MIN: "2" + with: + path: | + ${{ env.WORKDIR }}/.mypy_cache_test + key: mypy-test-${{ runner.os }}-${{ runner.arch }}-py${{ matrix.python-version }}-${{ inputs.working-directory }}-${{ hashFiles(format('{0}/poetry.lock', inputs.working-directory)) }} + + - name: Analysing the code with our lint + working-directory: ${{ inputs.working-directory }} + run: | + make lint_tests diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml new file mode 100644 index 0000000..8f2ace4 --- /dev/null +++ b/.github/workflows/_test.yml @@ -0,0 +1,58 @@ +name: test + +on: + workflow_call: + inputs: + working-directory: + required: true + type: string + description: "From which folder this pipeline executes" + +env: + POETRY_VERSION: "1.7.1" + +jobs: + build: + defaults: + run: + working-directory: ${{ inputs.working-directory }} + runs-on: ubuntu-latest + strategy: + matrix: + python-version: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + name: "make test #${{ matrix.python-version }}" + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + Poetry ${{ env.POETRY_VERSION }} + uses: "./.github/actions/poetry_setup" + with: + python-version: ${{ matrix.python-version }} + poetry-version: ${{ env.POETRY_VERSION }} + working-directory: ${{ inputs.working-directory }} + cache-key: core + + - name: Install dependencies + shell: bash + run: poetry install --with test + + - name: Run core tests + shell: bash + run: | + make test + + - name: Ensure the tests did not create any additional files + shell: bash + run: | + set -eu + + STATUS="$(git status)" + echo "$STATUS" + + # grep will exit non-zero if the target message isn't found, + # and `set -e` above will cause the step to fail. + echo "$STATUS" | grep 'nothing to commit, working tree clean' diff --git a/.github/workflows/check_diffs.yml b/.github/workflows/check_diffs.yml new file mode 100644 index 0000000..b6f4891 --- /dev/null +++ b/.github/workflows/check_diffs.yml @@ -0,0 +1,89 @@ +--- +name: CI + +on: + push: + branches: [main] + pull_request: + +# If another push to the same PR or branch happens while this workflow is still running, +# cancel the earlier run in favor of the next run. +# +# There's no point in testing an outdated version of the code. GitHub only allows +# a limited number of job runners to be active at the same time, so it's better to cancel +# pointless jobs early so that more useful jobs can run sooner. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + POETRY_VERSION: "1.7.1" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.10' + - id: files + uses: Ana06/get-changed-files@v2.2.0 + - id: set-matrix + run: | + python .github/scripts/check_diff.py ${{ steps.files.outputs.all }} >> $GITHUB_OUTPUT + outputs: + dirs-to-lint: ${{ steps.set-matrix.outputs.dirs-to-lint }} + dirs-to-test: ${{ steps.set-matrix.outputs.dirs-to-test }} + lint: + name: cd ${{ matrix.working-directory }} + needs: [ build ] + if: ${{ needs.build.outputs.dirs-to-lint != '[]' }} + strategy: + matrix: + working-directory: ${{ fromJson(needs.build.outputs.dirs-to-lint) }} + uses: ./.github/workflows/_lint.yml + with: + working-directory: ${{ matrix.working-directory }} + secrets: inherit + + test: + name: cd ${{ matrix.working-directory }} + needs: [ build ] + if: ${{ needs.build.outputs.dirs-to-test != '[]' }} + strategy: + matrix: + working-directory: ${{ fromJson(needs.build.outputs.dirs-to-test) }} + uses: ./.github/workflows/_test.yml + with: + working-directory: ${{ matrix.working-directory }} + secrets: inherit + + compile-integration-tests: + name: cd ${{ matrix.working-directory }} + needs: [ build ] + if: ${{ needs.build.outputs.dirs-to-test != '[]' }} + strategy: + matrix: + working-directory: ${{ fromJson(needs.build.outputs.dirs-to-test) }} + uses: ./.github/workflows/_compile_integration_test.yml + with: + working-directory: ${{ matrix.working-directory }} + secrets: inherit + ci_success: + name: "CI Success" + needs: [build, lint, test, compile-integration-tests] + if: | + always() + runs-on: ubuntu-latest + env: + JOBS_JSON: ${{ toJSON(needs) }} + RESULTS_JSON: ${{ toJSON(needs.*.result) }} + EXIT_CODE: ${{!contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && '0' || '1'}} + steps: + - name: "CI Success" + run: | + echo $JOBS_JSON + echo $RESULTS_JSON + echo "Exiting with $EXIT_CODE" + exit $EXIT_CODE diff --git a/.github/workflows/prebuild.yml b/.github/workflows/prebuild.yml deleted file mode 100644 index 4e1c46f..0000000 --- a/.github/workflows/prebuild.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Pre-build checks - -on: - push: - branches: [ main ] - pull_request: - branches: [ main ] - -jobs: - lint_check: - name: Lint the code - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v3 - - name: Build and run Dev Container task - uses: devcontainers/ci@v0.3 - with: - runCmd: | - poetry run ruff -v ./langchain_weaviate/ ./tests/ - - format_check: - name: Check code format - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v3 - - name: Build and run Dev Container task - uses: devcontainers/ci@v0.3 - with: - runCmd: | - poetry run ruff format -v --diff ./langchain_weaviate/ ./tests/ - - run_tests: - name: Run tests - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@v3 - - name: Build and run Dev Container task - uses: devcontainers/ci@v0.3 - with: - runCmd: | - poetry run pytest -n `nproc` \ - --cov=langchain_weaviate \ - --cov-report term-missing \ - --cov-fail-under=96.44 \ No newline at end of file diff --git a/LICENSE b/LICENSE index 426b650..fc0602f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 LangChain, Inc. +Copyright (c) 2024 LangChain, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index e8b177f..a0f70e3 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,5 @@ -# langchain-weaviate +# 🦜️🔗 LangChain Weaviate -## About +This repository contains 1 package with Weaviate integrations with LangChain: -This package contains the [Weaviate](https://github.com/weaviate/weaviate) integrations for [LangChain](https://github.com/langchain-ai/langchain). - -- **Weaviate** is an open source, AI-native vector database that helps developers create intuitive and reliable AI-powered applications. -- **LangChain** is a framework for developing applications powered by language models. - -Using this package, LangChain users can conveniently set Weaviate as their vector store to store and retrieve embeddings. - -## Requirements - -To use this package, you need to have a running Weaviate instance. - -Weaviate can be [deployed in many different ways](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate) such as in containerized environments, on Kubernetes, or in the cloud as a managed service, on-premises, or through a cloud provider such as AWS or Google Cloud. - -The deployment method to choose depends on your use case and infrastructure requirements. - -Two of the most common ways to deploy Weaviate are: -- [Docker Compose](https://weaviate.io/developers/weaviate/installation/docker-compose) -- [Weaviate Cloud Services (WCS)](https://console.weaviate.cloud) - -## Installation and Setup - -As an integration package, this assumes you have already installed LangChain. If not, please refer to the [LangChain installation guide](https://python.langchain.com/docs/get_started/installation). - -Then, install this package: - -```bash -pip install langchain-weaviate -``` - -## Usage - -Please see the included [Jupyter notebook](docs/vectorstores.ipynb) for an example of how to use this package. - -## Further resources - -- [LangChain documentation](https://python.langchain.com/docs) -- [Weaviate documentation](https://weaviate.io/developers/weaviate) +- [langchain-weaviate](https://pypi.org/project/langchain-weaviate/) integrates [Weaviate](https://weaviate.io/). diff --git a/docs/state_of_the_union.txt b/docs/state_of_the_union.txt deleted file mode 100644 index b453aac..0000000 --- a/docs/state_of_the_union.txt +++ /dev/null @@ -1,723 +0,0 @@ -Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. - -Last year COVID-19 kept us apart. This year we are finally together again. - -Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. - -With a duty to one another to the American people to the Constitution. - -And with an unwavering resolve that freedom will always triumph over tyranny. - -Six days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. - -He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. - -He met the Ukrainian people. - -From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. - -Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. - -In this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. - -Let each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. - -Please rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. - -Throughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos. - -They keep moving. - -And the costs and the threats to America and the world keep rising. - -That’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. - -The United States is a member along with 29 other nations. - -It matters. American diplomacy matters. American resolve matters. - -Putin’s latest attack on Ukraine was premeditated and unprovoked. - -He rejected repeated efforts at diplomacy. - -He thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. - -We prepared extensively and carefully. - -We spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. - -I spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. - -We countered Russia’s lies with truth. - -And now that he has acted the free world is holding him accountable. - -Along with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland. - -We are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. - -Together with our allies –we are right now enforcing powerful economic sanctions. - -We are cutting off Russia’s largest banks from the international financial system. - -Preventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund” worthless. - -We are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. - -Tonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. - -The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. - -We are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains. - -And tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. - -The Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. - -Together with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. - -We are giving more than $1 Billion in direct assistance to Ukraine. - -And we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering. - -Let me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine. - -Our forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west. - -For that purpose we’ve mobilized American ground forces, air squadrons, and ship deployments to protect NATO countries including Poland, Romania, Latvia, Lithuania, and Estonia. - -As I have made crystal clear the United States and our Allies will defend every inch of territory of NATO countries with the full force of our collective power. - -And we remain clear-eyed. The Ukrainians are fighting back with pure courage. But the next few days weeks, months, will be hard on them. - -Putin has unleashed violence and chaos. But while he may make gains on the battlefield – he will pay a continuing high price over the long run. - -And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. - -To all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. - -And I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. - -Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. - -America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. - -These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. - -But I want you to know that we are going to be okay. - -When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. - -While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly. - -We see the unity among leaders of nations and a more unified Europe a more unified West. And we see unity among the people who are gathering in cities in large crowds around the world even in Russia to demonstrate their support for Ukraine. - -In the battle between democracy and autocracy, democracies are rising to the moment, and the world is clearly choosing the side of peace and security. - -This is a real test. It’s going to take time. So let us continue to draw inspiration from the iron will of the Ukrainian people. - -To our fellow Ukrainian Americans who forge a deep bond that connects our two nations we stand with you. - -Putin may circle Kyiv with tanks, but he will never gain the hearts and souls of the Ukrainian people. - -He will never extinguish their love of freedom. He will never weaken the resolve of the free world. - -We meet tonight in an America that has lived through two of the hardest years this nation has ever faced. - -The pandemic has been punishing. - -And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. - -I understand. - -I remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. - -That’s why one of the first things I did as President was fight to pass the American Rescue Plan. - -Because people were hurting. We needed to act, and we did. - -Few pieces of legislation have done more in a critical moment in our history to lift us out of crisis. - -It fueled our efforts to vaccinate the nation and combat COVID-19. It delivered immediate economic relief for tens of millions of Americans. - -Helped put food on their table, keep a roof over their heads, and cut the cost of health insurance. - -And as my Dad used to say, it gave people a little breathing room. - -And unlike the $2 Trillion tax cut passed in the previous administration that benefitted the top 1% of Americans, the American Rescue Plan helped working people—and left no one behind. - -And it worked. It created jobs. Lots of jobs. - -In fact—our economy created over 6.5 Million new jobs just last year, more jobs created in one year -than ever before in the history of America. - -Our economy grew at a rate of 5.7% last year, the strongest growth in nearly 40 years, the first step in bringing fundamental change to an economy that hasn’t worked for the working people of this nation for too long. - -For the past 40 years we were told that if we gave tax breaks to those at the very top, the benefits would trickle down to everyone else. - -But that trickle-down theory led to weaker economic growth, lower wages, bigger deficits, and the widest gap between those at the top and everyone else in nearly a century. - -Vice President Harris and I ran for office with a new economic vision for America. - -Invest in America. Educate Americans. Grow the workforce. Build the economy from the bottom up -and the middle out, not from the top down. - -Because we know that when the middle class grows, the poor have a ladder up and the wealthy do very well. - -America used to have the best roads, bridges, and airports on Earth. - -Now our infrastructure is ranked 13th in the world. - -We won’t be able to compete for the jobs of the 21st Century if we don’t fix that. - -That’s why it was so important to pass the Bipartisan Infrastructure Law—the most sweeping investment to rebuild America in history. - -This was a bipartisan effort, and I want to thank the members of both parties who worked to make it happen. - -We’re done talking about infrastructure weeks. - -We’re going to have an infrastructure decade. - -It is going to transform America and put us on a path to win the economic competition of the 21st Century that we face with the rest of the world—particularly with China. - -As I’ve told Xi Jinping, it is never a good bet to bet against the American people. - -We’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America. - -And we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice. - -We’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities. - -4,000 projects have already been announced. - -And tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair. - -When we use taxpayer dollars to rebuild America – we are going to Buy American: buy American products to support American jobs. - -The federal government spends about $600 Billion a year to keep the country safe and secure. - -There’s been a law on the books for almost a century -to make sure taxpayers’ dollars support American jobs and businesses. - -Every Administration says they’ll do it, but we are actually doing it. - -We will buy American to make sure everything from the deck of an aircraft carrier to the steel on highway guardrails are made in America. - -But to compete for the best jobs of the future, we also need to level the playing field with China and other competitors. - -That’s why it is so important to pass the Bipartisan Innovation Act sitting in Congress that will make record investments in emerging technologies and American manufacturing. - -Let me give you one example of why it’s so important to pass it. - -If you travel 20 miles east of Columbus, Ohio, you’ll find 1,000 empty acres of land. - -It won’t look like much, but if you stop and look closely, you’ll see a “Field of dreams,” the ground on which America’s future will be built. - -This is where Intel, the American company that helped build Silicon Valley, is going to build its $20 billion semiconductor “mega site”. - -Up to eight state-of-the-art factories in one place. 10,000 new good-paying jobs. - -Some of the most sophisticated manufacturing in the world to make computer chips the size of a fingertip that power the world and our everyday lives. - -Smartphones. The Internet. Technology we have yet to invent. - -But that’s just the beginning. - -Intel’s CEO, Pat Gelsinger, who is here tonight, told me they are ready to increase their investment from -$20 billion to $100 billion. - -That would be one of the biggest investments in manufacturing in American history. - -And all they’re waiting for is for you to pass this bill. - -So let’s not wait any longer. Send it to my desk. I’ll sign it. - -And we will really take off. - -And Intel is not alone. - -There’s something happening in America. - -Just look around and you’ll see an amazing story. - -The rebirth of the pride that comes from stamping products “Made In America.” The revitalization of American manufacturing. - -Companies are choosing to build new factories here, when just a few years ago, they would have built them overseas. - -That’s what is happening. Ford is investing $11 billion to build electric vehicles, creating 11,000 jobs across the country. - -GM is making the largest investment in its history—$7 billion to build electric vehicles, creating 4,000 jobs in Michigan. - -All told, we created 369,000 new manufacturing jobs in America just last year. - -Powered by people I’ve met like JoJo Burgess, from generations of union steelworkers from Pittsburgh, who’s here with us tonight. - -As Ohio Senator Sherrod Brown says, “It’s time to bury the label “Rust Belt.” - -It’s time. - -But with all the bright spots in our economy, record job growth and higher wages, too many families are struggling to keep up with the bills. - -Inflation is robbing them of the gains they might otherwise feel. - -I get it. That’s why my top priority is getting prices under control. - -Look, our economy roared back faster than most predicted, but the pandemic meant that businesses had a hard time hiring enough workers to keep up production in their factories. - -The pandemic also disrupted global supply chains. - -When factories close, it takes longer to make goods and get them from the warehouse to the store, and prices go up. - -Look at cars. - -Last year, there weren’t enough semiconductors to make all the cars that people wanted to buy. - -And guess what, prices of automobiles went up. - -So—we have a choice. - -One way to fight inflation is to drive down wages and make Americans poorer. - -I have a better plan to fight inflation. - -Lower your costs, not your wages. - -Make more cars and semiconductors in America. - -More infrastructure and innovation in America. - -More goods moving faster and cheaper in America. - -More jobs where you can earn a good living in America. - -And instead of relying on foreign supply chains, let’s make it in America. - -Economists call it “increasing the productive capacity of our economy.” - -I call it building a better America. - -My plan to fight inflation will lower your costs and lower the deficit. - -17 Nobel laureates in economics say my plan will ease long-term inflationary pressures. Top business leaders and most Americans support my plan. And here’s the plan: - -First – cut the cost of prescription drugs. Just look at insulin. One in ten Americans has diabetes. In Virginia, I met a 13-year-old boy named Joshua Davis. - -He and his Dad both have Type 1 diabetes, which means they need insulin every day. Insulin costs about $10 a vial to make. - -But drug companies charge families like Joshua and his Dad up to 30 times more. I spoke with Joshua’s mom. - -Imagine what it’s like to look at your child who needs insulin and have no idea how you’re going to pay for it. - -What it does to your dignity, your ability to look your child in the eye, to be the parent you expect to be. - -Joshua is here with us tonight. Yesterday was his birthday. Happy birthday, buddy. - -For Joshua, and for the 200,000 other young people with Type 1 diabetes, let’s cap the cost of insulin at $35 a month so everyone can afford it. - -Drug companies will still do very well. And while we’re at it let Medicare negotiate lower prices for prescription drugs, like the VA already does. - -Look, the American Rescue Plan is helping millions of families on Affordable Care Act plans save $2,400 a year on their health care premiums. Let’s close the coverage gap and make those savings permanent. - -Second – cut energy costs for families an average of $500 a year by combatting climate change. - -Let’s provide investments and tax credits to weatherize your homes and businesses to be energy efficient and you get a tax credit; double America’s clean energy production in solar, wind, and so much more; lower the price of electric vehicles, saving you another $80 a month because you’ll never have to pay at the gas pump again. - -Third – cut the cost of child care. Many families pay up to $14,000 a year for child care per child. - -Middle-class and working families shouldn’t have to pay more than 7% of their income for care of young children. - -My plan will cut the cost in half for most families and help parents, including millions of women, who left the workforce during the pandemic because they couldn’t afford child care, to be able to get back to work. - -My plan doesn’t stop there. It also includes home and long-term care. More affordable housing. And Pre-K for every 3- and 4-year-old. - -All of these will lower costs. - -And under my plan, nobody earning less than $400,000 a year will pay an additional penny in new taxes. Nobody. - -The one thing all Americans agree on is that the tax system is not fair. We have to fix it. - -I’m not looking to punish anyone. But let’s make sure corporations and the wealthiest Americans start paying their fair share. - -Just last year, 55 Fortune 500 corporations earned $40 billion in profits and paid zero dollars in federal income tax. - -That’s simply not fair. That’s why I’ve proposed a 15% minimum tax rate for corporations. - -We got more than 130 countries to agree on a global minimum tax rate so companies can’t get out of paying their taxes at home by shipping jobs and factories overseas. - -That’s why I’ve proposed closing loopholes so the very wealthy don’t pay a lower tax rate than a teacher or a firefighter. - -So that’s my plan. It will grow the economy and lower costs for families. - -So what are we waiting for? Let’s get this done. And while you’re at it, confirm my nominees to the Federal Reserve, which plays a critical role in fighting inflation. - -My plan will not only lower costs to give families a fair shot, it will lower the deficit. - -The previous Administration not only ballooned the deficit with tax cuts for the very wealthy and corporations, it undermined the watchdogs whose job was to keep pandemic relief funds from being wasted. - -But in my administration, the watchdogs have been welcomed back. - -We’re going after the criminals who stole billions in relief money meant for small businesses and millions of Americans. - -And tonight, I’m announcing that the Justice Department will name a chief prosecutor for pandemic fraud. - -By the end of this year, the deficit will be down to less than half what it was before I took office. - -The only president ever to cut the deficit by more than one trillion dollars in a single year. - -Lowering your costs also means demanding more competition. - -I’m a capitalist, but capitalism without competition isn’t capitalism. - -It’s exploitation—and it drives up prices. - -When corporations don’t have to compete, their profits go up, your prices go up, and small businesses and family farmers and ranchers go under. - -We see it happening with ocean carriers moving goods in and out of America. - -During the pandemic, these foreign-owned companies raised prices by as much as 1,000% and made record profits. - -Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. - -And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. - -That ends on my watch. - -Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. - -We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. - -Let’s pass the Paycheck Fairness Act and paid leave. - -Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. - -Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges. - -And let’s pass the PRO Act when a majority of workers want to form a union—they shouldn’t be stopped. - -When we invest in our workers, when we build the economy from the bottom up and the middle out together, we can do something we haven’t done in a long time: build a better America. - -For more than two years, COVID-19 has impacted every decision in our lives and the life of the nation. - -And I know you’re tired, frustrated, and exhausted. - -But I also know this. - -Because of the progress we’ve made, because of your resilience and the tools we have, tonight I can say -we are moving forward safely, back to more normal routines. - -We’ve reached a new moment in the fight against COVID-19, with severe cases down to a level not seen since last July. - -Just a few days ago, the Centers for Disease Control and Prevention—the CDC—issued new mask guidelines. - -Under these new guidelines, most Americans in most of the country can now be mask free. - -And based on the projections, more of the country will reach that point across the next couple of weeks. - -Thanks to the progress we have made this past year, COVID-19 need no longer control our lives. - -I know some are talking about “living with COVID-19”. Tonight – I say that we will never just accept living with COVID-19. - -We will continue to combat the virus as we do other diseases. And because this is a virus that mutates and spreads, we will stay on guard. - -Here are four common sense steps as we move forward safely. - -First, stay protected with vaccines and treatments. We know how incredibly effective vaccines are. If you’re vaccinated and boosted you have the highest degree of protection. - -We will never give up on vaccinating more Americans. Now, I know parents with kids under 5 are eager to see a vaccine authorized for their children. - -The scientists are working hard to get that done and we’ll be ready with plenty of vaccines when they do. - -We’re also ready with anti-viral treatments. If you get COVID-19, the Pfizer pill reduces your chances of ending up in the hospital by 90%. - -We’ve ordered more of these pills than anyone in the world. And Pfizer is working overtime to get us 1 Million pills this month and more than double that next month. - -And we’re launching the “Test to Treat” initiative so people can get tested at a pharmacy, and if they’re positive, receive antiviral pills on the spot at no cost. - -If you’re immunocompromised or have some other vulnerability, we have treatments and free high-quality masks. - -We’re leaving no one behind or ignoring anyone’s needs as we move forward. - -And on testing, we have made hundreds of millions of tests available for you to order for free. - -Even if you already ordered free tests tonight, I am announcing that you can order more from covidtests.gov starting next week. - -Second – we must prepare for new variants. Over the past year, we’ve gotten much better at detecting new variants. - -If necessary, we’ll be able to deploy new vaccines within 100 days instead of many more months or years. - -And, if Congress provides the funds we need, we’ll have new stockpiles of tests, masks, and pills ready if needed. - -I cannot promise a new variant won’t come. But I can promise you we’ll do everything within our power to be ready if it does. - -Third – we can end the shutdown of schools and businesses. We have the tools we need. - -It’s time for Americans to get back to work and fill our great downtowns again. People working from home can feel safe to begin to return to the office. - -We’re doing that here in the federal government. The vast majority of federal workers will once again work in person. - -Our schools are open. Let’s keep it that way. Our kids need to be in school. - -And with 75% of adult Americans fully vaccinated and hospitalizations down by 77%, most Americans can remove their masks, return to work, stay in the classroom, and move forward safely. - -We achieved this because we provided free vaccines, treatments, tests, and masks. - -Of course, continuing this costs money. - -I will soon send Congress a request. - -The vast majority of Americans have used these tools and may want to again, so I expect Congress to pass it quickly. - -Fourth, we will continue vaccinating the world. - -We’ve sent 475 Million vaccine doses to 112 countries, more than any other nation. - -And we won’t stop. - -We have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. - -Let’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. - -Let’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. - -We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. - -I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. - -They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. - -Officer Mora was 27 years old. - -Officer Rivera was 22. - -Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. - -I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. - -I’ve worked on these issues a long time. - -I know what works: Investing in crime prevention and community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety. - -So let’s not abandon our streets. Or choose between safety and equal justice. - -Let’s come together to protect our communities, restore trust, and hold law enforcement accountable. - -That’s why the Justice Department required body cameras, banned chokeholds, and restricted no-knock warrants for its officers. - -That’s why the American Rescue Plan provided $350 Billion that cities, states, and counties can use to hire more police and invest in proven strategies like community violence interruption—trusted messengers breaking the cycle of violence and trauma and giving young people hope. - -We should all agree: The answer is not to Defund the police. The answer is to FUND the police with the resources and training they need to protect our communities. - -I ask Democrats and Republicans alike: Pass my budget and keep our neighborhoods safe. - -And I will keep doing everything in my power to crack down on gun trafficking and ghost guns you can buy online and make at home—they have no serial numbers and can’t be traced. - -And I ask Congress to pass proven measures to reduce gun violence. Pass universal background checks. Why should anyone on a terrorist list be able to purchase a weapon? - -Ban assault weapons and high-capacity magazines. - -Repeal the liability shield that makes gun manufacturers the only industry in America that can’t be sued. - -These laws don’t infringe on the Second Amendment. They save lives. - -The most fundamental right in America is the right to vote – and to have it counted. And it’s under assault. - -In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. - -We cannot let this happen. - -Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. - -Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. - -One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. - -And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence. - -A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. - -And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. - -We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. - -We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. - -We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. - -We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. - -We can do all this while keeping lit the torch of liberty that has led generations of immigrants to this land—my forefathers and so many of yours. - -Provide a pathway to citizenship for Dreamers, those on temporary status, farm workers, and essential workers. - -Revise our laws so businesses have the workers they need and families don’t wait decades to reunite. - -It’s not only the right thing to do—it’s the economically smart thing to do. - -That’s why immigration reform is supported by everyone from labor unions to religious leaders to the U.S. Chamber of Commerce. - -Let’s get it done once and for all. - -Advancing liberty and justice also requires protecting the rights of women. - -The constitutional right affirmed in Roe v. Wade—standing precedent for half a century—is under attack as never before. - -If we want to go forward—not backward—we must protect access to health care. Preserve a woman’s right to choose. And let’s continue to advance maternal health care in America. - -And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. - -As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. - -While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. - -And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. - -So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. - -First, beat the opioid epidemic. - -There is so much we can do. Increase funding for prevention, treatment, harm reduction, and recovery. - -Get rid of outdated rules that stop doctors from prescribing treatments. And stop the flow of illicit drugs by working with state and local law enforcement to go after traffickers. - -If you’re suffering from addiction, know you are not alone. I believe in recovery, and I celebrate the 23 million Americans in recovery. - -Second, let’s take on mental health. Especially among our children, whose lives and education have been turned upside down. - -The American Rescue Plan gave schools money to hire teachers and help students make up for lost learning. - -I urge every parent to make sure your school does just that. And we can all play a part—sign up to be a tutor or a mentor. - -Children were also struggling before the pandemic. Bullying, violence, trauma, and the harms of social media. - -As Frances Haugen, who is here with us tonight, has shown, we must hold social media platforms accountable for the national experiment they’re conducting on our children for profit. - -It’s time to strengthen privacy protections, ban targeted advertising to children, demand tech companies stop collecting personal data on our children. - -And let’s get all Americans the mental health services they need. More people they can turn to for help, and full parity between physical and mental health care. - -Third, support our veterans. - -Veterans are the best of us. - -I’ve always believed that we have a sacred obligation to equip all those we send to war and care for them and their families when they come home. - -My administration is providing assistance with job training and housing, and now helping lower-income veterans get VA care debt-free. - -Our troops in Iraq and Afghanistan faced many dangers. - -One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. - -When they came home, many of the world’s fittest and best trained warriors were never the same. - -Headaches. Numbness. Dizziness. - -A cancer that would put them in a flag-draped coffin. - -I know. - -One of those soldiers was my son Major Beau Biden. - -We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. - -But I’m committed to finding out everything we can. - -Committed to military families like Danielle Robinson from Ohio. - -The widow of Sergeant First Class Heath Robinson. - -He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. - -Stationed near Baghdad, just yards from burn pits the size of football fields. - -Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter. - -But cancer from prolonged exposure to burn pits ravaged Heath’s lungs and body. - -Danielle says Heath was a fighter to the very end. - -He didn’t know how to stop fighting, and neither did she. - -Through her pain she found purpose to demand we do better. - -Tonight, Danielle—we are. - -The VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits. - -And tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers. - -I’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve. - -And fourth, let’s end cancer as we know it. - -This is personal to me and Jill, to Kamala, and to so many of you. - -Cancer is the #2 cause of death in America–second only to heart disease. - -Last month, I announced our plan to supercharge -the Cancer Moonshot that President Obama asked me to lead six years ago. - -Our goal is to cut the cancer death rate by at least 50% over the next 25 years, turn more cancers from death sentences into treatable diseases. - -More support for patients and families. - -To get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. - -It’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. - -ARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. - -A unity agenda for the nation. - -We can do this. - -My fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. - -In this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. - -We have fought for freedom, expanded liberty, defeated totalitarianism and terror. - -And built the strongest, freest, and most prosperous nation the world has ever known. - -Now is the hour. - -Our moment of responsibility. - -Our test of resolve and conscience, of history itself. - -It is in this moment that our character is formed. Our purpose is found. Our future is forged. - -Well I know this nation. - -We will meet the test. - -To protect freedom and liberty, to expand fairness and opportunity. - -We will save democracy. - -As hard as these times have been, I am more optimistic about America today than I have been my whole life. - -Because I see the future that is within our grasp. - -Because I know there is simply nothing beyond our capacity. - -We are the only nation on Earth that has always turned every crisis we have faced into an opportunity. - -The only nation that can be defined by a single word: possibilities. - -So on this night, in our 245th year as a nation, I have come to report on the State of the Union. - -And my report is this: the State of the Union is strong—because you, the American people, are strong. - -We are stronger today than we were a year ago. - -And we will be stronger a year from now than we are today. - -Now is our moment to meet and overcome the challenges of our time. - -And we will, as one people. - -One America. - -The United States of America. - -May God bless you all. May God protect our troops. \ No newline at end of file diff --git a/docs/vectorstores.ipynb b/docs/vectorstores.ipynb deleted file mode 100644 index cde851f..0000000 --- a/docs/vectorstores.ipynb +++ /dev/null @@ -1,921 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "1957f5cb", - "metadata": {}, - "source": [ - "---\n", - "sidebar_label: Weaviate\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "ef1f0986", - "metadata": {}, - "source": [ - "# Weaviate\n", - "\n", - "This notebook covers how to get started with the Weaviate vector store in LangChain, using the `langchain-weaviate` package.\n", - "\n", - "> [Weaviate](https://weaviate.io/) is an open-source vector database. It allows you to store data objects and vector embeddings from your favorite ML-models, and scale seamlessly into billions of data objects.\n", - "\n", - "To use this integration, you need to have a running Weaviate database instance.\n", - "\n", - "## Minimum versions\n", - "\n", - "This module requires Weaviate `1.23.7` or higher. However, we recommend you use the latest version of Weaviate.\n", - "\n", - "## Connecting to Weaviate\n", - "\n", - "In this notebook, we assume that you have a local instance of Weaviate running on `http://localhost:8080` and port 50051 open for [gRPC traffic](https://weaviate.io/blog/grpc-performance-improvements). So, we will connect to Weaviate with:\n", - "\n", - "```python\n", - "weaviate_client = weaviate.connect_to_local()\n", - "```\n", - "\n", - "### Other deployment options\n", - "\n", - "Weaviate can be [deployed in many different ways](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate) such as using [Weaviate Cloud Services (WCS)](https://console.weaviate.cloud), [Docker](https://weaviate.io/developers/weaviate/installation/docker-compose) or [Kubernetes](https://weaviate.io/developers/weaviate/installation/kubernetes). \n", - "\n", - "If your Weaviate instance is deployed in another way, [read more here](https://weaviate.io/developers/weaviate/client-libraries/python#instantiate-a-client) about different ways to connect to Weaviate. You can use different [helper functions](https://weaviate.io/developers/weaviate/client-libraries/python#python-client-v4-helper-functions) or [create a custom instance](https://weaviate.io/developers/weaviate/client-libraries/python#python-client-v4-explicit-connection).\n", - "\n", - "> Note that you require a `v4` client API, which will create a `weaviate.WeaviateClient` object.\n", - "\n", - "### Authentication\n", - "\n", - "Some Weaviate instances, such as those running on WCS, have authentication enabled, such as API key and/or username+password authentication.\n", - "\n", - "Read the [client authentication guide](https://weaviate.io/developers/weaviate/client-libraries/python#authentication) for more information, as well as the [in-depth authentication configuration page](https://weaviate.io/developers/weaviate/configuration/authentication)." - ] - }, - { - "cell_type": "markdown", - "id": "4a8437b1", - "metadata": {}, - "source": [ - "## Installation" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "d97b55c2", - "metadata": {}, - "outputs": [], - "source": [ - "# install package\n", - "# %pip install -Uqq langchain-weaviate\n", - "# %pip install openai tiktoken langchain" - ] - }, - { - "cell_type": "markdown", - "id": "36fdc060", - "metadata": {}, - "source": [ - "## Environment Setup\n", - "\n", - "This notebook uses the OpenAI API through `OpenAIEmbeddings`. We suggest obtaining an OpenAI API key and export it as an environment variable with the name `OPENAI_API_KEY`.\n", - "\n", - "Once this is done, your OpenAI API key will be read automatically. If you are new to environment variables, read more about them [here](https://docs.python.org/3/library/os.html#os.environ) or in [this guide](https://www.twilio.com/en-us/blog/environment-variables-python)." - ] - }, - { - "cell_type": "markdown", - "id": "a8e3a83f", - "metadata": {}, - "source": [ - "# Usage" - ] - }, - { - "cell_type": "markdown", - "id": "6efee7cd", - "metadata": {}, - "source": [ - "## Find objects by similarity" - ] - }, - { - "cell_type": "markdown", - "id": "dc37144c-208d-4ab3-9f3a-0407a69fe052", - "metadata": { - "tags": [] - }, - "source": [ - "Here is an example of how to find objects by similarity to a query, from data import to querying the Weaviate instance.\n", - "\n", - "### Step 1: Data import\n", - "\n", - "First, we will create data to add to `Weaviate` by loading and chunking the contents of a long text file. " - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "9d0ab00c", - "metadata": {}, - "outputs": [], - "source": [ - "from langchain_community.document_loaders import TextLoader\n", - "from langchain_community.embeddings.openai import OpenAIEmbeddings\n", - "from langchain.text_splitter import CharacterTextSplitter" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "4618779d", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.embeddings.openai.OpenAIEmbeddings` was deprecated in langchain-community 0.1.0 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import OpenAIEmbeddings`.\n", - " warn_deprecated(\n" - ] - } - ], - "source": [ - "loader = TextLoader(\"state_of_the_union.txt\")\n", - "documents = loader.load()\n", - "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", - "docs = text_splitter.split_documents(documents)\n", - "\n", - "embeddings = OpenAIEmbeddings()" - ] - }, - { - "cell_type": "markdown", - "id": "ae774cf5", - "metadata": {}, - "source": [ - "Now, we can import the data. \n", - "\n", - "To do so, connect to the Weaviate instance and use the resulting `weaviate_client` object. For example, we can import the documents as shown below:" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "3fbda8c4", - "metadata": {}, - "outputs": [], - "source": [ - "from langchain_weaviate.vectorstores import WeaviateVectorStore\n", - "import weaviate" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e06f64b7", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n" - ] - } - ], - "source": [ - "weaviate_client = weaviate.connect_to_local()\n", - "db = WeaviateVectorStore.from_documents(docs, embeddings, client=weaviate_client)" - ] - }, - { - "cell_type": "markdown", - "id": "abe29115", - "metadata": {}, - "source": [ - "### Step 2: Perform the search" - ] - }, - { - "cell_type": "markdown", - "id": "2799f5a3", - "metadata": {}, - "source": [ - "We can now perform a similarity search. This will return the most similar documents to the query text, based on the embeddings stored in Weaviate and an equivalent embedding generated from the query text." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "ebc3aa1e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "Document 1:\n", - "Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Ac...\n", - "\n", - "Document 2:\n", - "And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of ...\n", - "\n", - "Document 3:\n", - "Vice President Harris and I ran for office with a new economic vision for America. \n", - "\n", - "Invest in Ameri...\n", - "\n", - "Document 4:\n", - "A former top litigator in private practice. A former federal public defender. And from a family of p...\n" - ] - } - ], - "source": [ - "query = \"What did the president say about Ketanji Brown Jackson\"\n", - "docs = db.similarity_search(query)\n", - "\n", - "# Print the first 100 characters of each result\n", - "for i, doc in enumerate(docs):\n", - " print(f\"\\nDocument {i+1}:\")\n", - " print(doc.page_content[:100] + \"...\")" - ] - }, - { - "cell_type": "markdown", - "id": "ca1134ef", - "metadata": {}, - "source": [ - "You can also add filters, which will either include or exclude results based on the filter conditions. (See [more filter examples](https://weaviate.io/developers/weaviate/search/filters).)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "d1210f90", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n", - "4\n" - ] - } - ], - "source": [ - "from weaviate.classes.query import Filter\n", - "\n", - "for filter_str in [\"blah.txt\", \"state_of_the_union.txt\"]:\n", - " search_filter = Filter.by_property(\"source\").equal(filter_str)\n", - " filtered_search_results = db.similarity_search(query, filters=search_filter)\n", - " print(len(filtered_search_results))\n", - " if filter_str == \"state_of_the_union.txt\":\n", - " assert len(filtered_search_results) > 0 # There should be at least one result\n", - " else:\n", - " assert len(filtered_search_results) == 0 # There should be no results" - ] - }, - { - "cell_type": "markdown", - "id": "2646a25f", - "metadata": {}, - "source": [ - "It is also possible to provide `k`, which is the upper limit of the number of results to return." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "6e53d7d5", - "metadata": {}, - "outputs": [], - "source": [ - "search_filter = Filter.by_property(\"source\").equal(\"state_of_the_union.txt\")\n", - "filtered_search_results = db.similarity_search(query, filters=search_filter, k=3)\n", - "assert len(filtered_search_results) <= 3" - ] - }, - { - "cell_type": "markdown", - "id": "26bfd9bc", - "metadata": {}, - "source": [ - "### Quantify result similarity" - ] - }, - { - "cell_type": "markdown", - "id": "3b286d60", - "metadata": {}, - "source": [ - "You can optionally retrieve a relevance \"score\". This is a relative score that indicates how good the particular search results is, amongst the pool of search results. \n", - "\n", - "Note that this is relative score, meaning that it should not be used to determine thresholds for relevance. However, it can be used to compare the relevance of different search results within the entire search result set." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "b3b4a2f4", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.935 : For that purpose we’ve mobilized American ground forces, air squadrons, and ship deployments to prot...\n", - "0.500 : And built the strongest, freest, and most prosperous nation the world has ever known. \n", - "\n", - "Now is the h...\n", - "0.462 : If you travel 20 miles east of Columbus, Ohio, you’ll find 1,000 empty acres of land. \n", - "\n", - "It won’t loo...\n", - "0.450 : And my report is this: the State of the Union is strong—because you, the American people, are strong...\n", - "0.442 : Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Ac...\n" - ] - } - ], - "source": [ - "docs = db.similarity_search_with_score(\"country\", k=5)\n", - "\n", - "for doc in docs:\n", - " print(f\"{doc[1]:.3f}\", \":\", doc[0].page_content[:100] + \"...\")" - ] - }, - { - "cell_type": "markdown", - "id": "8abf9adc", - "metadata": {}, - "source": [ - "## Search mechanism" - ] - }, - { - "cell_type": "markdown", - "id": "d2d5b24a", - "metadata": {}, - "source": [ - "`similarity_search` uses Weaviate's [hybrid search](https://weaviate.io/developers/weaviate/api/graphql/search-operators#hybrid).\n", - "\n", - "A hybrid search combines a vector and a keyword search, with `alpha` as the weight of the vector search. The `similarity_search` function allows you to pass additional arguments as kwargs. See this [reference doc](https://weaviate.io/developers/weaviate/api/graphql/search-operators#hybrid) for the available arguments.\n", - "\n", - "So, you can perform a pure keyword search by adding `alpha=0` as shown below:" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "74a7bae0", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': 'state_of_the_union.txt'})" - ] - }, - "execution_count": 10, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "docs = db.similarity_search(query, alpha=0)\n", - "docs[0]" - ] - }, - { - "cell_type": "markdown", - "id": "a2b75761", - "metadata": {}, - "source": [ - "## Persistence" - ] - }, - { - "cell_type": "markdown", - "id": "5f298bc0", - "metadata": {}, - "source": [ - "Any data added through `langchain-weaviate` will persist in Weaviate according to its configuration. \n", - "\n", - "WCS instances, for example, are configured to persist data indefinitely, and Docker instances can be set up to persist data in a volume. Read more about [Weaviate's persistence](https://weaviate.io/developers/weaviate/configuration/persistence)." - ] - }, - { - "cell_type": "markdown", - "id": "da874a61", - "metadata": {}, - "source": [ - "## Multi-tenancy" - ] - }, - { - "cell_type": "markdown", - "id": "67a0719f", - "metadata": {}, - "source": [ - "[Multi-tenancy](https://weaviate.io/developers/weaviate/concepts/data#multi-tenancy) allows you to have a high number of isolated collections of data, with the same collection configuration, in a single Weaviate instance. This is great for multi-user environments such as building a SaaS app, where each end user will have their own isolated data collection.\n", - "\n", - "To use multi-tenancy, the vector store need to be aware of the `tenant` parameter. \n", - "\n", - "So when adding any data, provide the `tenant` parameter as shown below." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "8d365855", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "2024-Mar-26 03:40 PM - langchain_weaviate.vectorstores - INFO - Tenant Foo does not exist in index LangChain_30b9273d43b3492db4fb2aba2e0d6871. Creating tenant.\n" - ] - } - ], - "source": [ - "db_with_mt = WeaviateVectorStore.from_documents(\n", - " docs, embeddings, client=weaviate_client, tenant=\"Foo\"\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "2b3e6107", - "metadata": {}, - "source": [ - "And when performing queries, provide the `tenant` parameter also." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "49659eb3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': 'state_of_the_union.txt'}),\n", - " Document(page_content='And so many families are living paycheck to paycheck, struggling to keep up with the rising cost of food, gas, housing, and so much more. \\n\\nI understand. \\n\\nI remember when my Dad had to leave our home in Scranton, Pennsylvania to find work. I grew up in a family where if the price of food went up, you felt it. \\n\\nThat’s why one of the first things I did as President was fight to pass the American Rescue Plan. \\n\\nBecause people were hurting. We needed to act, and we did. \\n\\nFew pieces of legislation have done more in a critical moment in our history to lift us out of crisis. \\n\\nIt fueled our efforts to vaccinate the nation and combat COVID-19. It delivered immediate economic relief for tens of millions of Americans. \\n\\nHelped put food on their table, keep a roof over their heads, and cut the cost of health insurance. \\n\\nAnd as my Dad used to say, it gave people a little breathing room.', metadata={'source': 'state_of_the_union.txt'}),\n", - " Document(page_content='He and his Dad both have Type 1 diabetes, which means they need insulin every day. Insulin costs about $10 a vial to make. \\n\\nBut drug companies charge families like Joshua and his Dad up to 30 times more. I spoke with Joshua’s mom. \\n\\nImagine what it’s like to look at your child who needs insulin and have no idea how you’re going to pay for it. \\n\\nWhat it does to your dignity, your ability to look your child in the eye, to be the parent you expect to be. \\n\\nJoshua is here with us tonight. Yesterday was his birthday. Happy birthday, buddy. \\n\\nFor Joshua, and for the 200,000 other young people with Type 1 diabetes, let’s cap the cost of insulin at $35 a month so everyone can afford it. \\n\\nDrug companies will still do very well. And while we’re at it let Medicare negotiate lower prices for prescription drugs, like the VA already does.', metadata={'source': 'state_of_the_union.txt'}),\n", - " Document(page_content='Putin’s latest attack on Ukraine was premeditated and unprovoked. \\n\\nHe rejected repeated efforts at diplomacy. \\n\\nHe thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. \\n\\nWe prepared extensively and carefully. \\n\\nWe spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. \\n\\nI spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. \\n\\nWe countered Russia’s lies with truth. \\n\\nAnd now that he has acted the free world is holding him accountable. \\n\\nAlong with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.', metadata={'source': 'state_of_the_union.txt'})]" - ] - }, - "execution_count": 12, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "db_with_mt.similarity_search(query, tenant=\"Foo\")" - ] - }, - { - "cell_type": "markdown", - "id": "24ecf858", - "metadata": {}, - "source": [ - "## Retriever options" - ] - }, - { - "cell_type": "markdown", - "id": "68e3757a", - "metadata": {}, - "source": [ - "Weaviate can also be used as a retriever" - ] - }, - { - "cell_type": "markdown", - "id": "f2a8712d", - "metadata": {}, - "source": [ - "### Maximal marginal relevance search (MMR)" - ] - }, - { - "cell_type": "markdown", - "id": "c92add51", - "metadata": {}, - "source": [ - "In addition to using similaritysearch in the retriever object, you can also use `mmr`." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "cb302651", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n" - ] - }, - { - "data": { - "text/plain": [ - "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': 'state_of_the_union.txt'})" - ] - }, - "execution_count": 13, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "retriever = db.as_retriever(search_type=\"mmr\")\n", - "retriever.get_relevant_documents(query)[0]" - ] - }, - { - "cell_type": "markdown", - "id": "22f52ca4", - "metadata": {}, - "source": [ - "# Use with LangChain" - ] - }, - { - "cell_type": "markdown", - "id": "66690c78", - "metadata": {}, - "source": [ - "A known limitation of large languag models (LLMs) is that their training data can be outdated, or not include the specific domain knowledge that you require.\n", - "\n", - "Take a look at the example below:" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "f74e20d8", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.chat_models.openai.ChatOpenAI` was deprecated in langchain-community 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`.\n", - " warn_deprecated(\n", - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `predict` was deprecated in LangChain 0.1.7 and will be removed in 0.2.0. Use invoke instead.\n", - " warn_deprecated(\n", - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n" - ] - }, - { - "data": { - "text/plain": [ - "\"I'm sorry, I cannot provide real-time information as my responses are generated based on a mixture of licensed data, data created by human trainers, and publicly available data. The last update was in October 2021.\"" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from langchain_community.chat_models import ChatOpenAI\n", - "\n", - "llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)\n", - "llm.predict(\"What did the president say about Justice Breyer\")" - ] - }, - { - "cell_type": "markdown", - "id": "829720ad", - "metadata": {}, - "source": [ - "Vector stores complement LLMs by providing a way to store and retrieve relevant information. This allow you to combine the strengths of LLMs and vector stores, by using LLM's reasoning and linguistic capabilities with vector stores' ability to retrieve relevant information.\n", - "\n", - "Two well-known applications for combining LLMs and vector stores are:\n", - "- Question answering\n", - "- Retrieval-augmented generation (RAG)" - ] - }, - { - "cell_type": "markdown", - "id": "0ae85eb4", - "metadata": {}, - "source": [ - "### Question Answering with Sources" - ] - }, - { - "cell_type": "markdown", - "id": "902d8ba7", - "metadata": {}, - "source": [ - "Question answering in langchain can be enhanced by the use of vector stores. Let's see how this can be done.\n", - "\n", - "This section uses the `RetrievalQAWithSourcesChain`, which does the lookup of the documents from an Index. \n", - "\n", - "First, we will chunk the text again and import them into the Weaviate vector store." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "ad91ded1", - "metadata": {}, - "outputs": [], - "source": [ - "from langchain.chains import RetrievalQAWithSourcesChain\n", - "from langchain_community.llms import OpenAI" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "2438d702", - "metadata": {}, - "outputs": [], - "source": [ - "with open(\"state_of_the_union.txt\") as f:\n", - " state_of_the_union = f.read()\n", - "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", - "texts = text_splitter.split_text(state_of_the_union)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "b0e106ab", - "metadata": {}, - "outputs": [], - "source": [ - "docsearch = WeaviateVectorStore.from_texts(\n", - " texts,\n", - " embeddings,\n", - " client=weaviate_client,\n", - " metadatas=[{\"source\": f\"{i}-pl\"} for i in range(len(texts))],\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "546bc958", - "metadata": {}, - "source": [ - "Now we can construct the chain, with the retriever specified:" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "86bbb953", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The class `langchain_community.llms.openai.OpenAI` was deprecated in langchain-community 0.0.10 and will be removed in 0.2.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import OpenAI`.\n", - " warn_deprecated(\n" - ] - } - ], - "source": [ - "chain = RetrievalQAWithSourcesChain.from_chain_type(\n", - " OpenAI(temperature=0), chain_type=\"stuff\", retriever=docsearch.as_retriever()\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "f8371444", - "metadata": {}, - "source": [ - "And run the chain, to ask the question:" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "5c38cc39", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n", - " warn_deprecated(\n", - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n", - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n" - ] - }, - { - "data": { - "text/plain": [ - "{'answer': ' The president thanked Justice Stephen Breyer for his service and announced his nomination of Judge Ketanji Brown Jackson to the Supreme Court.\\n',\n", - " 'sources': '31-pl'}" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "chain(\n", - " {\"question\": \"What did the president say about Justice Breyer\"},\n", - " return_only_outputs=True,\n", - ")" - ] - }, - { - "cell_type": "markdown", - "id": "fecab3b5", - "metadata": {}, - "source": [ - "### Retrieval-Augmented Generation\n", - "\n", - "Another very popular application of combining LLMs and vector stores is retrieval-augmented generation (RAG). This is a technique that uses a retriever to find relevant information from a vector store, and then uses an LLM to provide an output based on the retrieved data and a prompt.\n", - "\n", - "We begin with a similar setup:" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "33b0a9d3", - "metadata": {}, - "outputs": [], - "source": [ - "with open(\"state_of_the_union.txt\") as f:\n", - " state_of_the_union = f.read()\n", - "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n", - "texts = text_splitter.split_text(state_of_the_union)" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "d2ade6ae", - "metadata": {}, - "outputs": [], - "source": [ - "docsearch = WeaviateVectorStore.from_texts(\n", - " texts,\n", - " embeddings,\n", - " client=weaviate_client,\n", - " metadatas=[{\"source\": f\"{i}-pl\"} for i in range(len(texts))],\n", - ")\n", - "\n", - "retriever = docsearch.as_retriever()" - ] - }, - { - "cell_type": "markdown", - "id": "39413671", - "metadata": {}, - "source": [ - "We need to construct a template for the RAG model so that the retrieved information will be populated in the template." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "578570b8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "input_variables=['context', 'question'] messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['context', 'question'], template=\"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\\nQuestion: {question}\\nContext: {context}\\nAnswer:\\n\"))]\n" - ] - } - ], - "source": [ - "from langchain_core.prompts import ChatPromptTemplate\n", - "\n", - "template = \"\"\"You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.\n", - "Question: {question}\n", - "Context: {context}\n", - "Answer:\n", - "\"\"\"\n", - "prompt = ChatPromptTemplate.from_template(template)\n", - "\n", - "print(prompt)" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "74982155", - "metadata": {}, - "outputs": [], - "source": [ - "from langchain_community.chat_models import ChatOpenAI\n", - "\n", - "llm = ChatOpenAI(model_name=\"gpt-3.5-turbo\", temperature=0)" - ] - }, - { - "cell_type": "markdown", - "id": "e47abe3a", - "metadata": {}, - "source": [ - "And running the cell, we get a very similar output." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "fe129bdd", - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n", - "/workspaces/langchain-weaviate/.venv/lib/python3.12/site-packages/pydantic/main.py:1024: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.6/migration/\n", - " warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20)\n" - ] - }, - { - "data": { - "text/plain": [ - "\"The president honored Justice Stephen Breyer for his service to the country as an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. The president also mentioned nominating Circuit Court of Appeals Judge Ketanji Brown Jackson to continue Justice Breyer's legacy of excellence. The president expressed gratitude towards Justice Breyer and highlighted the importance of nominating someone to serve on the United States Supreme Court.\"" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from langchain_core.output_parsers import StrOutputParser\n", - "from langchain_core.runnables import RunnablePassthrough\n", - "\n", - "rag_chain = (\n", - " {\"context\": retriever, \"question\": RunnablePassthrough()}\n", - " | prompt\n", - " | llm\n", - " | StrOutputParser()\n", - ")\n", - "\n", - "rag_chain.invoke(\"What did the president say about Justice Breyer\")" - ] - }, - { - "cell_type": "markdown", - "id": "ce5a2553", - "metadata": {}, - "source": [ - "But note that since the template is upto you to construct, you can customize it to your needs. " - ] - }, - { - "cell_type": "markdown", - "id": "e7417ac5", - "metadata": {}, - "source": [ - "### Wrap-up & resources\n", - "\n", - "Weaviate is a scalable, production-ready vector store. \n", - "\n", - "This integration allows Weaviate to be used with LangChain to enhance the capabilities of large language models with a robust data store. Its scalability and production-readiness make it a great choice as a vector store for your LangChain applications, and it will reduce your time to production." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "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.12" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/libs/weaviate/LICENSE b/libs/weaviate/LICENSE new file mode 100644 index 0000000..fc0602f --- /dev/null +++ b/libs/weaviate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 LangChain, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Makefile b/libs/weaviate/Makefile similarity index 100% rename from Makefile rename to libs/weaviate/Makefile diff --git a/libs/weaviate/README.md b/libs/weaviate/README.md new file mode 100644 index 0000000..e8b177f --- /dev/null +++ b/libs/weaviate/README.md @@ -0,0 +1,41 @@ +# langchain-weaviate + +## About + +This package contains the [Weaviate](https://github.com/weaviate/weaviate) integrations for [LangChain](https://github.com/langchain-ai/langchain). + +- **Weaviate** is an open source, AI-native vector database that helps developers create intuitive and reliable AI-powered applications. +- **LangChain** is a framework for developing applications powered by language models. + +Using this package, LangChain users can conveniently set Weaviate as their vector store to store and retrieve embeddings. + +## Requirements + +To use this package, you need to have a running Weaviate instance. + +Weaviate can be [deployed in many different ways](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate) such as in containerized environments, on Kubernetes, or in the cloud as a managed service, on-premises, or through a cloud provider such as AWS or Google Cloud. + +The deployment method to choose depends on your use case and infrastructure requirements. + +Two of the most common ways to deploy Weaviate are: +- [Docker Compose](https://weaviate.io/developers/weaviate/installation/docker-compose) +- [Weaviate Cloud Services (WCS)](https://console.weaviate.cloud) + +## Installation and Setup + +As an integration package, this assumes you have already installed LangChain. If not, please refer to the [LangChain installation guide](https://python.langchain.com/docs/get_started/installation). + +Then, install this package: + +```bash +pip install langchain-weaviate +``` + +## Usage + +Please see the included [Jupyter notebook](docs/vectorstores.ipynb) for an example of how to use this package. + +## Further resources + +- [LangChain documentation](https://python.langchain.com/docs) +- [Weaviate documentation](https://weaviate.io/developers/weaviate) diff --git a/langchain_weaviate/__init__.py b/libs/weaviate/langchain_weaviate/__init__.py similarity index 100% rename from langchain_weaviate/__init__.py rename to libs/weaviate/langchain_weaviate/__init__.py diff --git a/langchain_weaviate/_math.py b/libs/weaviate/langchain_weaviate/_math.py similarity index 100% rename from langchain_weaviate/_math.py rename to libs/weaviate/langchain_weaviate/_math.py diff --git a/langchain_weaviate/py.typed b/libs/weaviate/langchain_weaviate/py.typed similarity index 100% rename from langchain_weaviate/py.typed rename to libs/weaviate/langchain_weaviate/py.typed diff --git a/langchain_weaviate/utils.py b/libs/weaviate/langchain_weaviate/utils.py similarity index 100% rename from langchain_weaviate/utils.py rename to libs/weaviate/langchain_weaviate/utils.py diff --git a/langchain_weaviate/vectorstores.py b/libs/weaviate/langchain_weaviate/vectorstores.py similarity index 100% rename from langchain_weaviate/vectorstores.py rename to libs/weaviate/langchain_weaviate/vectorstores.py diff --git a/poetry.lock b/libs/weaviate/poetry.lock similarity index 100% rename from poetry.lock rename to libs/weaviate/poetry.lock diff --git a/pyproject.toml b/libs/weaviate/pyproject.toml similarity index 100% rename from pyproject.toml rename to libs/weaviate/pyproject.toml diff --git a/scripts/check_imports.py b/libs/weaviate/scripts/check_imports.py similarity index 100% rename from scripts/check_imports.py rename to libs/weaviate/scripts/check_imports.py diff --git a/scripts/check_pydantic.sh b/libs/weaviate/scripts/check_pydantic.sh similarity index 100% rename from scripts/check_pydantic.sh rename to libs/weaviate/scripts/check_pydantic.sh diff --git a/scripts/lint_imports.sh b/libs/weaviate/scripts/lint_imports.sh similarity index 100% rename from scripts/lint_imports.sh rename to libs/weaviate/scripts/lint_imports.sh diff --git a/tests/__init__.py b/libs/weaviate/tests/__init__.py similarity index 100% rename from tests/__init__.py rename to libs/weaviate/tests/__init__.py diff --git a/tests/docker-compose.yml b/libs/weaviate/tests/docker-compose.yml similarity index 100% rename from tests/docker-compose.yml rename to libs/weaviate/tests/docker-compose.yml diff --git a/tests/integration_tests/__init__.py b/libs/weaviate/tests/integration_tests/__init__.py similarity index 100% rename from tests/integration_tests/__init__.py rename to libs/weaviate/tests/integration_tests/__init__.py diff --git a/tests/integration_tests/test_compile.py b/libs/weaviate/tests/integration_tests/test_compile.py similarity index 100% rename from tests/integration_tests/test_compile.py rename to libs/weaviate/tests/integration_tests/test_compile.py diff --git a/tests/unit_tests/__init__.py b/libs/weaviate/tests/unit_tests/__init__.py similarity index 100% rename from tests/unit_tests/__init__.py rename to libs/weaviate/tests/unit_tests/__init__.py diff --git a/tests/unit_tests/fake_docs.json b/libs/weaviate/tests/unit_tests/fake_docs.json similarity index 100% rename from tests/unit_tests/fake_docs.json rename to libs/weaviate/tests/unit_tests/fake_docs.json diff --git a/tests/unit_tests/fake_embeddings.py b/libs/weaviate/tests/unit_tests/fake_embeddings.py similarity index 100% rename from tests/unit_tests/fake_embeddings.py rename to libs/weaviate/tests/unit_tests/fake_embeddings.py diff --git a/tests/unit_tests/test__math.py b/libs/weaviate/tests/unit_tests/test__math.py similarity index 100% rename from tests/unit_tests/test__math.py rename to libs/weaviate/tests/unit_tests/test__math.py diff --git a/tests/unit_tests/test_vectorstores_integration.py b/libs/weaviate/tests/unit_tests/test_vectorstores_integration.py similarity index 100% rename from tests/unit_tests/test_vectorstores_integration.py rename to libs/weaviate/tests/unit_tests/test_vectorstores_integration.py diff --git a/tests/unit_tests/test_vectorstores_unit.py b/libs/weaviate/tests/unit_tests/test_vectorstores_unit.py similarity index 100% rename from tests/unit_tests/test_vectorstores_unit.py rename to libs/weaviate/tests/unit_tests/test_vectorstores_unit.py diff --git a/release-please-config.json b/release-please-config.json deleted file mode 100644 index 3646bea..0000000 --- a/release-please-config.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "release-type": "python", - "bump-minor-pre-major": true, - "bump-patch-for-minor-pre-major": true, - "prerelease-type": "rc", - "separate-pull-requests": true, - "packages": { - ".": { - "package-name": "langchain-weaviate" - } - } -}