Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pinecone: init pkg #16556

Merged
merged 32 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
51eb035
cli[patch]: new fields in integration template
efriis Jan 22, 2024
2318b36
0.0.21
efriis Jan 22, 2024
736b164
auto bootstrap
efriis Jan 22, 2024
ac7c458
add dep
efriis Jan 22, 2024
6cfc578
Merge branch 'master' into erick/partner-pinecone
efriis Jan 22, 2024
fd30b05
use prev docs (rm docs)
efriis Jan 22, 2024
8501002
wip
efriis Jan 22, 2024
24c3ca3
Merge branch 'master' into erick/partner-pinecone
efriis Jan 22, 2024
f320985
Merge branch 'master' into erick/partner-pinecone
efriis Jan 23, 2024
7ff96bd
Merge branch 'master' into erick/partner-pinecone
efriis Jan 23, 2024
4577ced
x
efriis Jan 23, 2024
bbeffdc
x
efriis Jan 23, 2024
7bba7cd
x
efriis Jan 23, 2024
dbec9b5
x
efriis Jan 23, 2024
4d52954
x
efriis Jan 23, 2024
b59bc54
cassettes
efriis Jan 23, 2024
38652d0
x
efriis Jan 24, 2024
9af66e5
Merge branch 'master' into erick/partner-pinecone
efriis Jan 24, 2024
df6af7b
Merge branch 'master' into erick/partner-pinecone
efriis Jan 25, 2024
b6cce85
rm cassettes
efriis Jan 25, 2024
ca45218
Merge branch 'master' into erick/partner-pinecone
efriis Jan 31, 2024
655e4d7
waits
efriis Jan 31, 2024
fa4ba0c
async
efriis Jan 31, 2024
1007e2c
x
efriis Jan 31, 2024
dd4e25f
lint
efriis Jan 31, 2024
bf355a8
x
efriis Jan 31, 2024
21de925
Merge branch 'master' into erick/partner-pinecone
efriis Feb 2, 2024
2c8de8a
Merge branch 'master' into erick/partner-pinecone
efriis Feb 2, 2024
54e1546
x
efriis Feb 3, 2024
ba4cf95
docstring
efriis Feb 3, 2024
9fb6b2b
x
efriis Feb 3, 2024
91c5edb
x
efriis Feb 3, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 6 additions & 13 deletions libs/community/langchain_community/vectorstores/pinecone.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union

import numpy as np
from langchain_core._api.deprecation import deprecated
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.utils.iter import batch_iterate
Expand Down Expand Up @@ -41,24 +42,16 @@ def _is_pinecone_v3() -> bool:
return version.parse(pinecone_client_version) >= version.parse("3.0.0.dev")


@deprecated(
since="0.0.15", removal="0.2.0", alternative_import="langchain_pinecone.Pinecone"
)
class Pinecone(VectorStore):
"""`Pinecone` vector store.

To use, you should have the ``pinecone-client`` python package installed.

Example:
.. code-block:: python

from langchain_community.vectorstores import Pinecone
from langchain_community.embeddings.openai import OpenAIEmbeddings
import pinecone

# The environment should be the one specified next to the API key
# in your Pinecone console
pinecone.init(api_key="***", environment="...")
index = pinecone.Index("langchain-demo")
embeddings = OpenAIEmbeddings()
vectorstore = Pinecone(index, embeddings, "text")
This version of Pinecone is deprecated. Please use `langchain_pinecone.Pinecone`
instead.
"""

def __init__(
Expand Down
1 change: 1 addition & 0 deletions libs/partners/pinecone/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__
21 changes: 21 additions & 0 deletions libs/partners/pinecone/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 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.
61 changes: 61 additions & 0 deletions libs/partners/pinecone/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
.PHONY: all format lint test tests integration_tests docker_tests help extended_tests

# Default target executed when no arguments are given to make.
all: help

# Define a variable for the test file path.
TEST_FILE ?= tests/unit_tests/

integration_tests: TEST_FILE = tests/integration_tests/

test integration_tests:
poetry run pytest $(TEST_FILE)

tests:
poetry run pytest $(TEST_FILE)


######################
# LINTING AND FORMATTING
######################

# Define a variable for Python and notebook files.
PYTHON_FILES=.
MYPY_CACHE=.mypy_cache
lint format: PYTHON_FILES=.
lint_diff format_diff: PYTHON_FILES=$(shell git diff --relative=libs/partners/pinecone --name-only --diff-filter=d master | grep -E '\.py$$|\.ipynb$$')
lint_package: PYTHON_FILES=langchain_pinecone
lint_tests: PYTHON_FILES=tests
lint_tests: MYPY_CACHE=.mypy_cache_test

lint lint_diff lint_package lint_tests:
poetry run ruff .
poetry run ruff format $(PYTHON_FILES) --diff
poetry run ruff --select I $(PYTHON_FILES)
mkdir $(MYPY_CACHE); poetry run mypy $(PYTHON_FILES) --cache-dir $(MYPY_CACHE)

format format_diff:
poetry run ruff format $(PYTHON_FILES)
poetry run ruff --select I --fix $(PYTHON_FILES)

spell_check:
poetry run codespell --toml pyproject.toml

spell_fix:
poetry run codespell --toml pyproject.toml -w

check_imports: $(shell find langchain_pinecone -name '*.py')
poetry run python ./scripts/check_imports.py $^

######################
# HELP
######################

help:
@echo '----'
@echo 'check_imports - check imports'
@echo 'format - run code formatters'
@echo 'lint - run linters'
@echo 'test - run unit tests'
@echo 'tests - run unit tests'
@echo 'test TEST_FILE=<test_file> - run all tests in file'
27 changes: 27 additions & 0 deletions libs/partners/pinecone/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# langchain-pinecone

This package contains the LangChain integration with Pinecone.

## Installation

```bash
pip install -U langchain-pinecone
```

And you should configure credentials by setting the following environment variables:

- `PINECONE_API_KEY`
- `PINECONE_INDEX_NAME`
- `PINECONE_ENVIRONMENT`

## Usage

The `Pinecone` class exposes the connection to the Pinecone vector store.

```python
from langchain_pinecone import Pinecone

embeddings = ... # use a LangChain Embeddings class

vectorstore = Pinecone(embeddings=embeddings)
```
5 changes: 5 additions & 0 deletions libs/partners/pinecone/langchain_pinecone/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from langchain_pinecone.vectorstores import Pinecone

__all__ = [
"Pinecone",
]
71 changes: 71 additions & 0 deletions libs/partners/pinecone/langchain_pinecone/_utilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from enum import Enum
from typing import List, Union

import numpy as np
import simsimd # type: ignore

Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray]


class DistanceStrategy(str, Enum):
"""Enumerator of the Distance strategies for calculating distances
between vectors."""

EUCLIDEAN_DISTANCE = "EUCLIDEAN_DISTANCE"
MAX_INNER_PRODUCT = "MAX_INNER_PRODUCT"
COSINE = "COSINE"


def maximal_marginal_relevance(
query_embedding: np.ndarray,
embedding_list: list,
lambda_mult: float = 0.5,
k: int = 4,
) -> List[int]:
"""Calculate maximal marginal relevance."""
if min(k, len(embedding_list)) <= 0:
return []
if query_embedding.ndim == 1:
query_embedding = np.expand_dims(query_embedding, axis=0)
similarity_to_query = cosine_similarity(query_embedding, embedding_list)[0]
most_similar = int(np.argmax(similarity_to_query))
idxs = [most_similar]
selected = np.array([embedding_list[most_similar]])
while len(idxs) < min(k, len(embedding_list)):
best_score = -np.inf
idx_to_add = -1
similarity_to_selected = cosine_similarity(embedding_list, selected)
for i, query_score in enumerate(similarity_to_query):
if i in idxs:
continue
redundant_score = max(similarity_to_selected[i])
equation_score = (
lambda_mult * query_score - (1 - lambda_mult) * redundant_score
)
if equation_score > best_score:
best_score = equation_score
idx_to_add = i
idxs.append(idx_to_add)
selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
return idxs


def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
"""Row-wise cosine similarity between two equal-width matrices."""
if len(X) == 0 or len(Y) == 0:
return np.array([])

X = np.array(X)
Y = np.array(Y)
if X.shape[1] != Y.shape[1]:
raise ValueError(
f"Number of columns in X and Y must be the same. X has shape {X.shape} "
f"and Y has shape {Y.shape}."
)

X = np.array(X, dtype=np.float32)
Y = np.array(Y, dtype=np.float32)
Z = 1 - simsimd.cdist(X, Y, metric="cosine")
if isinstance(Z, float):
return np.array([Z])
return Z
Empty file.
Loading
Loading