Generative AI

Coding guide to create an Agent Agent Agent Agent Agent Proor agency with Gemini and Langgraph

In this lesson, we hand-in-hand – cover the symbolic logical integration and AI productive AI. We put pyswip to embark on a The Location of Children About The information background, record its predictions such as Langchain tools, and put everything in the reaction style agent. On the way, we are creating the art of family relationships, mathematical statistics such as factorial services, and lists, then to allow agent system, call tools, and the reason for results. At the end of the setup, we can release the actions of the nature of nature and view the agent that translates them into the precise prologing paths, sending many many steps, and returned the supported understanding of JSON support.

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

We include a SWI-Proologist for APT-GET and add PYBIP, GENAI GENAI GENAI WRAPPER, LANGGRAPH PACKS, AND CORRE LANGCHAIN packages for PIP for the Gemini-Powered agent. In these dependents, we are ready for code, question, and keeping the end of the end.

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 upload our main stack, including Prog, Langchain and Langgraph for tools for tools, and the Gemini 1.5 Flash for the LLM Power. We then set the natural variable of Google_ap_key so the model can be verified. With the llm initiated in zero heat, it is written down to find decisive, logical answers from our agel.

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 threaten SWI-Progog on Adedruinface, Launch a rich law / Fact Base at the beginning, and put each clause safely. We then disclose the question () the method applicable to any purpose of incidents and also the Friendship results of JSON

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 keep Adrourtogic Adrintace and fold their questions as Langchain tools, such as Family_Relationship, MatholisShip, Matholations, and so that we can call specific protrol purposes in the environment. We explain each tool to format and send a relevant question (such as the Factorial / 2 or cousin) and return to the JSON side, allow our agent to be orchestrate logic calls.

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"
   ]
  
   for i, query in enumerate(queries, 1):
       print(f"n๐Ÿ” Query {i}: {query}")
       print("-" * 30)
      
       try:
           response = agent.invoke({"messages": [("human", query)]})
           answer = response["messages"][-1].content
           print(f"๐Ÿค– Response: {answer}")
       except Exception as e:
           print(f"โŒ Error: {str(e)}")


def demonstrate_complex_reasoning():
   """Show advanced multi-step reasoning"""
   print("n๐Ÿง  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"๐Ÿ“‹ 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?"
   ]
  
   while True:
       user_input = input("n๐Ÿง‘ You: ")
      
       if user_input.lower() == 'quit':
           print("๐Ÿ‘‹ Goodbye!")
           break
       elif user_input.lower() == 'examples':
           print("๐Ÿ“ Example queries:")
           for ex in examples:
               print(f"  โ€ข {ex}")
           continue
          
       try:
           response = agent.invoke({"messages": [("human", user_input)]})
           print(f"๐Ÿค– AI: {response['messages'][-1].content}")
       except Exception as e:
           print(f"โŒ Error: {str(e)}")

We register three three tools in the Progol, Download the accounting agent around Gemini, and then the Script, Run_family_analysis, which are connecting to Fire Loop, translation questions, translation questions, translation questions, translation questions, translation questions, translation questions, translation questions, translation questions, translation questions. In this way, we test simple products, many struggles, and live q & A, all when the Logic layer is obvious and criminal.

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: 
       return
  
   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"
   ]
  
   for query in math_queries:
       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__ == "__main__":
   main()
   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!")

We are ready for everything together in the main () to ensure our proologist purposes, indicate the family processing, and shows a lot of thinking, and shows a lot of_apanial () emphasizes factorial questions from the natural language. We conclude with a quick recycling of what we have done so far, allowing us to expand a statement with the conviction in new rules or models fluctuating.

In conclusion, we have shown that a symbolic thinking and well-related llms: Prool confirms the accuracy of well-defined understanding, while Gemini handles the understanding of languages and orchestation. We leave active scan, precise testing questions, predicting agents, and demographic activities of complex family and mathematical analysis. From here, we are ready to increase the information center, add new backgrounds (such as financial laws, game concept, information graphs), or various llms. We are also credited to express this stack with UI contacts or API, which allows others to check AI targeted by logic in real time.


Look Full codes. All credit for this study goes to research for this project.

During Ai Dev Newsletter Newspaper learned about 40k + Devs and researchers from Envidia, Open, Deeps, Microsoft, Microsoft, Ambigen, Aflac, Wells Fargo and 100s More [SUBSCRIBE NOW]


Asphazzaq is a Markteach Media Inc. According to a View Business and Developer, Asifi is committed to integrating a good social intelligence. His latest attempt is launched by the launch of the chemistrylife plan for an intelligence, MarktechPost, a devastating intimate practice of a machine learning and deep learning issues that are clearly and easily understood. The platform is adhering to more than two million moon visits, indicating its popularity between the audience.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button