LangChain-Prolog
A Python library that integrates SWI-Prolog with LangChain. It enables seamless blending of Prolog’s logic programming capabilities into LangChain applications, allowing rule-based reasoning, knowledge representation, and logical inference alongside GenAI models.
Features
- Seamless integration between LangChain and SWI-Prolog
- Use Prolog queries as LangChain's runnables and tools
- Invoke Prolog predicates from LangChain's LLM models, chains and agents
- Support for both synchronous and asynchronous operations
- Comprehensive error handling and logging
- Queries are checked before they run, so an LLM cannot use a Prolog tool to run shell commands or change the database
- Cross-platform support (macOS, Linux, Windows)
Installation
Prerequisites
- Python 3.10 or later
- SWI-Prolog installed on your system
- The following Python libraries will be installed:
langchain1.3.0 or laterjanus-swi1.5.0 or laterpydantic2.7.0 or later
Once SWI-Prolog has been installed, langchain-prolog can be installed using pip:
pip install langchain-prolog
Runnable Interface
The PrologRunnable class allows the generation of langchain runnables that use Prolog rules to generate answers.
Let's use the following set of Prolog rules in the file family.pl:
parent(john, bianca, mary).
parent(john, bianca, michael).
parent(peter, patricia, jennifer).
partner(X, Y) :- parent(X, Y, _).
There are three ways to use a PrologRunnable to query Prolog:
1) Using a Prolog runnable with a full predicate string
from langchain_prolog import PrologConfig, PrologRunnable
config = PrologConfig(rules_file="family.pl")
prolog = PrologRunnable(prolog_config=config)
result = prolog.invoke("partner(X, Y)")
print(result)
We can pass a string representing a single predicate query. The invoke method will return True, False or a list of dictionaries with all the solutions to the query:
[{'X': 'john', 'Y': 'bianca'},
{'X': 'john', 'Y': 'bianca'},
{'X': 'peter', 'Y': 'patricia'}]
2) Using a Prolog runnable with a default predicate
from langchain_prolog import PrologConfig, PrologRunnable
config = PrologConfig(rules_file="family.pl", default_predicate="partner")
prolog = PrologRunnable(prolog_config=config)
result = prolog.invoke("peter, X")
print(result)
When using a default predicate, only the arguments for the predicate are passed to the Prolog runable, as a single string. Following Prolog conventions, uppercase identifiers are variables and lowercase identifiers are values (atoms or strings):
[{'X': 'patricia'}]
3) Using a Prolog runnable with a dictionary and schema validation
from langchain_prolog import PrologConfig, PrologRunnable
schema = PrologRunnable.create_schema("partner", ["man", "woman"])
config = PrologConfig(rules_file="family.pl", query_schema=schema)
prolog = PrologRunnable(prolog_config=config)
result = prolog.invoke({"man": None, "woman": "bianca"})
print(result)
If a schema is defined, we can pass a dictionary using the names of the parameters in the schema as the keys in the dictionary. The values can represent Prolog variables (uppercase first letter) or strings (lower case first letter). A None value is interpreted as a variable and replaced with the key capitalized:
[{'Man': 'john'}, {'Man': 'john'}]
You can also pass a Pydantic object generated with the schema to the invoke method:
args = schema(man='M', woman='W')
result = prolog.invoke(args)
print(result)
Uppercase values are treated as variables:
[{'M': 'john', 'W': 'bianca'},
{'M': 'john', 'W': 'bianca'},
{'M': 'peter', 'W': 'patricia'}]
Tool Interface
The PrologTool class allows the generation of langchain tools that use Prolog rules to generate answers.
See the Runnable Interface section for the conventions on hown to pass variables and values to the Prolog interpreter.
The queries of a tool are written by an LLM, so they are checked before they run: they can call your rules and a set of safe predicates, but not shell/1, assertz/1 and the like. See the Query Safety section.
Let's use the following set of Prolog rules in the file family.pl:
parent(john, bianca, mary).
parent(john, bianca, michael).
parent(peter, patricia, jennifer).
partner(X, Y) :- parent(X, Y, _).
There are two diferent ways to use a PrologTool to query Prolog:
1) Using a Prolog tool with an LLM and function calling
First create the Prolog tool:
from langchain_prolog import PrologConfig, PrologRunnable, PrologTool
schema = PrologRunnable.create_schema("parent", ["man", "woman", "child"])
config = PrologConfig(
rules_file="family.pl",
query_schema=schema,
)
prolog_tool = PrologTool(
prolog_config=config,
name="family_query",
description="""
Query family relationships using Prolog.
parent(X, Y, Z) implies only that Z is a child of X and Y.
Input must be a dictionary like:
{
'man': 'richard',
'woman': 'valery',
'child': None,
}
Use 'None' to indicate a variable that need to be instantiated by Prolog
The query will return:
- 'True': if the relationship 'child' is a child of 'men' and 'women' holds.
- 'False' if the relationship 'child' is a child of 'man' and 'woman' does not holds.
- A list of dictionaries with all the answers to the Prolog query
Do not use double quotes.
""",
)
Then bind it to the LLM model and query the model:
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools([prolog_tool])
messages = [HumanMessage("Who are John's children?")]
response = llm_with_tools.invoke(messages)
messages.append(response)
print(response.tool_calls[0])
The LLM will respond with a tool call request:
{'name': 'family_query',
'args': {'man': 'john', 'woman': None, 'child': None},
'id': 'call_V6NUsJwhF41G9G7q6TBmghR0',
'type': 'tool_call'}
The tool takes this request and queries the Prolog database:
tool_msg = prolog_tool.invoke(response.tool_calls[0])
messages.append(tool_msg)
print(tool_msg)
The tool returns a list with all the solutions for the query:
content='[{"Woman": "bianca", "Child": "mary"}, {"Woman": "bianca", "Child": "michael"}]'
name='family_query'
tool_call_id='call_V6NUsJwhF41G9G7q6TBmghR0'
That we then pass to the LLM:
answer = llm_with_tools.invoke(messages)
print(answer.content)
And the LLM answers the original query using the tool response:
John has two children: Mary and Michael. Their mother is Bianca.
2) Using a Prolog tool with a LangChain agent
First create the Prolog tool:
from langchain_prolog import PrologConfig, PrologRunnable, PrologTool
schema = PrologRunnable.create_schema("parent", ["man", "woman", "child"])
config = PrologConfig(
rules_file="family.pl",
query_schema=schema,
)
prolog_tool = PrologTool(
prolog_config=config,
name="family_query",
description="""
Query family relationships using Prolog.
parent(X, Y, Z) implies only that Z is a child of X and Y.
Input must be a dictionary like:
{
'man': 'richard',
'woman': 'valery',
'child': None,
}
Use 'None' to indicate a variable that need to be instantiated by Prolog
The query will return:
- 'True': if the relationship 'child' is a child of 'men' and 'women' holds.
- 'False' if the relationship 'child' is a child of 'man' and 'woman' does not holds.
- A list of dictionaries with all the answers to the Prolog query
Do not use double quotes.
""",
)
Then pass it to the agent's constructor:
from langchain.agents import create_agent
llm = ChatOpenAI(model="gpt-4o-mini")
agent_executor = create_agent(
llm,
[prolog_tool],
system_prompt="You are a helpful assistant",
)
The agent takes the query and uses the Prolog tool if needed:
answer = agent_executor.invoke({"messages": [("human", "Who are John's children?")]})
print(answer["messages"][-1].content)
The agent receives the tool response and generates the answer:
John has two children: Mary and Michael. Their mother is Bianca.
Query Safety
Prolog is a general programming language: shell/1 runs a command, assertz/1 changes the database and open/3
reads and writes files. A query that reaches the interpreter as text can do any of that, and the query of a
PrologTool is written by an LLM, which can be steered by anything it reads.
So queries are checked before they run. The text is parsed, every goal in it is checked, and the query that runs is generated from the checked term, never copied from the text. A query may call:
- control constructs (
,,;,->,\+) and the meta predicatesfindall,bagof,setof,aggregate_all,forall,onceandignore, whose goal arguments are checked in turn; - the predicates defined by your rules files and the files they
includeor consult, which are trusted; a rules file that is a module offers its exported predicates. A library that a rules file loads withuse_moduleis not trusted: your rules may use it, but queries may not, wherever the library is installed; - a fixed set of predicates that only compute: unification and comparison, arithmetic, type checks and the usual list,
atom and string predicates (
member/2,append/3,length/2,atom_length/2,sub_atom/5and the like); - the predicates you list in
allowed_predicates.
Everything else is refused with a PrologQueryNotAllowedError, which is a PrologRuntimeError. That includes
module-qualified goals (user:shell(ls)), goals that are not known until run time (call/1, an unbound variable),
directives, clauses and anything after the first term. With a schema, a value cannot add goals or arguments: the query
must be one call of the schema predicate with one argument per field.
from langchain_prolog import PrologConfig, PrologRunnable
prolog = PrologRunnable(PrologConfig(rules_file="family.pl"))
prolog.invoke("shell('rm -rf ~')")
PrologQueryNotAllowedError: Prolog execution error: query not allowed: Predicate shell/1 is not allowed in queries
Your rules are not checked: shell/1 inside a rule works, so a rule can offer a controlled version of something the
queries may not do.
Allowing more predicates
List extra predicates as name/arity:
config = PrologConfig(rules_file="family.pl", allowed_predicates=["format/2"])
Allow only predicates that cannot hurt when an LLM picks their arguments.
Turning the check off
unrestricted_queries=True skips the check. Use it only when every query comes from your own code, and never for a
PrologTool that an LLM drives. A warning is logged when it is on.
What the check does not cover
- Resource use.
between(1, inf, X), fail,length(L, N)with both unbound and huge arithmetic all run until they finish. Run untrusted queries in a process with limits on time and memory. - Your rules. A rule that calls one of its own arguments (
call/N,assertz/1,shell/1) hands that power to every query that can reach it, so write rules for queries you do not control the way you would write a public API. - A shared interpreter. All runnables in a process share one Prolog database, so a query can call the predicates of any rules file loaded in the process, not only its own.
Metadata
Release files for langchain-prolog 2.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| langchain_prolog-2.0.0.tar.gz | 23.4 kB | Without provenance | Details for langchain_prolog-2.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| langchain_prolog-2.0.0-py3-none-any.whl | Python 3 | none | any | Details for langchain_prolog-2.0.0-py3-none-any.whl |
Total release size: 48.5 kB
Release files / langchain_prolog-2.0.0.tar.gz
| Download URL | langchain_prolog-2.0.0.tar.gz |
|---|---|
| Size | 23.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ab54af0c8bc32902d66edeb096b8ae253882e313d74fd6c3e25daf74fd9a1133
|
|
BLAKE2b-256 checksum How to use checksums |
a630b18a41eaf9e8767d26c2897cfe70a2a7a88c2fdda38578a71c674f9a62c8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / langchain_prolog-2.0.0-py3-none-any.whl
| Download URL | langchain_prolog-2.0.0-py3-none-any.whl |
|---|---|
| Size | 25.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
826902f15c5d67aa5a740dfed0d9b05e168963007fa35370f6c3722e1cfd6d62
|
|
BLAKE2b-256 checksum How to use checksums |
0b75e2bca87d4a689addcf3ec251007c7a7740e06c82fd3c61b467922f761ed5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for langchain-prolog 2.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.