Site icon Next Business 24

A Coding Info To Assemble A System-Calling ReAct Agent Fusing Prolog Logic With Gemini And LangGraph

A Coding Info To Assemble A System-Calling ReAct Agent Fusing Prolog Logic With Gemini And LangGraph


On this tutorial, we’re strolling by way of a hands-on fusion of symbolic logic and generative AI. We organize PySwip to embed a Prolog information base, wrap its predicates as LangChain devices, after which wire all of the issues proper right into a ReAct-style agent. Alongside one of the best ways, we’re crafting family-relationship tips, mathematical predicates like factorial, and guidelines utilities, then letting the agent plan, title devices, and trigger over the outcomes. By the tip of the setup, we are going to problem natural-language questions and watch the agent translate them into actual Prolog queries, sew collectively multi-step options, and return structured JSON-backed insights.

!apt-get arrange swi-prolog -y
!pip arrange pyswip langchain-google-genai langgraph langchain-core

We arrange SWI-Prolog with apt-get after which add pyswip, LangChain’s Google GenAI wrapper, LangGraph, and core LangChain packages by means of pip so we are going to bridge Prolog logic with our Gemini-powered agent. With these dependencies in place, we’re capable of code, query, and orchestrate reasoning end to complete.

import os
from pyswip import Prolog
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage
from langchain_core.devices import instrument
from langgraph.prebuilt import create_react_agent
import json


GOOGLE_API_KEY = "Use Your Private API Key Proper right here"
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY


llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0)

We load our core stack, along with PySwip for Prolog, LangChain and LangGraph for tooling, and Gemini 1.5 Flash for LLM vitality. We then set the GOOGLE_API_KEY setting variable so the model can authenticate. With the LLM initialized at zero temperature, we’re primed to get deterministic, logic-grounded options from our agent.

class AdvancedPrologInterface:
   def __init__(self):
       self.prolog = Prolog()
       self._load_knowledge_base()
  
   def _load_knowledge_base(self):
       """Load full Prolog information base"""
       tips = [
           "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)",
           "fowl(eagle)", "fowl(sparrow)",
           "can_fly(eagle)", "can_fly(sparrow)",
           "can_swim(whale)", "can_swim(fish)",
           "aquatic_mammal(X) :- mammal(X), can_swim(X)"
       ]
      
       for rule in tips:
           attempt:
               self.prolog.assertz(rule)
           in addition to Exception as e:
               print(f"Warning: Could not assert rule '{rule}': {e}")
  
   def query(self, query_string):
       """Execute Prolog query and return outcomes"""
       attempt:
           outcomes = guidelines(self.prolog.query(query_string))
           return outcomes if outcomes else [{"result": "No solutions found"}]
       in addition to Exception as e:
           return [{"error": f"Query failed: {str(e)}"}]

We wrap SWI-Prolog in an AdvancedPrologInterface, load a rich rule/actuality base on init, and assert each clause safely. We then expose a query() methodology that runs any Prolog goal and returns JSON-friendly outcomes (or a clear error/no-solution message), allowing us to drive logic queries straight from Python.

prolog_interface = AdvancedPrologInterface()


@instrument
def family_relationships(query: str) -> str:
   """
   Query family relationships in Prolog format.
   Examples: 'guardian(john, mary, X)', 'sibling(X, Y)', 'grandparent(X, charlie)'
   """
   outcomes = prolog_interface.query(query)
   return json.dumps(outcomes, indent=2)


@instrument
def mathematical_operations(operation: str, amount: int) -> str:
   """
   Perform mathematical operations using Prolog.
   Supported operations: 'factorial'
   Occasion: operation='factorial', amount=5
   """
   if operation == "factorial":
       query = f"factorial({amount}, Consequence)"
       outcomes = prolog_interface.query(query)
       return json.dumps(outcomes, indent=2)
   else:
       return json.dumps([{"error": f"Operation '{operation}' not supported"}])


@instrument
def advanced_queries(query_type: str, entity: str = "") -> str:
   """
   Perform superior relationship queries.
   Kinds: 'all_children', 'all_grandchildren', 'all_siblings', 'all_cousins'
   """
   queries = {
       'all_children': f"guardian(_, _, {entity})" if entity else "guardian(_, _, 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.query(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 devices, paying homage to family_relationships, mathematical_operations, and advanced_queries, so as that we’ll title actual Prolog goals from pure language. We define each instrument to format and dispatch the correct query (paying homage to factorial/2 or cousin lookups) and return clear JSON, allowing our agent to orchestrate logic calls seamlessly.

devices = [family_relationships, mathematical_operations, advanced_queries]
agent = create_react_agent(llm, devices)


def run_family_analysis():
   """Full 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"
   ]
  
   for i, query in enumerate(queries, 1):
       print(f"n🔍 Query {i}: {query}")
       print("-" * 30)
      
       attempt:
           response = agent.invoke({"messages": [("human", query)]})
           reply = response["messages"][-1].content material materials
           print(f"🤖 Response: {reply}")
       in addition to Exception as e:
           print(f"❌ Error: {str(e)}")


def demonstrate_complex_reasoning():
   """Current superior multi-step reasoning"""
   print("n🧠 Superior Multi-Step Reasoning")
   print("=" * 40)
  
   complex_query = """
   I would like a full family tree analysis. Please:
   1. Guidelines all parent-child relationships
   2. Decide all grandparent relationships 
   3. Uncover any uncle/aunt relationships
   4. Current cousin relationships
   5. Calculate factorial of 4 as a bonus math operation
   """
  
   print(f"Superior Query: {complex_query}")
   print("-" * 40)
  
   attempt:
       response = agent.invoke({"messages": [("human", complex_query)]})
       print(f"📋 Full Analysis:n{response['messages'][-1].content material materials}")
   in addition to Exception as e:
       print(f"❌ Error in difficult reasoning: {str(e)}")


def interactive_prolog_session():
   """Interactive Prolog information base exploration"""
   print("n💬 Interactive Prolog Explorer")
   print("Ask about family relationships, math operations, or frequent queries!")
   print("Type 'examples' to see sample queries, 'hand over' 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.lower() == 'hand over':
           print("👋 Goodbye!")
           break
       elif user_input.lower() == 'examples':
           print("📝 Occasion 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 materials}")
       in addition to Exception as e:
           print(f"❌ Error: {str(e)}")

We register our three Prolog devices, spin up a ReAct agent spherical Gemini, after which script helper routines, run_family_analysis, demonstrate_complex_reasoning, and an interactive loop, to fire natural-language queries that the agent interprets into Prolog calls. This style, we check out straightforward prompts, multi-step reasoning, and reside Q&A, all whereas sustaining the logic layer clear and debuggable.

def test_direct_queries():
   """Examine 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}")
       outcomes = prolog_interface.query(query)
       print(f"Outcomes: {json.dumps(outcomes, indent=2)}")




def principal():
   """Principal 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("Using PySwip for regular 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 query in math_queries:
       print(f"n🧮 Math Query: {query}")
       attempt:
           response = agent.invoke({"messages": [("human", query)]})
           print(f"📊 Consequence: {response['messages'][-1].content material materials}")
       in addition to Exception as e:
           print(f"❌ Error: {str(e)}")


if __name__ == "__main__":
   principal()
   show_mathematical_capabilities()
  
   print("n✅ Tutorial completed effectively!")
   print("🎯 Key achievements:")
   print("  • Constructed-in PySwip with Gemini AI")
   print("  • Created superior Prolog reasoning devices")
   print("  • Demonstrated difficult family relationship queries")
   print("  • Utilized mathematical operations in Prolog")
   print("  • Constructed interactive AI agent with logical reasoning")
   print("n🚀 Try extending along with your particular person Prolog tips and information!")

We wire all of the issues collectively in principal() to substantiate our Prolog goals, run the family analysis, and showcase multi-step reasoning, then show_mathematical_capabilities() stresses factorial queries from pure language. We conclude by printing a quick recap of what we’ve constructed up to now, allowing us to confidently lengthen the stack with new tips or swap fashions subsequent.

In conclusion, we now have demonstrated that symbolic reasoning and LLMs complement each other fantastically: 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 options for sophisticated family tree and mathematical analyses. From proper right here, we’re capable of broaden the info base, add new domains (paying homage to finance tips, sport logic, and information graphs), or swap in a number of LLMs. We’re moreover positioned to disclose this stack by means of an interactive UI or API, allowing others to find logic-guided AI in real-time.


Attempt the Full Codes. All credit score rating for this evaluation goes to the researchers of this enterprise.

Meet the AI Dev E-newsletter be taught by 40k+ Devs and Researchers from NVIDIA, OpenAI, DeepMind, Meta, Microsoft, JP Morgan Chase, Amgen, Aflac, Wells Fargo and 100s further [SUBSCRIBE NOW]

Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is devoted to harnessing the potential of Artificial Intelligence for social good. His most modern endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth safety of machine learning and deep learning info that’s every technically sound and easily understandable by a big viewers. The platform boasts of over 2 million month-to-month views, illustrating its fame amongst audiences.

Elevate your perspective with NextTech Info, the place innovation meets notion.
Uncover the newest breakthroughs, get distinctive updates, and be a part of with a world group of future-focused thinkers.
Unlock tomorrow’s traits at current: be taught further, subscribe to our publication, and become part of the NextTech neighborhood at NextTech-news.com

Keep forward of the curve with NextBusiness 24. Discover extra tales, subscribe to our publication, and be a part of our rising group at nextbusiness24.com

Exit mobile version