This tutorial will walk you through the fusion between symbolic logic and AI. PySwip is used to embed an embedded Python program. Prolog Knowledge base wrapped in LangChain Tools, then a ReAct style agent. Along the way we create family relationship rules, mathematical functions like factorials, and utility lists, before letting the agent reason, plan and call tools. At the end of setup, we will be able to ask natural language questions, watch as the agent converts them into Prolog queries and stitched together multiple-step answers. We’ll also get structured JSON-backed insight.
You can install Swi-Prolog using!apt get install swiprolog.
!pip install pyswip langchain-google-genai langgraph langchain-core
Installing SWI-Prolog via apt-get, we then install LangChain’s Google GenAI Wrapper, LangGraph and the core LangChain package using pip. This allows us to bridge Prolog logic and our Gemini powered agent. These dependencies have been installed, so we can now code, query and orchestrate reasoning.
Import os
Import Prolog from Pyswip
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage
From langchain_core.tools, import the tool
From langgraph.prebuilt, import create_react_agent
Download json
GOOGLE_API_KEY = "Use Your Own API Key Here"
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0)
Then we load the core stack. This includes PySwip and LangChain for Prolog. LangGraph and LangChain are used for tools, while Gemini 1.5 Flash is needed for LLM. Then we set up the environment variable GOOGLE_API_KEY so that the model could authenticate. We’re ready to receive deterministic and logic-based answers since the LLM is initialized with zero temperature.
class AdvancedPrologInterface:
def __init__(self):
self.prolog = Prolog()
self._load_knowledge_base()
def _load_knowledge_base(self):
"""Load comprehensive Prolog knowledge base"""
Rules = [
"parent(john, mary, alice)",
"parent(john, mary, bob)",
"parent(bob, susan, charlie)",
"parent(alice, david, emma)",
"parent(charlie, lisa, frank)",
"male(john)", "male(bob)", "male(david)", "male(charlie)", "male(frank)",
"female(mary)", "female(alice)", "female(susan)", "female(emma)", "female(lisa)",
"grandparent(X, Z) :- parent(X, _, Y), parent(Y, _, Z)",
"sibling(X, Y) :- parent(P1, P2, X), parent(P1, P2, Y), X = Y",
"uncle(X, Y) :- sibling(X, Z), parent(Z, _, Y), male(X)",
"aunt(X, Y) :- sibling(X, Z), parent(Z, _, Y), female(X)",
"cousin(X, Y) :- parent(P1, _, X), parent(P2, _, Y), sibling(P1, P2)",
"factorial(0, 1)",
"factorial(N, F) :- N > 0, N1 is N - 1, factorial(N1, F1), F is N * F1",
"list_member(X, [X|_])",
"list_member(X, [_|T]) :- list_member(X, T)",
"list_length([], 0)",
"list_length([_|T], N) :- list_length(T, N1), N is N1 + 1",
"animal(dog)", "animal(cat)", "animal(whale)", "animal(eagle)",
"mammal(dog)", "mammal(cat)", "mammal(whale)",
"bird(eagle)", "bird(sparrow)",
"can_fly(eagle)", "can_fly(sparrow)",
"can_swim(whale)", "can_swim(fish)",
"aquatic_mammal(X) :- mammal(X), can_swim(X)"
]
For rule in the rules
try:
self.prolog.assertz(rule)
The Exception is e.
print(f"Warning: Could not assert rule '{rule}': {e}")
def query(self, query_string):
"""Execute Prolog query and return results"""
try:
results = list(self.prolog.query(query_string))
return results if results else [{"result": "No solutions found"}]
Except as follows:
You can return to your original language by clicking here. [{"error": f"Query failed: {str(e)}"}]
We wrap SWI-Prolog in an AdvancedPrologInterface, load a rich rule/fact base on init, and assert each clause safely. Next, we reveal a query.() This method runs any Prolog goals and returns JSON results.
prolog_interface = AdvancedPrologInterface()
@tool
def family_relationships(query: str) -> str:
"""
Use Prolog to query family relations.
Examples: 'parent(john, mary, X)', 'sibling(X, Y)', 'grandparent(X, charlie)'
"""
results = prolog_interface.query(query)
return json.dumps(results, indent=2)
@tool
def mathematical_operations(operation: str, number: int) -> str:
"""
Use Prolog to perform mathematical operations.
Factorial: Supported Operations
Example: operation='factorial', number=5
"""
If Operation == "factorial":
query = f"factorial({number}, Result)"
results = prolog_interface.query(query)
return json.dumps(results, indent=2)
else:
return json.dumps([{"error": f"Operation '{operation}' not supported"}])
@tool
def advanced_queries(query_type: str, entity: str = "") -> str:
"""
Use advanced relationships queries.
Types: 'all_children', 'all_grandchildren', 'all_siblings', 'all_cousins'
"""
queries = {
"all_children":"parent(_, _, {entity})" If else, then entity "parent(_, _, X)",
"All_grandchildren":"grandparent(_, {entity})" if else entity "grandparent(_, X)",
All siblings: F"sibling({entity}, X)" If else, then entity "sibling(X, Y)",
All_cousins:"cousin({entity}, X)" If else, then entity "cousin(X, Y)"
}
if query_type in queries:
results = prolog_interface.query(queries[query_type])
return json.dumps(results, indent=2)
else:
return json.dumps([{"error": f"Query type '{query_type}' not supported"}])
We instantiate AdvancedPrologInterface and then wrap its queries as LangChain tools, such as family_relationships, mathematical_operations, and advanced_queries, so that we can call precise Prolog goals from natural language. The tools are defined so that they format, dispatch, and return the query in a clean JSON.
Tools = [family_relationships, mathematical_operations, advanced_queries]
agent = create_react_agent(llm, tools)
def run_family_analysis():
"""Comprehensive family relationship analysis"""
print("👨👩👧👦 Family Relationship Analysis")
print("=" * 50)
queries = [
"Who are all the parents in the family database?",
"Find all grandparent-grandchild relationships",
"Show me all the siblings in the family",
"Who are John and Mary's children?",
"Calculate the factorial of 6 using Prolog"
]
If i is the first query, then enumerate it."response = agent.invoke"
print(f"n🔍 Query {i}: {query}")
print("-" * 30)
try:
response = agent.invoke({"messages": [("human", query)]})
Answer = Response["messages"][-1].content
print(f"🤖 Response: {answer}")
Exception to the rule:
print(f"❌ Error: {str(e)}")
def demonstrate_complex_reasoning():
"""Show advanced multi-step reasoning"""
print("n🧠 Complex Multi-Step Reasoning")
print("=" * 40)
complex_query = """
Please: I would like a full family tree. Please:
1. List of all Parent-Child Relationships
2. Find all grandparents
3. Search for any aunt/uncle relationships
4. Relationships between cousins
5. Factorial 4 is a math bonus operation.Response = Agent.invoke
"""
print(f"Complex Query: {complex_query}")
print("-" * 40)
try:
response = agent.invoke({"messages": [("human", complex_query)]})
print(f"📋 Comprehensive Analysis:n{response['messages'][-1].content}")
Except Exception As e.
print(f"❌ Error in complex reasoning: {str(e)}")
def interactive_prolog_session():
"""Interactive Prolog knowledge base exploration"""
print("n💬 Interactive Prolog Explorer")
print("Ask about family relationships, math operations, or general queries!")
print("Type 'examples' to see sample queries, 'quit' to exit")
print("-" * 50)
examples = [
"Who are Bob's children?",
"Find all grandparents in the family",
"Calculate factorial of 5",
"Show me all cousin relationships",
"Who are Alice's siblings?"
]
It is True
user_input = input("n🧑 You: ")
if user_input.lower() == 'quit':
print("👋 Goodbye!")
Breaking the Law
User_input.lower() == 'examples':
print("📝 Example queries:")
Example:
print(f" • {ex}")
You can continue readingResponse = Agent.invoke
try:
response = agent.invoke({"messages": [("human", user_input)]})
print(f"🤖 AI: {response['messages'][-1].content}")
Please note that this is not the same as:
print(f"❌ Error: {str(e)}")
We register our three Prolog tools, spin up a ReAct agent around Gemini, and then script helper routines, run_family_analysis, demonstrate_complex_reasoning, and an interactive loop, to fire natural-language queries that the agent translates into Prolog calls. This way, we test simple prompts, multi-step reasoning, and live Q&A, all while keeping the logic layer transparent and debuggable.
Def test_direct_queries():
"""Test direct Prolog queries for verification"""
print("n🔬 Direct Prolog Query Testing")
print("=" * 35)
test_queries = [
("parent(john, mary, X)", "Find John and Mary's children"),
("grandparent(X, charlie)", "Find Charlie's grandparents"),
("sibling(alice, X)", "Find Alice's siblings"),
("factorial(4, X)", "Calculate 4 factorial"),
("cousin(X, Y)", "Find all cousin pairs")
]
for query, description in test_queries:
print(f"n📋 {description}")
print(f"Query: {query}")
results = prolog_interface.query(query)
print(f"Results: {json.dumps(results, indent=2)}")
Def main():
"""Main demonstration runner"""
If GOOGLE_API_KEY== "YOUR_GEMINI_API_KEY_HERE":
print("⚠️ Please set your Gemini API key in Cell 3!")
print("Get it from: https://aistudio.google.com/app/apikey")
Return to the Homepage
print("🚀 Advanced Prolog + Gemini Integration")
print("Using PySwip for stable Prolog integration")
print("=" * 55)
test_direct_queries()
run_family_analysis()
demonstrate_complex_reasoning()
def show_mathematical_capabilities():
"""Demonstrate mathematical reasoning with Prolog"""
print("n🔢 Mathematical Reasoning with Prolog")
print("=" * 40)
math_queries = [
"Calculate factorial of 3, 4, and 5",
"What is the factorial of 7?",
"Show me how factorial calculation works step by step"
]
Math_Queries for Query:Response = Agent.invoke
print(f"n🧮 Math Query: {query}")
try:
response = agent.invoke({"messages": [("human", query)]})
print(f"📊 Result: {response['messages'][-1].content}")
Except Exception As e.
print(f"❌ Error: {str(e)}")
If __name__ is equal to "__main__":
You can also read more about it here.()
show_mathematical_capabilities()
print("n✅ Tutorial completed successfully!")
print("🎯 Key achievements:")
print(" • Integrated PySwip with Gemini AI")
print(" • Created advanced Prolog reasoning tools")
print(" • Demonstrated complex family relationship queries")
print(" • Implemented mathematical operations in Prolog")
print(" • Built interactive AI agent with logical reasoning")
print("n🚀 Try extending with your own Prolog rules and facts!")
Main wiring is done in a mainframe.() to verify our Prolog goals, run the family analysis, and showcase multi-step reasoning, then show_mathematical_capabilities() The emphasis is on factorial questions using natural language. Then we print a summary of the work done so far. This allows us to extend our stack by adding new rules and models.
As a conclusion, we’ve shown how LLMs work well with symbolic reasoning: Prolog provides a guarantee of correctness for logics that are clearly defined, while Gemini is responsible for flexible language interpretation and orchestration. The scaffold is complete, with direct Prolog questions for verification, predicates wrapped in toolkits for agents and demonstration functions for family tree and mathematics analyses. Now that we have a working scaffold, direct Prolog queries for verification, tool-wrapped predicates for agents, and demo functions, we can expand our knowledge base or add other domains such as knowledge graphs, finance rules, games logic, etc. This stack can be exposed via an API or interactive interface, which allows others to experiment with logic-guided AI.
Click here to find out more Full Codes. The researchers are the sole credit holders for this work.
The AI Dev newsletter is read by over 40k+ developers and researchers from NVIDIA and OpenAI. DeepMind and Meta are also included. Microsoft, JP Morgan Chase and Amgen. Aflac and Wells Fargo. [SUBSCRIBE NOW]
Asif Razzaq, CEO of Marktechpost Media Inc. is a visionary engineer and entrepreneur who is dedicated to harnessing Artificial Intelligence’s potential for the social good. Marktechpost is his latest venture, a media platform that focuses on Artificial Intelligence. It is known for providing in-depth news coverage about machine learning, deep learning, and other topics. The content is technically accurate and easy to understand by an audience of all backgrounds. Over 2 million views per month are a testament to the platform’s popularity.

