Metadata-Version: 2.4
Name: langchain_intersystems
Version: 1.0.0
Summary: LangChain Integration for InterSystems IRIS
Author-email: InterSystems Corporation <support@intersystems.com>
License-Expression: LicenseRef-InterSystems-External-Repository
Project-URL: Homepage, https://www.intersystems.com/
Project-URL: License, https://www.intersystems.com/IERTU/
Classifier: Development Status :: 5 - Production/Stable
Classifier: Topic :: Database
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: intersystems-irispython~=5.4
Requires-Dist: langchain~=1.0
Requires-Dist: langchain-core~=1.0
Requires-Dist: langchain-mcp-adapters~=0.2
Dynamic: license-file

# LangChain Integration for InterSystems IRIS

`langchain_intersystems` is a LangChain integration for the InterSystems IRIS data platform. It features a vector store, chat models, and MCP clients.

## Requirements

- InterSystems IRIS 2025.1+ (for vector store)
- InterSystems IRIS 2026.3+ (for chat models and MCP clients)
- Python 3.10+

## Vector Store

`langchain_intersystems.IRISVectorStore` is an implementation of a LangChain VectorStore that stores vectorized documents in an InterSystems IRIS database. See the [LangChain VectorStore documentation](https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore) for general usage instructions. See the docstrings in the `IRISVectorStore` class for more per-method details.

An `IRISVectorStore` instance holds a collection of documents in an InterSystems IRIS SQL table. The table layout is an internal implementation detail and may change between versions. Use the Python interface rather than querying or modifying the table directly.

### Example Usage

The following example assumes
- InterSystems IRIS is listening at `localhost:1972`.
- [Ollama](https://ollama.com) is running locally with the `mxbai-embed-large` embedding model installed.
- The `langchain-ollama` package is installed. (Any LangChain [`Embeddings`](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings) implementation can be used instead.)

```python
from langchain_core.documents import Document
from langchain_intersystems import IRISVectorStore, SimilarityMetric
from langchain_ollama import OllamaEmbeddings

vector_store = IRISVectorStore(
    OllamaEmbeddings(model='mxbai-embed-large'),
    connect_args=('localhost', 1972, 'USER', 'username', 'password'),  # change as needed
    collection_name='langchain',
    replace_collection=True,  # drops any existing table; omit to keep existing data
    similarity_metric=SimilarityMetric.COSINE
)

vector_store.add_documents([
    Document(page_content='The cat sat on the mat.', metadata={'animal': 'cat'}),
    Document(page_content='Dogs love to play fetch.', metadata={'animal': 'dog'}),
    Document(page_content='Goldfish swim in a bowl.', metadata={'animal': 'fish'}),
])

for doc in vector_store.similarity_search('Which pet likes to chase a ball?', k=1):
    print(doc.page_content)  # Dogs love to play fetch.

# Filter results by metadata
for doc in vector_store.similarity_search('pets', filter={'animal': 'cat'}):
    print(doc.page_content)  # The cat sat on the mat.
```

### Metadata Limitations

The LangChain [Document](https://reference.langchain.com/python/langchain-core/documents/base/Document) class has a `metadata` field that supports an arbitrary `dict` of key-value pairs. `IRISVectorStore`, however, has stricter requirements and limitations regarding metadata format.

#### Keys
- Keys must have type `str`, contain only alphanumeric characters and underscores, and have a maximum length of `126`. An exception is raised if an invalid key is encountered.
- Keys are normalized to lowercase when stored. Consequently, one document cannot have two metadata keys that differ by case only. An exception is raised if such a document is encountered.

#### Value Types
- `None` values are ignored. For example, `{'key1': 1, 'key2': None}` is treated the same as `{'key1': 1}`. In both cases, a SQL `NULL` value is stored in the backend SQL column corresponding to `'key2'`.
- Supported value types are `str`, `bytes`, `int`, `float`, `bool`, `decimal.Decimal`, `datetime.date`, `datetime.time`, `datetime.datetime`, and `uuid.UUID`. An exception is raised if an unsupported value type is encountered.
- All non-`None` values for a given key must have the same type. For example, an exception is raised if an attempt is made to store a document with metadata `{'key': 1}` and another with metadata `{'key': '1'}`.

#### Value Limits
- `str` and `bytes` values have a maximum length of `1024`. Longer values result in an exception.
- `int` values must be in the range `-9223372036854775808` to `9223372036854775807`. Out-of-range values result in an exception.
- `decimal.Decimal` values must be in the range `decimal.Decimal('-999999999999999999')` to `decimal.Decimal('999999999999999999')`. `decimal.Decimal('NaN')`, `decimal.Decimal('-Infinity')`, and `decimal.Decimal('Infinity')` are invalid. Invalid or out-of-range values result in an exception.
- `decimal.Decimal` values with more than 9 digits after the decimal point are rounded to 9 post-decimal-point digits. Values with more than 18 total digits of precision are rounded to 18 digits. Rounded values result in a warning.

### Metadata Filtering

Similarity search functions (`similarity_search()`, `similarity_search_by_vector()`, `similarity_search_with_score()`, `max_marginal_relevance_search()`, and `max_marginal_relevance_search_by_vector()`) have a `filter` parameter which allows filtering results based on metadata fields using a flexible and composable SQL-inspired syntax. Filters are expressed as nested Python `dict`s that describe logical and comparison operations using the `langchain_intersystems.Predicate` enumeration. Each key represents either:
- a (case-insensitive) **metadata field name** (e.g. `'author'`, `'year'`, `'category'`), or
- a **logical operator** (e.g. `Predicate.AND`, `Predicate.OR`, `Predicate.NOT`).

A value can be:
- a **predicate expression** &mdash; a tuple containing a predicate and its argument(s), e.g. `(Predicate.EQUAL, 'value')` or `(Predicate.IS_NULL,)`.
- a **nested filter** &mdash; additional `dict`(s) of field conditions combined with logical operators.
- a **literal value** &mdash; value used for equality comparison (shorthand for `(Predicate.EQUAL, 'value')`)

The basic structure of a filter is:

```
{ field_name: (predicate, value, [optional_arguments]) }
```

Logical combination:
- Use `Predicate.AND` or `Predicate.OR` as `dict` keys whose values are `list`s of filters.
- Use `Predicate.NOT` with a single filter (`dict`) to negate a condition.
- When a `dict` contains multiple keys, the conditions are implicitly ANDed together.

Predicates can be specified as `Predicate` enum values or their `str` equivalents. The following table summarizes all supported predicates.

| Predicate as `Predicate` enum | Predicate as `str` | IRIS SQL equivalent     |
|-------------------------------|--------------------|-------------------------|
| `AND`                         | `'$and'`           | `AND`                   |
| `OR`                          | `'$or'`            | `OR`                    |
| `NOT`                         | `'$not'`           | `NOT`                   |
| `EQUAL`                       | `'$eq'`            | `= ?`                   |
| `NOT_EQUAL`                   | `'$ne'`            | `!= ?`                  |
| `GREATER_THAN`                | `'$gt'`            | `> ?`                   |
| `GREATER_THAN_OR_EQUAL`       | `'$gte'`           | `>= ?`                  |
| `LESS_THAN`                   | `'$lt'`            | `< ?`                   |
| `LESS_THAN_OR_EQUAL`          | `'$lte'`           | `<= ?`                  |
| `IS_NULL`                     | `'$isnull'`        | `IS NULL`               |
| `IS_NOT_NULL`                 | `'$notnull'`       | `IS NOT NULL`           |
| `BETWEEN`                     | `'$between'`       | `BETWEEN ? AND ?`       |
| `IN`                          | `'$in'`            | `IN (?[,?...])`         |
| `CONTAINS`                    | `'$contains'`      | `[ ?`                   |
| `NOT_CONTAINS`                | `'$ncontains'`     | `NOT[ ?`                |
| `FOLLOWS`                     | `'$follows'`       | `] ?`                   |
| `NOT_FOLLOWS`                 | `'$nfollows'`      | `NOT] ?`                |
| `STARTS_WITH`                 | `'$startswith'`    | `%STARTSWITH ?`         |
| `LIKE`                        | `'$like'`          | `LIKE ? [ESCAPE ?]`     |
| `MATCHES`                     | `'$matches'`       | `%MATCHES ? [ESCAPE ?]` |
| `PATTERN`                     | `'$pattern'`       | `%PATTERN ?`            |

The following examples demonstrate how to use all the predicates.

```python
from langchain_intersystems import Predicate

# key1 metadata field equals 'value1'
{'key1': (Predicate.EQUAL, 'value1')}

# key1 equals 'value1'; uses equivalent string literal instead of Predicate
# enum
{'key1': ('$eq', 'value1')}

# key1 equals 'value1'; uses equivalent shorthand
{'key1': 'value1'}

# key1 equals 'value1' and key2 is greater than 0
{
    'key1': (Predicate.EQUAL, 'value1'),
    'key2': (Predicate.GREATER_THAN, 0)
}

# key1 is greater than or equal to 0 and is less than 5
{
    Predicate.AND: [
        {'key1': (Predicate.GREATER_THAN_OR_EQUAL, 0)},
        {'key1': (Predicate.LESS_THAN, 5)}
    ]
}

# key1 is not equal to 0 or key2 is less than or equal to 5
{
    Predicate.OR: [
        {'key1': (Predicate.NOT_EQUAL, 0)},
        {'key2': (Predicate.LESS_THAN_OR_EQUAL, 5)}
    ]
}

# key1 exists, key2 does not exist, and key3 and key4 do not both exist
{
    'key1': (Predicate.IS_NOT_NULL,),
    'key2': (Predicate.IS_NULL,),
    Predicate.NOT: {
        'key3': (Predicate.IS_NOT_NULL,),
        'key4': (Predicate.IS_NOT_NULL,)
    }
}

# key1 is between 0 and 5, inclusive
{'key1': (Predicate.BETWEEN, 0, 5)}

# key1 is 'value1', 'value2', or 'value3'
{'key1': (Predicate.IN, ['value1', 'value2', 'value3'])}

# key1 contains 'value1' as a substring and key2 does not
{
    'key1': (Predicate.CONTAINS, 'value1'),
    'key2': (Predicate.NOT_CONTAINS, 'value1')
}

# key1 is after 'value1' in collation sequence and key2 is not
{
    'key1': (Predicate.FOLLOWS, 'value1'),
    'key2': (Predicate.NOT_FOLLOWS, 'value1')
}

# key1 starts with 'value1'
{'key1': (Predicate.STARTS_WITH, 'value1')}

# key1 matches the pattern string 'value1' with literals and wildcards, and
# key2 matches the pattern string 'value2' with the backslash escape character.
{
    'key1': (Predicate.LIKE, 'value1'),
    'key2': (Predicate.LIKE, 'value2', '\\')
}

# key1 matches the pattern string 'value1' with literals, wildcards, and
# ranges; and key2 matches the pattern string 'value2' with the backslash
# escape character.
{
    'key1': (Predicate.MATCHES, 'value1'),
    'key2': (Predicate.MATCHES, 'value2', '\\')
}

# key1 matches the pattern string 'value1' with literals, wildcards, and
# character type codes.
{'key1': (Predicate.PATTERN, 'value1')}
```

## Chat Models and MCP Clients

This package can load chat model and MCP server settings from named configurations stored in InterSystems IRIS.

### Chat Models

`init_chat_model(name, conn)` loads the chat model configuration called `name` and returns a [LangChain chat model](https://reference.langchain.com/python/langchain-core/language_models/chat_models/BaseChatModel).

```python
import iris
from langchain_intersystems.chat_models import init_chat_model

conn = iris.connect('localhost', 1972, 'USER', 'username', 'password')  # change as needed
model = init_chat_model('mychatmodel', conn)
```

The LangChain package for the chat model provider must be installed. For example, if `'mychatmodel'` refers to an Ollama model, then the `langchain-ollama` package must be installed.

A chat model configuration can be created in ObjectScript with `##class(%ConfigStore.Configuration).Create("AI", "LLM", "", "mychatmodel", jsonConfig,,,,,, 0)`, where `jsonConfig` contains the chat model configuration in JSON key-value format. Within the configuration, the `"model_provider"` and `"model"` fields are required. Each field in the configuration is passed as a keyword argument to [`langchain.chat_models.init_chat_model()`](https://reference.langchain.com/python/langchain/chat_models/base/init_chat_model), so any parameter it accepts can be used.

For example, the following configuration specifies the `llama3.2` chat model from the Ollama provider.
```json
{
  "model_provider": "ollama",
  "model": "llama3.2"
}
```

### MCP Clients

`init_mcp_client(names, conn)` loads a list of MCP server configurations and returns a [`MultiServerMCPClient`](https://reference.langchain.com/python/langchain-mcp-adapters/client/MultiServerMCPClient) configured for all of them.

```python
import iris
from langchain_intersystems import init_mcp_client

conn = iris.connect('localhost', 1972, 'USER', 'username', 'password')  # change as needed
client = init_mcp_client(['mymcpserver1', 'mymcpserver2'], conn)
```

An MCP server configuration named `'mymcpserver'` can be created in ObjectScript with `##class(%ConfigStore.Configuration).Create("AI", "MCP", "", "mymcpserver", jsonConfig,,,,,, 0)`, where `jsonConfig` contains the MCP server configuration in JSON key-value format. Supported fields in `jsonConfig` are defined by the [`langchain_mcp_adapters.sessions.Connection` dictionary](https://reference.langchain.com/python/langchain-mcp-adapters/sessions/Connection).

For example, the following MCP server configuration specifies a local server that uses the HTTP transport.
```json
{
  "transport": "http",
  "url": "http://localhost:8000/mcp"
}
```

### Example Usage

Assume that an InterSystems IRIS instance contains the configurations for
- a chat model named `'mychatmodel'`,
- an MCP server named `'addition'` which provides a tool to do addition, and
- an MCP server named `'multiplication'` which provides a tool to do multiplication

This example creates an agent that uses the chat model along with the tools from the MCP servers.

```python
import asyncio
import pprint

import iris
from langchain.agents import create_agent
from langchain_intersystems import init_mcp_client
from langchain_intersystems.chat_models import init_chat_model

conn = iris.connect('localhost', 1972, 'USER', 'username', 'password')  # change as needed
model = init_chat_model('mychatmodel', conn)
client = init_mcp_client(['addition', 'multiplication'], conn)


async def main():
    agent = create_agent(model, await client.get_tools())
    questions = ['What is 3+5?', 'What is 3x5?']
    for question in questions:
        print(question)
        pprint.pprint(await agent.ainvoke({'messages': [{'role': 'user', 'content': question}]}))


asyncio.run(main())
```

## Retrieval-Augmented Generation

An `IRISVectorStore` can be turned into a [retriever](https://reference.langchain.com/python/langchain-core/retrievers/BaseRetriever) with [`as_retriever()`](https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore/as_retriever), which can then be wrapped in a tool for an agent. A chat model can then use the tool to answer questions based on documents stored in InterSystems IRIS.

The following example assumes
- the prerequisites of the [vector store example](#example-usage) are met, and
- InterSystems IRIS contains a chat model configuration named `'mychatmodel'` (see [Chat Models](#chat-models)).

```python
import iris
from langchain.agents import create_agent
from langchain_core.documents import Document
from langchain_core.tools import tool
from langchain_intersystems import IRISVectorStore
from langchain_intersystems.chat_models import init_chat_model
from langchain_ollama import OllamaEmbeddings

conn = iris.connect('localhost', 1972, 'USER', 'username', 'password')  # change as needed
vector_store = IRISVectorStore(
    OllamaEmbeddings(model='mxbai-embed-large'),
    connection=conn,
    collection_name='langchain',
    replace_collection=True,  # drops any existing table; omit to keep existing data
)
vector_store.add_documents([
    Document(page_content='The cat sat on the mat.', metadata={'animal': 'cat'}),
    Document(page_content='Dogs love to play fetch.', metadata={'animal': 'dog'}),
    Document(page_content='Goldfish swim in a bowl.', metadata={'animal': 'fish'}),
])

# as_retriever() accepts the same search options as the similarity search
# methods. For example, search_kwargs={'filter': {'animal': 'dog'}} applies a
# metadata filter, and search_type='mmr' uses maximal marginal relevance
# search.
retriever = vector_store.as_retriever(search_kwargs={'k': 2})


@tool
def search_pet_facts(query: str) -> str:
    """Search the knowledge base for facts about pets."""
    return '\n\n'.join(doc.page_content for doc in retriever.invoke(query))


model = init_chat_model('mychatmodel', conn)
agent = create_agent(
    model,
    [search_pet_facts],
    system_prompt='Answer questions using the search_pet_facts tool.',
)
result = agent.invoke({'messages': [{'role': 'user', 'content': 'Which pet likes to chase a ball?'}]})
print(result['messages'][-1].content)  # Example output: Dogs, which love to play fetch.
```
