Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      The Value-Driven AI Roadmap

      September 9, 2025

      This week in AI updates: Mistral’s new Le Chat features, ChatGPT updates, and more (September 5, 2025)

      September 6, 2025

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      Lenovo Legion Go 2 specs unveiled: The handheld gaming device to watch this October

      September 10, 2025

      As Windows 10 support ends, users weigh costly extended security program against upgrading to Windows 11

      September 10, 2025

      Lenovo’s Legion Glasses 2 update could change handheld gaming

      September 10, 2025

      Is Lenovo’s refreshed LOQ tower enough to compete? New OLED monitors raise the stakes at IFA 2025

      September 10, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      External Forces Reshaping Financial Services in 2025 and Beyond

      September 10, 2025
      Recent

      External Forces Reshaping Financial Services in 2025 and Beyond

      September 10, 2025

      Why It’s Time to Move from SharePoint On-Premises to SharePoint Online

      September 10, 2025

      Apple’s Big Move: The Future of Mobile

      September 10, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Lenovo Legion Go 2 specs unveiled: The handheld gaming device to watch this October

      September 10, 2025
      Recent

      Lenovo Legion Go 2 specs unveiled: The handheld gaming device to watch this October

      September 10, 2025

      As Windows 10 support ends, users weigh costly extended security program against upgrading to Windows 11

      September 10, 2025

      Lenovo’s Legion Glasses 2 update could change handheld gaming

      September 10, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»A Coding Guide to Build a Tool-Calling ReAct Agent Fusing Prolog Logic with Gemini and LangGraph

    A Coding Guide to Build a Tool-Calling ReAct Agent Fusing Prolog Logic with Gemini and LangGraph

    July 24, 2025

    In this tutorial, we are walking through a hands-on fusion of symbolic logic and generative AI. We set up PySwip to embed a Prolog knowledge base, wrap its predicates as LangChain tools, and then wire everything into a ReAct-style agent. Along the way, we are crafting family-relationship rules, mathematical predicates like factorial, and list utilities, then letting the agent plan, call tools, and reason over the results. By the end of the setup, we can issue natural-language questions and watch the agent translate them into precise Prolog queries, stitch together multi-step answers, and return structured JSON-backed insights.

    Download full codes/notebook
    Copy CodeCopiedUse a different Browser
    !apt-get install swi-prolog -y
    !pip install pyswip langchain-google-genai langgraph langchain-core

    We install SWI-Prolog with apt-get and then add pyswip, LangChain’s Google GenAI wrapper, LangGraph, and core LangChain packages via pip so we can bridge Prolog logic with our Gemini-powered agent. With these dependencies in place, we’re ready to code, query, and orchestrate reasoning end to end.

    Copy CodeCopiedUse a different Browser
    import os
    from pyswip import Prolog
    from langchain_google_genai import ChatGoogleGenerativeAI
    from langchain_core.messages import HumanMessage
    from langchain_core.tools import tool
    from langgraph.prebuilt import create_react_agent
    import 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)

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

    Copy CodeCopiedUse a different Browser
    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 rules:
               try:
                   self.prolog.assertz(rule)
               except Exception as 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 Exception as e:
               return [{"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. We then expose a query() method that runs any Prolog goal and returns JSON-friendly results (or a clear error/no-solution message), allowing us to drive logic queries directly from Python.

    Download full codes/notebook
    Copy CodeCopiedUse a different Browser
    prolog_interface = AdvancedPrologInterface()
    
    
    @tool
    def family_relationships(query: str) -> str:
       """
       Query family relationships in Prolog format.
       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:
       """
       Perform mathematical operations using Prolog.
       Supported operations: 'factorial'
       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:
       """
       Perform advanced relationship queries.
       Types: 'all_children', 'all_grandchildren', 'all_siblings', 'all_cousins'
       """
       queries = {
           'all_children': f"parent(_, _, {entity})" if entity else "parent(_, _, 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:
           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. We define each tool to format and dispatch the right query (such as factorial/2 or cousin lookups) and return clean JSON, allowing our agent to orchestrate logic calls seamlessly.

    Copy CodeCopiedUse a different Browser
    tools = [family_relationships, mathematical_operations, advanced_queries]
    agent = create_react_agent(llm, tools)
    
    
    def run_family_analysis():
       """Comprehensive family relationship analysis"""
       print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f468-200d-1f469-200d-1f467-200d-1f466.png" alt="👨‍👩‍👧‍👦" class="wp-smiley"/> 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<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f50d.png" alt="🔍" class="wp-smiley"/> Query {i}: {query}")
           print("-" * 30)
          
           try:
               response = agent.invoke({"messages": [("human", query)]})
               answer = response["messages"][-1].content
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f916.png" alt="🤖" class="wp-smiley"/> Response: {answer}")
           except Exception as e:
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley"/> Error: {str(e)}")
    
    
    def demonstrate_complex_reasoning():
       """Show advanced multi-step reasoning"""
       print("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f9e0.png" alt="🧠" class="wp-smiley"/> Complex Multi-Step Reasoning")
       print("=" * 40)
      
       complex_query = """
       I want a complete family tree analysis. Please:
       1. List all parent-child relationships
       2. Identify all grandparent relationships 
       3. Find any uncle/aunt relationships
       4. Show cousin relationships
       5. Calculate factorial of 4 as a bonus math operation
       """
      
       print(f"Complex Query: {complex_query}")
       print("-" * 40)
      
       try:
           response = agent.invoke({"messages": [("human", complex_query)]})
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4cb.png" alt="📋" class="wp-smiley"/> Comprehensive Analysis:n{response['messages'][-1].content}")
       except Exception as e:
           print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley"/> Error in complex reasoning: {str(e)}")
    
    
    def interactive_prolog_session():
       """Interactive Prolog knowledge base exploration"""
       print("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4ac.png" alt="💬" class="wp-smiley"/> 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?"
       ]
      
       while True:
           user_input = input("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f9d1.png" alt="🧑" class="wp-smiley"/> You: ")
          
           if user_input.lower() == 'quit':
               print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f44b.png" alt="👋" class="wp-smiley"/> Goodbye!")
               break
           elif user_input.lower() == 'examples':
               print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4dd.png" alt="📝" class="wp-smiley"/> Example queries:")
               for ex in examples:
                   print(f"  • {ex}")
               continue
              
           try:
               response = agent.invoke({"messages": [("human", user_input)]})
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f916.png" alt="🤖" class="wp-smiley"/> AI: {response['messages'][-1].content}")
           except Exception as e:
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley"/> 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.

    Copy CodeCopiedUse a different Browser
    def test_direct_queries():
       """Test direct Prolog queries for verification"""
       print("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f52c.png" alt="🔬" class="wp-smiley"/> 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<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4cb.png" alt="📋" class="wp-smiley"/> {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("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/26a0.png" alt="⚠" class="wp-smiley"/>  Please set your Gemini API key in Cell 3!")
           print("Get it from: https://aistudio.google.com/app/apikey")
           return
      
       print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f680.png" alt="🚀" class="wp-smiley"/> 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<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f522.png" alt="🔢" class="wp-smiley"/> 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<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f9ee.png" alt="🧮" class="wp-smiley"/> Math Query: {query}")
           try:
               response = agent.invoke({"messages": [("human", query)]})
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f4ca.png" alt="📊" class="wp-smiley"/> Result: {response['messages'][-1].content}")
           except Exception as e:
               print(f"<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley"/> Error: {str(e)}")
    
    
    if __name__ == "__main__":
       main()
       show_mathematical_capabilities()
      
       print("n<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley"/> Tutorial completed successfully!")
       print("<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f3af.png" alt="🎯" class="wp-smiley"/> 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<img src="https://s.w.org/images/core/emoji/16.0.1/72x72/1f680.png" alt="🚀" class="wp-smiley"/> Try extending with your own Prolog rules and facts!")

    We wire everything together in main() to verify our Prolog goals, run the family analysis, and showcase multi-step reasoning, then show_mathematical_capabilities() stresses factorial queries from natural language. We conclude by printing a quick recap of what we’ve built so far, allowing us to confidently extend the stack with new rules or swap models next.

    In conclusion, we have demonstrated that symbolic reasoning and LLMs complement each other beautifully: Prolog guarantees correctness on well-defined logic, while Gemini handles flexible language understanding and orchestration. We are leaving with a working scaffold, direct Prolog queries for verification, tool-wrapped predicates for agents, and demo functions for complex family tree and mathematical analyses. From here, we are ready to expand the knowledge base, add new domains (such as finance rules, game logic, and knowledge graphs), or swap in different LLMs. We are also positioned to expose this stack via an interactive UI or API, allowing others to explore logic-guided AI in real-time.


    Check out the Full Codes. All credit for this research goes to the researchers of this project.

    Meet the AI Dev Newsletter read by 40k+ Devs and Researchers from NVIDIA, OpenAI, DeepMind, Meta, Microsoft, JP Morgan Chase, Amgen, Aflac, Wells Fargo and 100s more [SUBSCRIBE NOW]

    The post A Coding Guide to Build a Tool-Calling ReAct Agent Fusing Prolog Logic with Gemini and LangGraph appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow Global Calibration Strengthens Multiaccuracy
    Next Article GitHub Introduces Vibe Coding with Spark: Revolutionizing Intelligent App Development in a Flash

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    September 3, 2025
    Machine Learning

    Announcing the new cluster creation experience for Amazon SageMaker HyperPod

    September 3, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

    Tech & Work

    CVE-2025-4196 – SourceCodester Patient Record Management System SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-48848 – Aspect Disk Overutilization Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    FOSS Weekly #25.33: Debian 13 Released, Torvalds vs RISC-V, Arch’s New Tool, GNOME Perfection and More Linux Stuff

    Learning Resources

    Highlights

    News & Updates

    My jaw dropped at this Fallout-themed DOOM mod that reimagines the classic RPG as an FPS — one of the coolest fan games I’ve ever seen

    July 22, 2025

    Fallout: Bakersfield — a DOOM mod that transforms the classic Fallout RPG into an old-school…

    CVE-2025-4244 – Code-Projects Online Bus Reservation System SQL Injection

    May 3, 2025

    Microsoft Introduces Paid Extended Support for Azure Database for MySQL

    August 13, 2025

    CVE-2025-49281 – Magways PHP Remote File Inclusion Vulnerability

    June 9, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.