langchain-ydb


Namelangchain-ydb JSON
Version 0.0.6 PyPI version JSON
download
home_pageNone
SummaryAn integration package connecting YDB and LangChain
upload_time2025-08-07 11:20:05
maintainerNone
docs_urlNone
authorNone
requires_python<4.0,>=3.9
licenseNone
keywords ydb langchain database ai
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # langchain-ydb
---
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ydb-platform/langchain-ydb/blob/main/LICENSE)
[![PyPI version](https://badge.fury.io/py/langchain-ydb.svg)](https://badge.fury.io/py/langchain-ydb)
[![Functional tests](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml)
[![Lint checks](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml)

LangChain's YDB integration (langchain-ydb) provides vector capabilities for working with [YDB](https://ydb.tech/).

## Getting Started

### Setting Up YDB

Launch a YDB Docker container with:

```shell
docker run -d -p 2136:2136 --name ydb-langchain -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:trunk
```

### Installing the Package

Install `langchain-ydb` package with:

```bash
pip install -U langchain-ydb
```

VectorStore works along with an embedding model, here using `langchain-openai` as example.

```shell
pip install langchain-openai
export OPENAI_API_KEY=...
```

## Work with YDB Vector Store

### Creating a Vector Store

```python
from langchain_openai import OpenAIEmbeddings
from langchain_ydb.vectorstores import YDB, YDBSearchStrategy, YDBSettings


settings = YDBSettings(
    host="localhost",
    port=2136,
    database="/local",
    table="ydb_example",
    strategy=YDBSearchStrategy.COSINE_SIMILARITY,
)

vector_store = YDB(
    OpenAIEmbeddings(),
    config=settings,
)
```

#### How to use Credentials

To use `YDB` credentials you have to use `credentials` arg during vector store creation.

There are several ways to use credentials:

**Static Credentials**:

```python
credentials = {"username": "name", "password": "pass"}

vector_store = YDB(embeddings, config=settings, credentials=credentials)
```

**Access Token Credentials**:

```python
credentials = {"token": "zxc123"}

vector_store = YDB(embeddings, config=settings, credentials=credentials)
```

**Service Account Credentials**:

```python
credentials = {
    "service_account_json": {
        "id": "...",
        "service_account_id": "...",
        "created_at": "...",
        "key_algorithm": "...",
        "public_key": "...",
        "private_key": "..."
    }
}

vector_store = YDB(embeddings, config=settings, credentials=credentials)
```

**Credentials Object From YDB SDK**:

Additionally, you can use any credentials that comes with `ydb` package. Example:

```python
import ydb.iam

vector_store = YDB(
    embeddings,
    config=settings,
    credentials=ydb.iam.MetadataUrlCredentials(),
)

```

### Add items to vector store

Once you have created your vector store, you can interact with it by adding and deleting different items.

Prepare documents to work with:

```python
from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
    page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
    metadata={"source": "tweet"},
)

document_2 = Document(
    page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
    metadata={"source": "news"},
)

document_3 = Document(
    page_content="Building an exciting new project with LangChain - come check it out!",
    metadata={"source": "tweet"},
)

document_4 = Document(
    page_content="Robbers broke into the city bank and stole $1 million in cash.",
    metadata={"source": "news"},
)

document_5 = Document(
    page_content="Wow! That was an amazing movie. I can't wait to see it again.",
    metadata={"source": "tweet"},
)

document_6 = Document(
    page_content="Is the new iPhone worth the price? Read this review to find out.",
    metadata={"source": "website"},
)

document_7 = Document(
    page_content="The top 10 soccer players in the world right now.",
    metadata={"source": "website"},
)

document_8 = Document(
    page_content="LangGraph is the best framework for building stateful, agentic applications!",
    metadata={"source": "tweet"},
)

document_9 = Document(
    page_content="The stock market is down 500 points today due to fears of a recession.",
    metadata={"source": "news"},
)

document_10 = Document(
    page_content="I have a bad feeling I am going to get deleted :(",
    metadata={"source": "tweet"},
)

documents = [
    document_1,
    document_2,
    document_3,
    document_4,
    document_5,
    document_6,
    document_7,
    document_8,
    document_9,
    document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]
```

You can add items to your vector store by using the `add_documents` function.

```python
vector_store.add_documents(documents=documents, ids=uuids)
```

### Delete items from vector store

You can delete items from your vector store by ID using the `delete` function.

```python
vector_store.delete(ids=[uuids[-1]])
```

### Query vector store

Once your vector store has been created and relevant documents have been added, you will likely want to query it during the execution of your chain or agent.

#### Query directly

**Similarity search**:

A simple similarity search can be performed as follows:

```python
results = vector_store.similarity_search(
    "LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
```

**Similarity search with score**

You can also perform a search with a score:

```python
results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=3)
for res, score in results:
    print(f"* [SIM={score:.3f}] {res.page_content} [{res.metadata}]")
```

#### Filtering

You can search with filters as described below:

```python
results = vector_store.similarity_search_with_score(
    "What did I eat for breakfast?",
    k=4,
    filter={"source": "tweet"},
)
for res, _ in results:
    print(f"* {res.page_content} [{res.metadata}]")
```

#### Query by turning into retriever

You can also transform the vector store into a retriever for easier usage in your chains.

Here's how to transform your vector store into a retriever and then invoke the retriever with a simple query and filter.

```python
retriever = vector_store.as_retriever(
    search_kwargs={"k": 2},
)
results = retriever.invoke(
    "Stealing from the bank is a crime", filter={"source": "news"}
)
for res in results:
    print(f"* {res.page_content} [{res.metadata}]")
```


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "langchain-ydb",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.9",
    "maintainer_email": null,
    "keywords": "ydb, langchain, database, AI",
    "author": null,
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/24/d1/fcf583393b4d53d583f5e282ecd5a0dbf1c87a537963fbae1a0fa1b03994/langchain_ydb-0.0.6.tar.gz",
    "platform": null,
    "description": "# langchain-ydb\n---\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/ydb-platform/langchain-ydb/blob/main/LICENSE)\n[![PyPI version](https://badge.fury.io/py/langchain-ydb.svg)](https://badge.fury.io/py/langchain-ydb)\n[![Functional tests](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/tests.yml)\n[![Lint checks](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml/badge.svg)](https://github.com/ydb-platform/langchain-ydb/actions/workflows/lint.yml)\n\nLangChain's YDB integration (langchain-ydb) provides vector capabilities for working with [YDB](https://ydb.tech/).\n\n## Getting Started\n\n### Setting Up YDB\n\nLaunch a YDB Docker container with:\n\n```shell\ndocker run -d -p 2136:2136 --name ydb-langchain -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:trunk\n```\n\n### Installing the Package\n\nInstall `langchain-ydb` package with:\n\n```bash\npip install -U langchain-ydb\n```\n\nVectorStore works along with an embedding model, here using `langchain-openai` as example.\n\n```shell\npip install langchain-openai\nexport OPENAI_API_KEY=...\n```\n\n## Work with YDB Vector Store\n\n### Creating a Vector Store\n\n```python\nfrom langchain_openai import OpenAIEmbeddings\nfrom langchain_ydb.vectorstores import YDB, YDBSearchStrategy, YDBSettings\n\n\nsettings = YDBSettings(\n    host=\"localhost\",\n    port=2136,\n    database=\"/local\",\n    table=\"ydb_example\",\n    strategy=YDBSearchStrategy.COSINE_SIMILARITY,\n)\n\nvector_store = YDB(\n    OpenAIEmbeddings(),\n    config=settings,\n)\n```\n\n#### How to use Credentials\n\nTo use `YDB` credentials you have to use `credentials` arg during vector store creation.\n\nThere are several ways to use credentials:\n\n**Static Credentials**:\n\n```python\ncredentials = {\"username\": \"name\", \"password\": \"pass\"}\n\nvector_store = YDB(embeddings, config=settings, credentials=credentials)\n```\n\n**Access Token Credentials**:\n\n```python\ncredentials = {\"token\": \"zxc123\"}\n\nvector_store = YDB(embeddings, config=settings, credentials=credentials)\n```\n\n**Service Account Credentials**:\n\n```python\ncredentials = {\n    \"service_account_json\": {\n        \"id\": \"...\",\n        \"service_account_id\": \"...\",\n        \"created_at\": \"...\",\n        \"key_algorithm\": \"...\",\n        \"public_key\": \"...\",\n        \"private_key\": \"...\"\n    }\n}\n\nvector_store = YDB(embeddings, config=settings, credentials=credentials)\n```\n\n**Credentials Object From YDB SDK**:\n\nAdditionally, you can use any credentials that comes with `ydb` package. Example:\n\n```python\nimport ydb.iam\n\nvector_store = YDB(\n    embeddings,\n    config=settings,\n    credentials=ydb.iam.MetadataUrlCredentials(),\n)\n\n```\n\n### Add items to vector store\n\nOnce you have created your vector store, you can interact with it by adding and deleting different items.\n\nPrepare documents to work with:\n\n```python\nfrom uuid import uuid4\n\nfrom langchain_core.documents import Document\n\ndocument_1 = Document(\n    page_content=\"I had chocalate chip pancakes and scrambled eggs for breakfast this morning.\",\n    metadata={\"source\": \"tweet\"},\n)\n\ndocument_2 = Document(\n    page_content=\"The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.\",\n    metadata={\"source\": \"news\"},\n)\n\ndocument_3 = Document(\n    page_content=\"Building an exciting new project with LangChain - come check it out!\",\n    metadata={\"source\": \"tweet\"},\n)\n\ndocument_4 = Document(\n    page_content=\"Robbers broke into the city bank and stole $1 million in cash.\",\n    metadata={\"source\": \"news\"},\n)\n\ndocument_5 = Document(\n    page_content=\"Wow! That was an amazing movie. I can't wait to see it again.\",\n    metadata={\"source\": \"tweet\"},\n)\n\ndocument_6 = Document(\n    page_content=\"Is the new iPhone worth the price? Read this review to find out.\",\n    metadata={\"source\": \"website\"},\n)\n\ndocument_7 = Document(\n    page_content=\"The top 10 soccer players in the world right now.\",\n    metadata={\"source\": \"website\"},\n)\n\ndocument_8 = Document(\n    page_content=\"LangGraph is the best framework for building stateful, agentic applications!\",\n    metadata={\"source\": \"tweet\"},\n)\n\ndocument_9 = Document(\n    page_content=\"The stock market is down 500 points today due to fears of a recession.\",\n    metadata={\"source\": \"news\"},\n)\n\ndocument_10 = Document(\n    page_content=\"I have a bad feeling I am going to get deleted :(\",\n    metadata={\"source\": \"tweet\"},\n)\n\ndocuments = [\n    document_1,\n    document_2,\n    document_3,\n    document_4,\n    document_5,\n    document_6,\n    document_7,\n    document_8,\n    document_9,\n    document_10,\n]\nuuids = [str(uuid4()) for _ in range(len(documents))]\n```\n\nYou can add items to your vector store by using the `add_documents` function.\n\n```python\nvector_store.add_documents(documents=documents, ids=uuids)\n```\n\n### Delete items from vector store\n\nYou can delete items from your vector store by ID using the `delete` function.\n\n```python\nvector_store.delete(ids=[uuids[-1]])\n```\n\n### Query vector store\n\nOnce your vector store has been created and relevant documents have been added, you will likely want to query it during the execution of your chain or agent.\n\n#### Query directly\n\n**Similarity search**:\n\nA simple similarity search can be performed as follows:\n\n```python\nresults = vector_store.similarity_search(\n    \"LangChain provides abstractions to make working with LLMs easy\", k=2\n)\nfor res in results:\n    print(f\"* {res.page_content} [{res.metadata}]\")\n```\n\n**Similarity search with score**\n\nYou can also perform a search with a score:\n\n```python\nresults = vector_store.similarity_search_with_score(\"Will it be hot tomorrow?\", k=3)\nfor res, score in results:\n    print(f\"* [SIM={score:.3f}] {res.page_content} [{res.metadata}]\")\n```\n\n#### Filtering\n\nYou can search with filters as described below:\n\n```python\nresults = vector_store.similarity_search_with_score(\n    \"What did I eat for breakfast?\",\n    k=4,\n    filter={\"source\": \"tweet\"},\n)\nfor res, _ in results:\n    print(f\"* {res.page_content} [{res.metadata}]\")\n```\n\n#### Query by turning into retriever\n\nYou can also transform the vector store into a retriever for easier usage in your chains.\n\nHere's how to transform your vector store into a retriever and then invoke the retriever with a simple query and filter.\n\n```python\nretriever = vector_store.as_retriever(\n    search_kwargs={\"k\": 2},\n)\nresults = retriever.invoke(\n    \"Stealing from the bank is a crime\", filter={\"source\": \"news\"}\n)\nfor res in results:\n    print(f\"* {res.page_content} [{res.metadata}]\")\n```\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "An integration package connecting YDB and LangChain",
    "version": "0.0.6",
    "project_urls": null,
    "split_keywords": [
        "ydb",
        " langchain",
        " database",
        " ai"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6a83e2f2e6860a878abaa5aab0db2478f2370596a8c2bf8cc9ca74378822f1f7",
                "md5": "1e876e219fd1369a8632d77d673dde5d",
                "sha256": "5943abdfe4d9526ed5d3476eec7389f31de22ff97f97508af4c276c48390e81d"
            },
            "downloads": -1,
            "filename": "langchain_ydb-0.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1e876e219fd1369a8632d77d673dde5d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.9",
            "size": 13678,
            "upload_time": "2025-08-07T11:20:04",
            "upload_time_iso_8601": "2025-08-07T11:20:04.327650Z",
            "url": "https://files.pythonhosted.org/packages/6a/83/e2f2e6860a878abaa5aab0db2478f2370596a8c2bf8cc9ca74378822f1f7/langchain_ydb-0.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "24d1fcf583393b4d53d583f5e282ecd5a0dbf1c87a537963fbae1a0fa1b03994",
                "md5": "873b1a452fb9337f0609a28279be9854",
                "sha256": "b2d4087c54420795b0f7a7e26f045a8b94b6de375039637d91162b6dcad2ff05"
            },
            "downloads": -1,
            "filename": "langchain_ydb-0.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "873b1a452fb9337f0609a28279be9854",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.9",
            "size": 14554,
            "upload_time": "2025-08-07T11:20:05",
            "upload_time_iso_8601": "2025-08-07T11:20:05.376352Z",
            "url": "https://files.pythonhosted.org/packages/24/d1/fcf583393b4d53d583f5e282ecd5a0dbf1c87a537963fbae1a0fa1b03994/langchain_ydb-0.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-07 11:20:05",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "langchain-ydb"
}
        
Elapsed time: 1.00187s