On this tutorial, we’re strolling by a hands-on fusion of symbolic logic and generative AI. We arrange PySwip to embed a Prolog data base, wrap its predicates as LangChain instruments, after which wire every part right into a ReAct-style agent. Alongside the way in which, we’re crafting family-relationship guidelines, mathematical predicates like factorial, and listing utilities, then letting the agent plan, name instruments, and purpose over the outcomes. By the tip of the setup, we will challenge natural-language questions and watch the agent translate them into exact Prolog queries, sew collectively multi-step solutions, and return structured JSON-backed insights.
!apt-get set up swi-prolog -y
!pip set up pyswip langchain-google-genai langgraph langchain-core
We set up SWI-Prolog with apt-get after which add pyswip, LangChain’s Google GenAI wrapper, LangGraph, and core LangChain packages by way of pip so we will bridge Prolog logic with our Gemini-powered agent. With these dependencies in place, we’re able to code, question, and orchestrate reasoning finish to finish.
import os
from pyswip import Prolog
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage
from langchain_core.instruments import device
from langgraph.prebuilt import create_react_agent
import json
GOOGLE_API_KEY = "Use Your Personal API Key Right here"
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
llm = ChatGoogleGenerativeAI(mannequin="gemini-1.5-flash", temperature=0)
We load our core stack, together with PySwip for Prolog, LangChain and LangGraph for tooling, and Gemini 1.5 Flash for LLM energy. We then set the GOOGLE_API_KEY atmosphere variable so the mannequin can authenticate. With the LLM initialized at zero temperature, we’re primed to get deterministic, logic-grounded solutions from our agent.
class AdvancedPrologInterface:
def __init__(self):
self.prolog = Prolog()
self._load_knowledge_base()
def _load_knowledge_base(self):
"""Load complete Prolog data base"""
guidelines = [
"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(canine)", "animal(cat)", "animal(whale)", "animal(eagle)",
"mammal(canine)", "mammal(cat)", "mammal(whale)",
"chicken(eagle)", "chicken(sparrow)",
"can_fly(eagle)", "can_fly(sparrow)",
"can_swim(whale)", "can_swim(fish)",
"aquatic_mammal(X) :- mammal(X), can_swim(X)"
]
for rule in guidelines:
attempt:
self.prolog.assertz(rule)
besides Exception as e:
print(f"Warning: Couldn't assert rule '{rule}': {e}")
def question(self, query_string):
"""Execute Prolog question and return outcomes"""
attempt:
outcomes = listing(self.prolog.question(query_string))
return outcomes if outcomes else [{"result": "No solutions found"}]
besides Exception as e:
return [{"error": f"Query failed: {str(e)}"}]
We wrap SWI-Prolog in an AdvancedPrologInterface, load a wealthy rule/reality base on init, and assert every clause safely. We then expose a question() technique that runs any Prolog objective and returns JSON-friendly outcomes (or a transparent error/no-solution message), permitting us to drive logic queries immediately from Python.
prolog_interface = AdvancedPrologInterface()
@device
def family_relationships(question: str) -> str:
"""
Question household relationships in Prolog format.
Examples: 'father or mother(john, mary, X)', 'sibling(X, Y)', 'grandparent(X, charlie)'
"""
outcomes = prolog_interface.question(question)
return json.dumps(outcomes, indent=2)
@device
def mathematical_operations(operation: str, quantity: int) -> str:
"""
Carry out mathematical operations utilizing Prolog.
Supported operations: 'factorial'
Instance: operation='factorial', quantity=5
"""
if operation == "factorial":
question = f"factorial({quantity}, Outcome)"
outcomes = prolog_interface.question(question)
return json.dumps(outcomes, indent=2)
else:
return json.dumps([{"error": f"Operation '{operation}' not supported"}])
@device
def advanced_queries(query_type: str, entity: str = "") -> str:
"""
Carry out superior relationship queries.
Sorts: 'all_children', 'all_grandchildren', 'all_siblings', 'all_cousins'
"""
queries = {
'all_children': f"father or mother(_, _, {entity})" if entity else "father or mother(_, _, X)",
'all_grandchildren': f"grandparent(_, {entity})" if entity else "grandparent(_, X)",
'all_siblings': f"sibling({entity}, X)" if entity else "sibling(X, Y)",
'all_cousins': f"cousin({entity}, X)" if entity else "cousin(X, Y)"
}
if query_type in queries:
outcomes = prolog_interface.question(queries[query_type])
return json.dumps(outcomes, indent=2)
else:
return json.dumps([{"error": f"Query type '{query_type}' not supported"}])
We instantiate AdvancedPrologInterface after which wrap its queries as LangChain instruments, comparable to family_relationships, mathematical_operations, and advanced_queries, in order that we will name exact Prolog targets from pure language. We outline every device to format and dispatch the fitting question (comparable to factorial/2 or cousin lookups) and return clear JSON, permitting our agent to orchestrate logic calls seamlessly.
instruments = [family_relationships, mathematical_operations, advanced_queries]
agent = create_react_agent(llm, instruments)
def run_family_analysis():
"""Complete household relationship evaluation"""
print("👨👩👧👦 Household Relationship Evaluation")
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"
]
for i, question in enumerate(queries, 1):
print(f"n🔍 Question {i}: {question}")
print("-" * 30)
attempt:
response = agent.invoke({"messages": [("human", query)]})
reply = response["messages"][-1].content material
print(f"🤖 Response: {reply}")
besides Exception as e:
print(f"❌ Error: {str(e)}")
def demonstrate_complex_reasoning():
"""Present superior multi-step reasoning"""
print("n🧠 Advanced Multi-Step Reasoning")
print("=" * 40)
complex_query = """
I need a full household tree evaluation. Please:
1. Checklist all parent-child relationships
2. Establish all grandparent relationships
3. Discover any uncle/aunt relationships
4. Present cousin relationships
5. Calculate factorial of 4 as a bonus math operation
"""
print(f"Advanced Question: {complex_query}")
print("-" * 40)
attempt:
response = agent.invoke({"messages": [("human", complex_query)]})
print(f"📋 Complete Evaluation:n{response['messages'][-1].content material}")
besides Exception as e:
print(f"❌ Error in advanced reasoning: {str(e)}")
def interactive_prolog_session():
"""Interactive Prolog data base exploration"""
print("n💬 Interactive Prolog Explorer")
print("Ask about household relationships, math operations, or common queries!")
print("Kind 'examples' to see pattern queries, 'stop' 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?"
]
whereas True:
user_input = enter("n🧑 You: ")
if user_input.decrease() == 'stop':
print("👋 Goodbye!")
break
elif user_input.decrease() == 'examples':
print("📝 Instance queries:")
for ex in examples:
print(f" • {ex}")
proceed
attempt:
response = agent.invoke({"messages": [("human", user_input)]})
print(f"🤖 AI: {response['messages'][-1].content material}")
besides Exception as e:
print(f"❌ Error: {str(e)}")
We register our three Prolog instruments, spin up a ReAct agent round Gemini, after which script helper routines, run_family_analysis, demonstrate_complex_reasoning, and an interactive loop, to fireplace natural-language queries that the agent interprets into Prolog calls. This manner, we check easy prompts, multi-step reasoning, and stay Q&A, all whereas conserving the logic layer clear and debuggable.
def test_direct_queries():
"""Take a look at direct Prolog queries for verification"""
print("n🔬 Direct Prolog Question 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 question, description in test_queries:
print(f"n📋 {description}")
print(f"Question: {question}")
outcomes = prolog_interface.question(question)
print(f"Outcomes: {json.dumps(outcomes, indent=2)}")
def principal():
"""Primary 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
print("🚀 Superior Prolog + Gemini Integration")
print("Utilizing PySwip for steady Prolog integration")
print("=" * 55)
test_direct_queries()
run_family_analysis()
demonstrate_complex_reasoning()
def show_mathematical_capabilities():
"""Exhibit 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"
]
for question in math_queries:
print(f"n🧮 Math Question: {question}")
attempt:
response = agent.invoke({"messages": [("human", query)]})
print(f"📊 Outcome: {response['messages'][-1].content material}")
besides Exception as e:
print(f"❌ Error: {str(e)}")
if __name__ == "__main__":
principal()
show_mathematical_capabilities()
print("n✅ Tutorial accomplished efficiently!")
print("🎯 Key achievements:")
print(" • Built-in PySwip with Gemini AI")
print(" • Created superior Prolog reasoning instruments")
print(" • Demonstrated advanced household relationship queries")
print(" • Applied mathematical operations in Prolog")
print(" • Constructed interactive AI agent with logical reasoning")
print("n🚀 Strive extending with your personal Prolog guidelines and information!")
We wire every part collectively in principal() to confirm our Prolog targets, run the household evaluation, and showcase multi-step reasoning, then show_mathematical_capabilities() stresses factorial queries from pure language. We conclude by printing a fast recap of what we’ve constructed thus far, permitting us to confidently prolong the stack with new guidelines or swap fashions subsequent.
In conclusion, we now have demonstrated that symbolic reasoning and LLMs complement one another superbly: Prolog ensures correctness on well-defined logic, whereas Gemini handles versatile language understanding and orchestration. We’re leaving with a working scaffold, direct Prolog queries for verification, tool-wrapped predicates for brokers, and demo features for advanced household tree and mathematical analyses. From right here, we’re able to develop the data base, add new domains (comparable to finance guidelines, sport logic, and data graphs), or swap in numerous LLMs. We’re additionally positioned to show this stack by way of an interactive UI or API, permitting others to discover logic-guided AI in real-time.
Take a look at the Full Codes. All credit score for this analysis goes to the researchers of this undertaking.
Meet the AI Dev E-newsletter learn by 40k+ Devs and Researchers from NVIDIA, OpenAI, DeepMind, Meta, Microsoft, JP Morgan Chase, Amgen, Aflac, Wells Fargo and 100s extra [SUBSCRIBE NOW]
Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its reputation amongst audiences.