# Connect with LangChain

Use the `langchain-singlestore` connector to integrate your SingleStore databases with LangChain. This integration enables you to build AI applications and manage documents, embeddings, and chat message history using SingleStore.

Refer to the [langchain-singlestore](https://github.com/singlestore-labs/langchain-singlestore) GitHub repository for the source code and related information.

## Install langchain-singlestore

The `langchain-singlestore` package can be installed using the standard Python package installation process:

```shell
pip install -U langchain-singlestore
```

If the package is already installed, this command upgrades it to the latest version.

The `langchain-singlestore` package requires `langchain-core`, `singlestoredb` ([SingleStore Python client](https://docs.singlestore.com/db/v9.1/developer-resources/connect-with-application-development-tools/connect-with-python/connect-using-the-singlestore-python-client.md)), and `sqlalchemy`. These dependencies are automatically installed if they are not already present.

## Connect to SingleStore

Specify the connection configuration of your SingleStore deployment either in the constructor argument while instantiating the class or using environment variables.

| Constructor Argument | Environment Variable     | Description                                                                                             |
| -------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------- |
| -                    | `SINGLESTOREDB_URL`      | Connection URL in the following format:`singlestoredb://<username>:<password>@<host>:<port>/<database>` |
| `host`               | `SINGLESTOREDB_HOST`     | IP address or the hostname of theSingleStorecluster.                                                    |
| `port`               | `SINGLESTOREDB_PORT`     | Port of theSingleStorecluster. The default is`3306`.                                                    |
| `user`               | `SINGLESTOREDB_USER`     | Username of theSingleStoredatabase user.                                                                |
| `password`           | `SINGLESTOREDB_PASSWORD` | Password for theSingleStoredatabase user.                                                               |
| `database`           | `SINGLESTOREDB_DATABASE` | Name of theSingleStoredatabase to connect with.                                                         |
| `table_name`         | -                        | Name of the table in the specifiedSingleStoredatabase.                                                  |

For example:

```python
retriever = SingleStoreSQLDatabaseRetriever(
    host="svchost",
    user="s2user",
    password="pa55w0rd",
    database="dbTest",
    table_name="t1"
)
```

## Supported Components

The `langchain-singlestore` package implements LangChain integrations for SingleStore and provides the following core components:

* `SingleStoreChatMessageHistory` 
* `SingleStoreSemanticCache` 
* `SingleStoreVectorStore` 
* `SingleStoreSQLDatabaseRetriever` 
* `SingleStoreLoader` 

## SingleStoreChatMessageHistory

The `SingleStoreChatMessageHistory` class provides support for persistent chat message storage and session management, which is essential for AI applications that need to maintain conversation context across sessions.

Key features:

* Automatic schema creation and management
* Multiple conversation sessions
* Message storage and retrieval
* Integration with LangChain chat models

## SingleStoreSemanticCache

The `SingleStoreSemanticCache` class implements vector-based semantic caching for LLM responses. Instead of exact string matching, it uses embeddings to find semantically similar cached queries.

Key features:

* Vector-based semantic similarity for cached queries
* Reduces LLM API calls for similar queries
* Configurable similarity threshold
* Thread-safe caching operations

## SingleStoreVectorStore

The `SingleStoreVectorStore` class provides support for document storage and retrieval with vector and full-text search indexes. It supports multiple search strategies, advanced metadata filtering, and both vector and text-based indexing.

Key features:

* Hybrid search (using a combination of vector and text indexes)
* Multiple search strategies (`VECTOR_ONLY`, `TEXT_ONLY`, `FILTER_BY_TEXT`, `FILTER_BY_VECTOR`, `WEIGHTED_SUM`)
* Simple and advanced metadata filtering
* Efficient document management (add, delete, update)
* Configurable distance metrics

## SingleStoreSQLDatabaseRetriever

The `SingleStoreSQLDatabaseRetriever` class enables LangChain agents and chains to directly run SQL queries on the SingleStore database and retrieve results as structured documents.

Key features:

* Run SQL queries and convert results to documents
* Flexible row-to-document conversion with custom handlers
* Connection pooling for efficient resource management
* Integration with LangChain agents for database-aware AI
* Support for complex queries with JSON results

## SingleStoreLoader

The `SingleStoreLoader` class provides support for directly loading documents from SingleStore, which enables AI applications to process documents stored in the SingleStore database.

Key features:

* Load documents from any database table
* Configurable content and metadata fields
* Efficient batch processing
* Support for complex metadata structures

## Example

The following is a basic example that shows how to store documents as embeddings in SingleStore and retrieve them via semantic search using LangChain and Hugging Face. For more examples, refer to the [langchain-singlestore](https://github.com/singlestore-labs/langchain-singlestore) GitHub repository.

1. Install the required packages:
   ```shell
   pip install -U langchain langchain-singlestore langchain-huggingface sentence-transformers
   ```

2. Add the following code to **main.py**:
   ```python
   from langchain_huggingface import HuggingFaceEmbeddings
   from langchain_singlestore import SingleStoreVectorStore

   embedding = HuggingFaceEmbeddings(
       model_name="sentence-transformers/all-MiniLM-L6-v2"
   )

   # Connect to SingleStore
   vectorstore = SingleStoreVectorStore(
       host="svchost",       
       port=3306,            
       user="s2user",      
       password="passkey",
       database="dbTest",
       embedding=embedding
   )

   # Sample products
   products = [
       "Wireless noise-cancelling headphones with long battery life.",
       "Smartwatch with heart rate and sleep tracking.",
       "Portable Bluetooth speaker with deep bass.",
       "Ergonomic office chair with lumbar support.",
       "4K UHD monitor for gaming and productivity."
   ]

   # Store products in SingleStore
   vectorstore.add_texts(products)
   print("Products stored in SingleStore.")

   # User interest
   user_query = "I want headphones for running and music"

   # Retrieve top 2 recommended products
   results = vectorstore.similarity_search(user_query, k=2)

   print("\nRecommended products:")
   for  doc in results:
       print("- ", doc.page_content)
   ```

3. Run the code:
   ```shell
   python main.py

   ```
   ```output

   Products stored in SingleStore.

   Recommended products:
   -  Wireless noise-cancelling headphones with long battery life.
   -  Portable Bluetooth speaker with deep bass.
   ```

***

Modified at: March 20, 2026

Source: [/db/v9.1/developer-resources/connect-with-application-development-tools/connect-with-python/connect-with-langchain/](https://docs.singlestore.com/db/v9.1/developer-resources/connect-with-application-development-tools/connect-with-python/connect-with-langchain/)

(An index of the documentation is available at /llms.txt)
