Skip to main content

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 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 is running locally with the mxbai-embed-large embedding model installed.
  • The langchain-ollama package is installed. (Any LangChain Embeddings implementation can be used instead.)
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 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 dicts 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 — a tuple containing a predicate and its argument(s), e.g. (Predicate.EQUAL, 'value') or (Predicate.IS_NULL,).
  • a nested filter — additional dict(s) of field conditions combined with logical operators.
  • a literal value — 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 lists 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.

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.

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(), so any parameter it accepts can be used.

For example, the following configuration specifies the llama3.2 chat model from the Ollama provider.

{
  "model_provider": "ollama",
  "model": "llama3.2"
}

MCP Clients

init_mcp_client(names, conn) loads a list of MCP server configurations and returns a MultiServerMCPClient configured for all of them.

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.

For example, the following MCP server configuration specifies a local server that uses the HTTP transport.

{
  "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.

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 with 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

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.

Metadata

Release files for langchain-intersystems 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for langchain-intersystems 1.0.0
File Interpreter ABI Platform Actions
langchain_intersystems-1.0.0-py3-none-any.whl Python 3 none any Details for langchain_intersystems-1.0.0-py3-none-any.whl

Release files / langchain_intersystems-1.0.0-py3-none-any.whl

Download URL langchain_intersystems-1.0.0-py3-none-any.whl
Size 19.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7ddc5a35143a0ccf86472c59cc7e5b1045a707f620cd92ea86f2669811f45463
BLAKE2b-256 checksum
How to use checksums
e15ecd3de50683d0a7135d47623ce2089c99db0ee0579649b36957abc83e97a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for langchain-intersystems 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page