├── IntelligentGraph.egg-info ├── dependency_links.txt ├── requires.txt ├── top_level.txt ├── SOURCES.txt └── PKG-INFO ├── IntelligentGraph.gif ├── IntelligentGraph.diagrams.gif ├── dist └── IntelligentGraph-0.9.0-py3.10.egg ├── intelligentgraph ├── __pycache__ │ ├── graph.cpython-310.pyc │ ├── script.cpython-310.pyc │ └── __init__.cpython-310.pyc ├── __init__.py ├── script.py └── graph.py ├── .vscode └── settings.json ├── tests ├── __pycache__ │ ├── test_dataset.cpython-310-pytest-7.4.3.pyc │ ├── test_graph.cpython-310-pytest-7.4.3.pyc │ ├── test_script.cpython-310-pytest-7.4.3.pyc │ ├── test_scripy.cpython-310-pytest-7.4.3.pyc │ ├── test_recursion.cpython-310-pytest-7.4.3.pyc │ ├── test_gettingstarted.cpython-310-pytest-7.4.3.pyc │ └── test_conjunctiveGraph.cpython-310-pytest-7.4.3.pyc ├── test_graph.py └── test_conjunctiveGraph.py ├── setup.py ├── IntelligentGraph+LLM.ipynb ├── LICENSE ├── README.md └── GettingStarted.ipynb /IntelligentGraph.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /IntelligentGraph.egg-info/requires.txt: -------------------------------------------------------------------------------- 1 | RDFLib>=7.0 2 | -------------------------------------------------------------------------------- /IntelligentGraph.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | intelligentgraph 2 | -------------------------------------------------------------------------------- /IntelligentGraph.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/IntelligentGraph.gif -------------------------------------------------------------------------------- /IntelligentGraph.diagrams.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/IntelligentGraph.diagrams.gif -------------------------------------------------------------------------------- /dist/IntelligentGraph-0.9.0-py3.10.egg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/dist/IntelligentGraph-0.9.0-py3.10.egg -------------------------------------------------------------------------------- /intelligentgraph/__pycache__/graph.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/intelligentgraph/__pycache__/graph.cpython-310.pyc -------------------------------------------------------------------------------- /intelligentgraph/__pycache__/script.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/intelligentgraph/__pycache__/script.cpython-310.pyc -------------------------------------------------------------------------------- /intelligentgraph/__pycache__/__init__.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/intelligentgraph/__pycache__/__init__.cpython-310.pyc -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.testing.pytestArgs": [ 3 | "." 4 | ], 5 | "python.testing.unittestEnabled": false, 6 | "python.testing.pytestEnabled": true 7 | } -------------------------------------------------------------------------------- /tests/__pycache__/test_dataset.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_dataset.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_graph.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_graph.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_script.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_script.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_scripy.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_scripy.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_recursion.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_recursion.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_gettingstarted.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_gettingstarted.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /tests/__pycache__/test_conjunctiveGraph.cpython-310-pytest-7.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peterjohnlawrence/IntelligentGraph/HEAD/tests/__pycache__/test_conjunctiveGraph.cpython-310-pytest-7.4.3.pyc -------------------------------------------------------------------------------- /intelligentgraph/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["graph","script"] 2 | 3 | from intelligentgraph.graph import IntelligentConjunctiveGraph, IntelligentDataset, IntelligentGraph 4 | from intelligentgraph.script import SCRIPT 5 | 6 | -------------------------------------------------------------------------------- /IntelligentGraph.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | LICENSE 2 | README.md 3 | setup.py 4 | IntelligentGraph.egg-info/PKG-INFO 5 | IntelligentGraph.egg-info/SOURCES.txt 6 | IntelligentGraph.egg-info/dependency_links.txt 7 | IntelligentGraph.egg-info/requires.txt 8 | IntelligentGraph.egg-info/top_level.txt 9 | intelligentgraph/__init__.py 10 | intelligentgraph/graph.py 11 | intelligentgraph/script.py -------------------------------------------------------------------------------- /IntelligentGraph.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.1 2 | Name: IntelligentGraph 3 | Version: 0.9.0 4 | Summary: Python package that adds IntelligentGraph capabilities to RDFLib RDF graph package 5 | Home-page: https://https://github.com/peterjohnlawrence/IntelligentGraph 6 | Author: Peter Lawrence 7 | Author-email: peter.lawrence@inova8.com 8 | License: Apache License 2.0 9 | Classifier: Development Status :: 1 - Planning 10 | Classifier: Intended Audience :: Science/Research 11 | Classifier: License :: OSI Approved :: Apache License 12 | Classifier: Operating System :: POSIX :: Linux 13 | Classifier: Programming Language :: Python :: 3 14 | Classifier: Programming Language :: Python :: 3.4 15 | Classifier: Programming Language :: Python :: 3.5 16 | License-File: LICENSE 17 | Requires-Dist: RDFLib>=7.0 18 | -------------------------------------------------------------------------------- /intelligentgraph/script.py: -------------------------------------------------------------------------------- 1 | from rdflib.namespace import Namespace,DefinedNamespace 2 | from rdflib import URIRef, term 3 | 4 | class SCRIPT(DefinedNamespace): 5 | """ 6 | SCRIPT vocabulary 7 | 8 | The SCRIPT RDF vocabulary provides some aditional datatypes for conveniently handling scripts 9 | It also contains the SCRIPT evaluation engine 10 | 11 | Date: 2023-12-19 12 | 13 | """ 14 | _fail = True 15 | _NS = Namespace("http://inova8.com/script/") 16 | 17 | python=URIRef("http://inova8.com/script/python") 18 | error=URIRef("http://inova8.com/script/error") 19 | 20 | def __init__( self,*args, **kwargs): 21 | super().__init__(*args, **kwargs) 22 | 23 | python_type =self.python 24 | error_type =self.error 25 | if( self.python not in term._toPythonMapping): term.bind(self.python, str) 26 | if( self.error not in term._toPythonMapping): term.bind(self.error, str) 27 | 28 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='IntelligentGraph', 5 | version='0.9.0', 6 | description='Python package that adds IntelligentGraph capabilities to RDFLib RDF graph package', 7 | url='https://https://github.com/peterjohnlawrence/IntelligentGraph', 8 | author='Peter Lawrence', 9 | author_email='peter.lawrence@inova8.com', 10 | license='Apache License 2.0', 11 | packages=["intelligentgraph"], 12 | install_requires=['RDFLib>=7.0', 13 | ], 14 | 15 | classifiers=[ 16 | 'Development Status :: 1 - Planning', 17 | 'Intended Audience :: Science/Research', 18 | 'License :: OSI Approved :: Apache License', 19 | 'Operating System :: POSIX :: Linux', 20 | 'Programming Language :: Python :: 3', 21 | 'Programming Language :: Python :: 3.4', 22 | 'Programming Language :: Python :: 3.5', 23 | ], 24 | ) 25 | -------------------------------------------------------------------------------- /tests/test_graph.py: -------------------------------------------------------------------------------- 1 | import intelligentgraph 2 | from intelligentgraph import IntelligentConjunctiveGraph, IntelligentDataset,IntelligentGraph,SCRIPT 3 | from rdflib import Literal, URIRef 4 | from rdflib.namespace import FOAF 5 | from datetime import date 6 | 7 | def test_simpleLiteral(): 8 | g = IntelligentGraph() 9 | ig = URIRef("http://inova8.com/ig") 10 | g.add((ig, FOAF.birthday, Literal('''_result= 1952 11 | ''',datatype=SCRIPT.python))) 12 | 13 | for triple in g.triples( (None , None, None)): 14 | assert triple[0]==URIRef("http://inova8.com/ig") 15 | assert triple[1]==FOAF.birthday 16 | assert triple[2].toPython() ==1952 17 | 18 | def test_simpleLiteralwoIntelligence(): 19 | g = IntelligentGraph() 20 | ig = URIRef("http://inova8.com/ig") 21 | g.add((ig, FOAF.birthday, Literal('1952',datatype=SCRIPT.python))) 22 | g.disableIntelligence() 23 | for triple in g.triples( (None , None, None)): 24 | assert triple[0]==URIRef("http://inova8.com/ig") 25 | assert triple[1]==FOAF.birthday 26 | assert triple[2] ==Literal('1952',datatype=SCRIPT.python) 27 | 28 | def test_simpleDatetime(): 29 | g = IntelligentGraph() 30 | ig = URIRef("http://inova8.com/ig") 31 | g.add((ig, FOAF.birthday, Literal('''from datetime import date 32 | _result =date(1951, 3, 8) 33 | ''',datatype=SCRIPT.python))) 34 | for triple in g.triples( (None , None, None)): 35 | assert triple[0]==URIRef("http://inova8.com/ig") 36 | assert triple[1]==FOAF.birthday 37 | assert triple[2].toPython() == date(1951, 3, 8) 38 | 39 | 40 | def test_AgeCalc(): 41 | g = IntelligentGraph() 42 | ig = URIRef("http://inova8.com/ig") 43 | 44 | g.add((ig, FOAF.birthday, Literal('''from datetime import date 45 | _result =date(1951, 3, 8) 46 | ''',datatype=SCRIPT.python))) 47 | 48 | g.add((ig, FOAF.age, Literal(''' 49 | from rdflib.namespace import FOAF 50 | from datetime import date 51 | for triple in g.triples( (s , FOAF.birthday, None)): 52 | age= int((date.today()-triple[2].toPython()).days/365.25) 53 | _result = age''',datatype=SCRIPT.python))) 54 | 55 | for triple in g.triples( (None , FOAF, None)): 56 | assert triple[0]==URIRef("http://inova8.com/ig") 57 | assert triple[1]==FOAF.age 58 | assert triple[2].toPython() == 72 59 | 60 | def test_externalData(): 61 | g = IntelligentGraph() 62 | ig = URIRef("http://inova8.com/ig") 63 | g.add((ig, FOAF.knows, Literal(''' 64 | import requests 65 | from rdflib.namespace import FOAF 66 | def getKnows(individual): 67 | response = requests.get("https://random-word-api.herokuapp.com/word?lang=en&number=5") 68 | for word in response.json(): 69 | yield (individual, FOAF.knows, URIRef("http://inova8.com/"+word)) 70 | _result = getKnows(s)''',datatype=SCRIPT.python))) 71 | 72 | for row in g.query( '''select (count(*) as ?total)where{?s ?p ?o}'''): 73 | assert row['total'].toPython()==5 74 | 75 | def test_scriptRecursion(): 76 | g = IntelligentGraph() 77 | ig = URIRef("http://inova8.com/ig") 78 | g.add((ig, FOAF.birthday, Literal(''' 79 | _result = Literal("_result =1952" ,datatype=SCRIPT.python) 80 | ''',datatype=SCRIPT.python))) 81 | 82 | for triple in g.triples( (None , None, None)): 83 | #assert triple[0]==URIRef("http://inova8.com/ig") 84 | #assert triple[1]==FOAF.birthday 85 | print(triple[2]) 86 | assert triple[2].toPython()==1952 87 | 88 | def test_circularReference(): 89 | g = IntelligentGraph() 90 | ig = URIRef("http://inova8.com/ig") 91 | ig1 = URIRef("http://inova8.com/ig1") 92 | ig2 = URIRef("http://inova8.com/ig2") 93 | ig3 = URIRef("http://inova8.com/ig3") 94 | ig4 = URIRef("http://inova8.com/ig4") 95 | g.add((ig, ig1, Literal(''' 96 | from rdflib.namespace import FOAF 97 | for triple in g.triples( (s , URIRef("http://inova8.com/ig2"), None)): 98 | o= triple[2] 99 | _result = o''',datatype=SCRIPT.python))) 100 | g.add((ig, ig2, Literal(''' 101 | from rdflib.namespace import FOAF 102 | for triple in g.triples( (s , URIRef("http://inova8.com/ig3"), None)): 103 | o= triple[2] 104 | _result = o''',datatype=SCRIPT.python))) 105 | g.add((ig, ig3, Literal(''' 106 | from rdflib.namespace import FOAF 107 | for triple in g.triples( (s , URIRef("http://inova8.com/ig4"), None)): 108 | o= triple[2] 109 | _result = o''',datatype=SCRIPT.python))) 110 | g.add((ig, ig4, Literal(''' 111 | from rdflib.namespace import FOAF 112 | for triple in g.triples( (s , URIRef("http://inova8.com/ig1"), None)): 113 | o= triple[2] 114 | _result = o''',datatype=SCRIPT.python))) 115 | for triple in g.triples( (ig, ig1, None)): 116 | print(triple[2]) 117 | assert triple[2]==Literal("Error=Script circular reference", datatype=SCRIPT.error) -------------------------------------------------------------------------------- /tests/test_conjunctiveGraph.py: -------------------------------------------------------------------------------- 1 | import intelligentgraph 2 | from intelligentgraph import IntelligentConjunctiveGraph, IntelligentDataset,IntelligentGraph,SCRIPT 3 | from rdflib import Literal, URIRef 4 | from rdflib.namespace import FOAF 5 | from datetime import date 6 | 7 | def test_simpleLiteral(): 8 | g = IntelligentConjunctiveGraph() 9 | ig = URIRef("http://inova8.com/ig") 10 | g.add((ig, FOAF.birthday, Literal('''_result= 1952 11 | ''',datatype=SCRIPT.python))) 12 | 13 | for triple in g.triples( (None , None, None)): 14 | assert triple[0]==URIRef("http://inova8.com/ig") 15 | assert triple[1]==FOAF.birthday 16 | assert triple[2].toPython() ==1952 17 | 18 | def test_simpleLiteralwoIntelligence(): 19 | g = IntelligentConjunctiveGraph() 20 | ig = URIRef("http://inova8.com/ig") 21 | g.add((ig, FOAF.birthday, Literal('1952',datatype=SCRIPT.python))) 22 | g.disableIntelligence() 23 | for triple in g.triples( (None , None, None)): 24 | assert triple[0]==URIRef("http://inova8.com/ig") 25 | assert triple[1]==FOAF.birthday 26 | assert triple[2] ==Literal('1952',datatype=SCRIPT.python) 27 | 28 | def test_simpleDatetime(): 29 | g = IntelligentConjunctiveGraph() 30 | ig = URIRef("http://inova8.com/ig") 31 | g.add((ig, FOAF.birthday, Literal('''from datetime import date 32 | _result =date(1951, 3, 8) 33 | ''',datatype=SCRIPT.python))) 34 | for triple in g.triples( (None , None, None)): 35 | assert triple[0]==URIRef("http://inova8.com/ig") 36 | assert triple[1]==FOAF.birthday 37 | assert triple[2].toPython() == date(1951, 3, 8) 38 | 39 | 40 | def test_AgeCalc(): 41 | g = IntelligentConjunctiveGraph() 42 | ig = URIRef("http://inova8.com/ig") 43 | 44 | g.add((ig, FOAF.birthday, Literal('''from datetime import date 45 | _result =date(1951, 3, 8) 46 | ''',datatype=SCRIPT.python))) 47 | 48 | g.add((ig, FOAF.age, Literal(''' 49 | from rdflib.namespace import FOAF 50 | from datetime import date 51 | for triple in g.triples( (s , FOAF.birthday, None)): 52 | age= int((date.today()-triple[2].toPython()).days/365.25) 53 | _result = age''',datatype=SCRIPT.python))) 54 | 55 | for triple in g.triples( (None , FOAF, None)): 56 | assert triple[0]==URIRef("http://inova8.com/ig") 57 | assert triple[1]==FOAF.age 58 | assert triple[2].toPython() == 72 59 | 60 | def test_externalData(): 61 | g = IntelligentConjunctiveGraph() 62 | ig = URIRef("http://inova8.com/ig") 63 | g.add((ig, FOAF.knows, Literal(''' 64 | import requests 65 | from rdflib.namespace import FOAF 66 | def getKnows(individual): 67 | response = requests.get("https://random-word-api.herokuapp.com/word?lang=en&number=5") 68 | for word in response.json(): 69 | yield (individual, FOAF.knows, URIRef("http://inova8.com/"+word)) 70 | _result = getKnows(s)''',datatype=SCRIPT.python))) 71 | 72 | for row in g.query( '''select (count(*) as ?total)where{?s ?p ?o}'''): 73 | assert row['total'].toPython()==5 74 | 75 | def test_scriptRecursion(): 76 | g = IntelligentConjunctiveGraph() 77 | ig = URIRef("http://inova8.com/ig") 78 | g.add((ig, FOAF.birthday, Literal(''' 79 | _result = Literal("_result =1952" ,datatype=SCRIPT.python) 80 | ''',datatype=SCRIPT.python))) 81 | 82 | for triple in g.triples( (None , None, None)): 83 | #assert triple[0]==URIRef("http://inova8.com/ig") 84 | #assert triple[1]==FOAF.birthday 85 | print(triple[2]) 86 | assert triple[2].toPython()==1952 87 | 88 | def test_circularReference(): 89 | g = IntelligentConjunctiveGraph() 90 | ig = URIRef("http://inova8.com/ig") 91 | ig1 = URIRef("http://inova8.com/ig1") 92 | ig2 = URIRef("http://inova8.com/ig2") 93 | ig3 = URIRef("http://inova8.com/ig3") 94 | ig4 = URIRef("http://inova8.com/ig4") 95 | g.add((ig, ig1, Literal(''' 96 | from rdflib.namespace import FOAF 97 | for triple in g.triples( (s , URIRef("http://inova8.com/ig2"), None)): 98 | o= triple[2] 99 | _result = o''',datatype=SCRIPT.python))) 100 | g.add((ig, ig2, Literal(''' 101 | from rdflib.namespace import FOAF 102 | for triple in g.triples( (s , URIRef("http://inova8.com/ig3"), None)): 103 | o= triple[2] 104 | _result = o''',datatype=SCRIPT.python))) 105 | g.add((ig, ig3, Literal(''' 106 | from rdflib.namespace import FOAF 107 | for triple in g.triples( (s , URIRef("http://inova8.com/ig4"), None)): 108 | o= triple[2] 109 | _result = o''',datatype=SCRIPT.python))) 110 | g.add((ig, ig4, Literal(''' 111 | from rdflib.namespace import FOAF 112 | for triple in g.triples( (s , URIRef("http://inova8.com/ig1"), None)): 113 | o= triple[2] 114 | _result = o''',datatype=SCRIPT.python))) 115 | for triple in g.triples( (ig, ig1, None)): 116 | print(triple[2]) 117 | assert triple[2]==Literal("Error=Script circular reference", datatype=SCRIPT.error) -------------------------------------------------------------------------------- /IntelligentGraph+LLM.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyNLeOZAZQwErIbkrR1ghmoR"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"cP6iTex9NAwW"},"outputs":[],"source":["!pip install --upgrade openai --quiet"]},{"cell_type":"code","source":["!pip install \"git+https://github.com/peterjohnlawrence/IntelligentGraph.git\""],"metadata":{"id":"vCgOQKN4NYh7"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import os\n","os.environ['OPENAI_API_KEY'] = 'insert your own key here'"],"metadata":{"id":"fHJK6x09NND8"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import intelligentgraph\n","from intelligentgraph import IntelligentConjunctiveGraph, IntelligentDataset,IntelligentGraph,SCRIPT\n","from rdflib import Literal, URIRef\n","from rdflib.namespace import SDO"],"metadata":{"id":"NrJEjitVNQK1"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["from openai import OpenAI\n","import json\n","import os\n","def getCities(countryCode):\n"," client = OpenAI()\n"," completion = client.chat.completions.create(\n"," model=\"gpt-3.5-turbo\",\n"," messages=[\n"," {\"role\": \"system\", \"content\": \"Make a json structure of three columns, one for city/town name, one for its population, and one for its area in hectares. for example { 'results':[{'city':'Manchester','population':'530300', 'area':'4390'}]}. Format the population number without commas ','\"},\n"," {\"role\": \"user\", \"content\": \"Now fill in the results with the top 10 cities in the \" + countryCode + \" by population.\"}\n"," ]\n"," )\n"," return json.loads(completion.choices[0].message.content)\n","for city in getCities('UK')['results']:\n"," print('city='+city['city']+',population='+city['population']+',area=' +city['area']+',density='+str(float(city['population'])/float(city['area'])))"],"metadata":{"id":"Ywv3KxG3Nmc6"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["def getCity(country):\n"," contryCode = os.path.split(country.toPython())[1]\n"," for city in getCities(contryCode)['results']:\n"," cityName =city['city'].replace(' ','_')\n"," cityIRI = URIRef(\"http://inova8.com/\"+cityName)\n"," yield (country, SDO.City ,cityIRI)\n"," population = float(city['population'].replace(',',''))\n"," area = float(city['area'].replace(',',''))\n"," yield (cityIRI, URIRef(\"http://inova8.com/population\") , Literal(population))\n"," yield (cityIRI, URIRef(\"http://inova8.com/area\") , Literal(area))\n"," yield (cityIRI, URIRef(\"http://inova8.com/density\") , Literal(population/area))\n","for triple in getCity(URIRef(\"http://inova8.com/France\")):\n"," print(triple)"],"metadata":{"id":"VboxerNZNmQi"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["cityg = IntelligentGraph()\n","\n","USA = URIRef(\"http://inova8.com/USA\")\n","cityg.add((USA, SDO.City, Literal('''\n","from openai import OpenAI\n","from rdflib.namespace import SDO\n","import os\n","import json\n","def getCities(countryCode):\n"," client = OpenAI()\n"," completion = client.chat.completions.create(\n"," model=\"gpt-3.5-turbo\",\n"," messages=[\n"," {\"role\": \"system\", \"content\": \"Make a json structure of three columns, one for city/town name, one for its population, and one for its area in hectares. for example { 'results':[{'city':'Manchester','population':'530300', 'area':'4390'}]}. Format the population number without commas ','\"},\n"," {\"role\": \"user\", \"content\": \"Now fill in the results with the top 10 cities in the \" + countryCode + \" by population.\"}\n"," ]\n"," )\n"," return json.loads(completion.choices[0].message.content)\n","def getCity(country):\n"," contryCode = os.path.split(country.toPython())[1]\n"," for city in getCities(contryCode)['results']:\n"," cityName =city['city'].replace(' ','_')\n"," cityIRI = URIRef(\"http://inova8.com/\"+cityName)\n"," yield (country, SDO.City ,cityIRI)\n"," population = float(city['population'].replace(',',''))\n"," area = float(city['area'].replace(',',''))\n"," yield (cityIRI, URIRef(\"http://inova8.com/population\") , Literal(population))\n"," yield (cityIRI, URIRef(\"http://inova8.com/area\") , Literal(area))\n"," yield (cityIRI, URIRef(\"http://inova8.com/density\") , Literal(population/area))\n","_result = getCity(s)''',datatype=SCRIPT.python)))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vK5WDs8-Ollg","executionInfo":{"status":"ok","timestamp":1703193251743,"user_tz":0,"elapsed":392,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"b724fed7-58af-42e6-c990-f02217177e6a"},"execution_count":null,"outputs":[{"output_type":"execute_result","data":{"text/plain":[")>"]},"metadata":{},"execution_count":11}]},{"cell_type":"code","source":["print(cityg.serialize(format=\"nt\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ttq20MCCOrh4","executionInfo":{"status":"ok","timestamp":1703193269766,"user_tz":0,"elapsed":5129,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"6bff2647-378c-436c-8a6d-4659c186786d"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":[" .\n"," \"8622698.0\"^^ .\n"," \"78217.0\"^^ .\n"," \"110.24071493409362\"^^ .\n"," .\n"," \"3990456.0\"^^ .\n"," \"130060.0\"^^ .\n"," \"30.68165462094418\"^^ .\n"," .\n"," \"2705994.0\"^^ .\n"," \"22734.0\"^^ .\n"," \"119.02850356294537\"^^ .\n"," .\n"," \"2325502.0\"^^ .\n"," \"17082.0\"^^ .\n"," \"136.13757171291417\"^^ .\n"," .\n"," \"1660272.0\"^^ .\n"," \"13374.0\"^^ .\n"," \"124.14176760879317\"^^ .\n"," .\n"," \"1580863.0\"^^ .\n"," \"36958.0\"^^ .\n"," \"42.77458195789816\"^^ .\n"," .\n"," \"1532233.0\"^^ .\n"," \"119163.0\"^^ .\n"," \"12.858294940543626\"^^ .\n"," .\n"," \"1425976.0\"^^ .\n"," \"96451.0\"^^ .\n"," \"14.784460503260723\"^^ .\n"," .\n"," \"1343573.0\"^^ .\n"," \"99911.0\"^^ .\n"," \"13.447698451621944\"^^ .\n"," .\n"," \"1030119.0\"^^ .\n"," \"46145.0\"^^ .\n"," \"22.323523675371113\"^^ .\n","\n"]}]}]} -------------------------------------------------------------------------------- /intelligentgraph/graph.py: -------------------------------------------------------------------------------- 1 | from intelligentgraph.script import SCRIPT 2 | 3 | from rdflib.namespace import Namespace,DefinedNamespace 4 | from rdflib import Graph, ConjunctiveGraph, Dataset, Literal, URIRef, term 5 | from rdflib.paths import Path 6 | from rdflib.term import Node 7 | from typing import Generator ,Tuple,Optional,Union ,List 8 | 9 | _SubjectType = Node 10 | _PredicateType = Node 11 | _ObjectType = Node 12 | _TripleType = Tuple["_SubjectType", "_PredicateType", "_ObjectType"] 13 | _ContextType = Graph 14 | _TripleSelectorType = Tuple[ 15 | Optional["_SubjectType"], 16 | Optional[Union["Path", "_PredicateType"]], 17 | Optional["_ObjectType"], 18 | ] 19 | _TriplePathType = Tuple["_SubjectType", Path, "_ObjectType"] 20 | _TripleOrTriplePathType= Union["_TripleType", "_TriplePathType"] 21 | 22 | _QuadSelectorType = Tuple[ 23 | Optional["_SubjectType"], 24 | Optional[Union["Path", "_PredicateType"]], 25 | Optional["_ObjectType"], 26 | Optional["_ContextType"], 27 | ] 28 | _TripleOrQuadSelectorType = Union["_TripleSelectorType", "_QuadSelectorType"] 29 | _TriplePathPatternType = Tuple[Optional["_SubjectType"], Path, Optional["_ObjectType"]] 30 | _QuadPathPatternType = Tuple[ 31 | Optional["_SubjectType"], 32 | Path, 33 | Optional["_ObjectType"], 34 | Optional["_ContextType"], 35 | ] 36 | _TripleOrQuadPatternType = Union["_TriplePatternType", "_QuadPatternType"] 37 | _OptionalQuadType = Tuple[ 38 | "_SubjectType", "_PredicateType", "_ObjectType", Optional["_ContextType"] 39 | ] 40 | _TriplePatternType = Tuple[ 41 | Optional["_SubjectType"], Optional["_PredicateType"], Optional["_ObjectType"] 42 | ] 43 | _QuadPatternType = Tuple[ 44 | Optional["_SubjectType"], 45 | Optional["_PredicateType"], 46 | Optional["_ObjectType"], 47 | Optional["_ContextType"], 48 | ] 49 | class Intelligent(): 50 | _enabled = True 51 | stack =None 52 | def handleScript( self, 53 | triple: _TripleSelectorType, 54 | _ctx :Optional[_ContextType]=None, 55 | stack:Optional[Graph]=None 56 | ) : 57 | if(self.stack is None): 58 | self.stack=Graph() 59 | if (triple in self.stack): 60 | yield (triple[0], triple[1] ,Literal("Error=Script circular reference", datatype=SCRIPT.error) ) 61 | else: 62 | self.stack.add(triple) 63 | for s, p, o in self.scriptEvaluator(triple=triple,_ctx= _ctx ): 64 | if (isinstance(o, Literal) and (o.datatype == SCRIPT.python)): 65 | self.handleScript(triple=(s,p,o),_ctx=_ctx, stack= self.stack ) 66 | else: 67 | yield (s, p, o ) 68 | def disableIntelligence(self): 69 | self._enabled = False 70 | def enableIntelligence(self): 71 | self._enabled = True 72 | def isEnabled(self): 73 | return self._enabled 74 | def _handleReturn(s,p,returnResult): 75 | if(returnResult is not None ): 76 | if(isinstance(returnResult ,Generator)): 77 | yield returnResult 78 | elif(isinstance(returnResult ,term.Node)): 79 | yield s, p , returnResult 80 | else: 81 | yield s, p ,Literal(returnResult) 82 | else: 83 | yield s, p ,Literal("Error=Script does not return _return value", datatype=SCRIPT.error) 84 | 85 | def _eval( self, 86 | triple: _TriplePatternType, 87 | ctx :Optional[_ContextType]=None 88 | ) -> Generator["_TripleType", None, None]: 89 | s, p, o = triple 90 | inputs = globals() 91 | inputs['g']=self 92 | inputs['s']=s 93 | inputs['p']=p 94 | inputs['o']=o 95 | inputs['ctx']=ctx 96 | result= globals() 97 | result['_result']=None 98 | try: 99 | exec(o,inputs,result) 100 | except BaseException as err: 101 | yield s, p ,Literal("Error="+str(err)+ "\nCode = "+ str(o), datatype=SCRIPT.error) 102 | #yield SCRIPT.handleReturn(s,p,result['_result']) 103 | if(result['_result'] is not None ): 104 | if(isinstance(result['_result'] ,Generator)): 105 | yield result['_result'] 106 | elif(isinstance(result['_result'] ,term.Node)): 107 | yield s, p , result['_result'] 108 | else: 109 | yield s, p ,Literal(result['_result']) 110 | else: 111 | yield s, p ,Literal("Error=Script does assign _return value or value assigned is None. \nCode ="+ str(o), datatype=SCRIPT.error) 112 | 113 | 114 | def scriptEvaluator(self, triple: _TriplePatternType, _ctx :Optional[_ContextType]=None): 115 | resultGenerator = next(self._eval(triple=triple), _ctx) 116 | (_s,_p,_o)=triple 117 | if(isinstance(resultGenerator,Generator)): 118 | try: 119 | for triple in resultGenerator: 120 | if (isinstance(triple, tuple)): 121 | if ( isinstance(triple[0],term.Node) and isinstance(triple[1],term.Node) and isinstance(triple[2],term.Node) ): 122 | yield triple 123 | else: 124 | yield _s, _p ,Literal("Error=tuple but not all elements are term.Node"+ "\nCode = "+ str(_o), datatype=SCRIPT.error) 125 | else: 126 | yield _s, _p ,Literal("Error=incomplete tuple"+ "\nCode = "+ str(_o), datatype=SCRIPT.error) 127 | except BaseException as err: 128 | yield _s, _p ,Literal("Error="+str(err)+ "\nCode = "+ str(_o), datatype=SCRIPT.error) 129 | else: 130 | yield resultGenerator 131 | class IntelligentGraph(Intelligent, Graph): 132 | """An Intelligent RDF Graph, inherited from Graph 133 | 134 | Supports triples with SCRIPT-valued objects, literals of datatype SCRIPT.python. 135 | 136 | Instead of returning the object literal, the Python script within that literal is executed. 137 | 138 | The Python script can return a scalar, which is interpreted as the node replacement value for the scipt. 139 | Alternatively the Pythobn scrript can yield a list of tuples. 140 | 141 | In the event of a script execution error, the error message os returned as the literal value of the object with datatype SCRIPT.error 142 | """ 143 | def triples( 144 | self, 145 | triple: _TripleSelectorType, 146 | ) -> Generator[_TripleOrTriplePathType, None, None]: 147 | """Generator over the triple store 148 | 149 | Returns triples that match the given triple pattern. If triple pattern 150 | does not provide a context, all contexts will be searched. 151 | """ 152 | s, p, o = triple 153 | if isinstance(p, Path): 154 | for _s, _o in p.eval(self, s, o): 155 | yield _s, p, _o 156 | else: 157 | for (_s, _p, _o), cg in self.store.triples((s, p, o), context=self): 158 | # __store not visible so replaced with store 159 | if (isinstance(_o, Literal) and (_o.datatype == SCRIPT.python) and (self.isEnabled())): 160 | for (ss,pp,oo) in self.handleScript((_s, _p, _o)): 161 | yield (ss,pp,oo) 162 | else: 163 | yield _s, _p, _o 164 | 165 | #_ContextType = IntelligentGraph 166 | 167 | class IntelligentConjunctiveGraph(Intelligent,ConjunctiveGraph): 168 | def triples( 169 | self, 170 | triple_or_quad: _TripleOrQuadSelectorType, 171 | context: Optional[_ContextType] = None, 172 | ) -> Generator[_TripleOrTriplePathType, None, None]: 173 | """ 174 | Iterate over all the triples in the entire conjunctive graph 175 | 176 | For legacy reasons, this can take the context to query either 177 | as a fourth element of the quad, or as the explicit context 178 | keyword parameter. The kw param takes precedence. 179 | """ 180 | 181 | s, p, o, c = self._spoc(triple_or_quad) 182 | context = self._graph(context or c) 183 | 184 | if self.default_union: 185 | if context == self.default_context: 186 | context = None 187 | else: 188 | if context is None: 189 | context = self.default_context 190 | 191 | if isinstance(p, Path): 192 | if context is None: 193 | context = self 194 | 195 | for s, o in p.eval(context, s, o): 196 | yield s, p, o 197 | else: 198 | for (s, p, o), cg in self.store.triples((s, p, o), context=context): 199 | if (isinstance(o, Literal) and (o.datatype == SCRIPT.python) and (self.isEnabled())): 200 | for (ss,pp,oo) in self.handleScript(( s, p, o),cg): 201 | yield (ss,pp,oo) 202 | else: 203 | yield s, p, o 204 | 205 | def quads( 206 | self, triple_or_quad: Optional[_TripleOrQuadPatternType] = None 207 | ) -> Generator[_OptionalQuadType, None, None]: 208 | """Iterate over all the quads in the entire conjunctive graph""" 209 | 210 | s, p, o, c = self._spoc(triple_or_quad) 211 | 212 | for (s, p, o), cg in self.store.triples((s, p, o), context=c): 213 | for ctx in cg: 214 | #yield s, p, o, ctx 215 | if (isinstance(o, Literal) and (o.datatype == SCRIPT.python)): 216 | for (ss,pp,oo) in self.handleScript(( s, p, o),ctx): 217 | yield (ss,pp,oo) 218 | else: 219 | yield s, p, o, ctx 220 | 221 | def triples_choices( 222 | self, 223 | triple: Union[ 224 | Tuple[List[_SubjectType], _PredicateType, _ObjectType], 225 | Tuple[_SubjectType, List[_PredicateType], _ObjectType], 226 | Tuple[_SubjectType, _PredicateType, List[_ObjectType]], 227 | ], 228 | context: Optional[_ContextType] = None, 229 | ) -> Generator[_TripleType, None, None]: 230 | """Iterate over all the triples in the entire conjunctive graph""" 231 | s, p, o = triple 232 | if context is None: 233 | if not self.default_union: 234 | context = self.default_context 235 | else: 236 | context = self._graph(context) 237 | # type error: Argument 1 to "triples_choices" of "Store" has incompatible type "Tuple[Union[List[Node], Node], Union[Node, List[Node]], Union[Node, List[Node]]]"; expected "Union[Tuple[List[Node], Node, Node], Tuple[Node, List[Node], Node], Tuple[Node, Node, List[Node]]]" 238 | # type error note: unpacking discards type info 239 | for (s1, p1, o1), cg in self.store.triples_choices((s, p, o), context=context): # type: ignore[arg-type] 240 | if (isinstance(o, Literal) and (o.datatype == SCRIPT.python)and (self.isEnabled())): 241 | for (ss,pp,oo) in self.handleScript((s1, p1, o1),cg): 242 | yield (ss,pp,oo) 243 | else: 244 | yield s1, p1, o1 245 | 246 | class IntelligentDataset(Intelligent, Dataset): 247 | None 248 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](IntelligentGraph.gif) 2 | # IntelligentGraph 3 | Python package that adds IntelligentGraph capabilities to RDFLib RDF graph package. 4 | 5 | IntelligentGraph introduces a special Literal value: a SCRIPT. These literals have a datatype of SCRIPT.python. 6 | When a SCRIPT-valued object is retrieved from the RDF store, the script is executed and the values returned from the execution of the script replace the SCRIPT-valued object. 7 | 8 | # Documentation 9 | 10 | Most of the documentation for IntelligentGraph can be found in RDFlib, see https://rdflib.readthedocs.io for its documentation built from the code. 11 | 12 | # Table of Contents 13 | 1. [Installation](#installation) 14 | 2. [Getting Started](#getting_started) 15 | 1. [Really simple start](#really_simple_start) 16 | 2. [Let's get a bit more real](#lets_get_a_bit_more_real) 17 | 3. [Fetching External Data ](#fetching_external_data) 18 | 4. [Summary](#summary) 19 | 4. [Script Writing](#script_writing) 20 | 5. [Controlling Intelligence](#controlling_intelligence) 21 | 6. [What Next?](#what_next) 22 | 1. [Data Analysis](#data_analysis) 23 | 2. [Integraion with IoT and IIoT](#integration_with_iot_and_iiot) 24 | 3. [Integration with Large Language Models (LLMs)](#integration_with_large_language_models_llms) 25 | 8. [Caveats](#caveats) 26 | 27 | # Installation 28 | The latest release of RDFLib may be installed with Python's package management tool pip. 29 | Since IntelligentGraph depends on rdflib, version >7 of rdflib will be installed. 30 | However, since IntelligentGraph is still experimental it is loaded directly from GitHub 31 | ```python 32 | $ pip install "git+https://github.com/peterjohnlawrence/IntelligentGraph.git" 33 | ``` 34 | Jupyter or Google Colab is a handy way of interacting with graphs. To install from within a cell 35 | ```python 36 | !pip install "git+https://github.com/peterjohnlawrence/IntelligentGraph.git" 37 | ``` 38 | # Getting Started 39 | 40 | IntelligentGraph follows the same pattern as RDFLib, since IntelligentGraph is derived from Graph. So everything that works for RDFLib works the same for IntelligentGraph. 41 | 42 | ## Really simple start 43 | 44 | The simplest example is to create an IntelkligentGraph with a single triple, whose value is a script that returns a literal. the value is return by assigning it to the predefined _result variable. We don't need a script to do this, but let's build up simply: 45 | ```python 46 | from intelligentgraph import IntelligentGraph,SCRIPT 47 | from rdflib import Literal, URIRef 48 | from rdflib.namespace import FOAF 49 | from datetime import date 50 | 51 | g = IntelligentGraph() 52 | iggy = URIRef("http://inova8.com/iggy") 53 | g.add((iggy, FOAF.birthday, Literal(date(1951, 3, 8)))) 54 | ``` 55 | We can query this graph (with one triple!) as follows: 56 | ```python 57 | for triple in g.triples( (None , None, None)): 58 | print(triple) 59 | ``` 60 | This returns the single triple result: subject, predicate, object 61 | ```python 62 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/birthday'), rdflib.term.Literal('1951-03-08', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#date'))) 63 | ``` 64 | Note that the object's script value has been replaced with a literal containing the xsd:date value that was returned from the script when it was evaluated. 65 | 66 | ## Let's get a bit more real 67 | 68 | If we wanted to know a person's age, we could of course query this graph, and as part of the SPARQL query, or Python code handling the returned values, calculate the age in years. For example 69 | ```python 70 | s = URIRef("http://inova8.com/ig") 71 | from rdflib.namespace import FOAF 72 | from datetime import date 73 | for triple in g.triples( (s , FOAF.birthday, None)): 74 | age= int((date.today()-triple[2].toPython()).days/365.25) 75 | print (age) 76 | ``` 77 | The result of which is: 78 | ```python 79 | 72 80 | ``` 81 | However, if we were to share the graph with someone, they would not have access to this code unless we shared that as well. Why not incorporate the age calculation *within* the graph? This is analogous to a spreadsheet in which some cell values are literals whilst others are calculations based on other cell values. 82 | Let's add a calculation script for the FOAF:age as follows. 83 | Note that the script will be initialized with values as follows: 84 | - The value 's' is supplied to the script as the subject of the triple with which the script is associated as the object. 85 | - The predicate of the same triples is supplied a variable 'p'. 86 | - If we are using 'quads' then the context is provided as variable 'ctx'. 87 | - Finally, the graph within which the triple is defined is provided as variable 'g' 88 | 89 | 90 | ```python 91 | g.add((ig, FOAF.age, Literal(''' 92 | from rdflib.namespace import FOAF 93 | from datetime import date 94 | for triple in g.triples( (s , FOAF.birthday, None)): 95 | age= int((date.today()-triple[2].toPython()).days/365.25) 96 | _result = age''',datatype=SCRIPT.python))) 97 | ``` 98 | We can view the calculated graph using 99 | ```python 100 | print(g.serialize(format="n3")) 101 | ``` 102 | Which returns the following graph in n3 format. Again, please note that the scripts have been replaced by their calculated equivalent. 103 | ```python 104 | @prefix foaf: . 105 | @prefix xsd: . 106 | foaf:age 72 ; 107 | foaf:birthday "1951-03-08"^^xsd:date .\n\n 108 | ``` 109 | 110 | ## Fetching External Data 111 | 112 | There are many occasions when we want to merge a graph with external information. Usually, this is done by running some code that retrieves the triples from the external data source, such as an IoT server. This data then has to be merged with the underlying graph. 113 | IntelligentGraph offers a better alternative: add an agent *within* the graph that pulls this external data just-in-time, instead of just-in-case. 114 | 115 | Let's start by simulating an external service that returns the FOAF:knows triples about a particular individual. In reality, we will use an external service (https://random-word-api.herokuapp.com) that generates random names. 116 | ```python 117 | s = URIRef("http://inova8.com/ig") 118 | import requests 119 | def getKnows(individual): 120 | response = requests.get("https://random-word-api.herokuapp.com/word?lang=en&number=5") 121 | for word in response.json(): 122 | yield (individual, FOAF.knows, URIRef("http://inova8.com/"+word)) 123 | for triple in getKnows(s): 124 | print(triple) 125 | ``` 126 | If we were to run this outside of the graph, it would return triples something like this (remember the values are random): 127 | ```python 128 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/sandpapery')) 129 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/trimotors')) 130 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/apostrophe')) 131 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/flyspecking')) 132 | (rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/grooving')) 133 | ``` 134 | Instead of merging these two graphs, let's add an agent script that returns these results. we use the 'yield' pattern so that a script need not fetch all results. Instead, yield allows each value to be fetced on request: 135 | ```python 136 | g.add((ig, FOAF.knows, Literal(''' 137 | import requests 138 | def getKnows(individual): 139 | response = requests.get("https://random-word-api.herokuapp.com/word?lang=en&number=5") 140 | for word in response.json(): 141 | yield (individual, FOAF.knows, URIRef("http://inova8.com/"+word)) 142 | _result = getKnows(s)''',datatype=SCRIPT.python))) 143 | ``` 144 | We can again view the entire graph simply by serializing it as follows: 145 | ```python 146 | print(g.serialize(format="n3")) 147 | ``` 148 | ```python 149 | @prefix foaf: . 150 | @prefix xsd: . 151 | 152 | foaf:age 72 ; 153 | foaf:birthday "1951-03-08"^^xsd:date ; 154 | foaf:knows , 155 | , 156 | , 157 | , 158 | . 159 | ``` 160 | ## Summary 161 | 162 | In this example, the asserted graph only contains three statements, each of which has a script for an object value: 163 | ```python 164 | @prefix foaf: . 165 | 166 | foaf:birthday """from datetime import date 167 | _result =date(1951, 3, 8)"""^^ ; 168 | foaf:age """ 169 | from rdflib.namespace import FOAF 170 | from datetime import date 171 | for triple in g.triples( (s , FOAF.birthday, None)): 172 | age= int((date.today()-triple[2].toPython()).days/365.25) 173 | _result = age"""^^ ; 174 | 175 | foaf:knows """ 176 | import requests 177 | def getKnows(individual): 178 | response = requests.get("https://random-word-api.herokuapp.com/word?lang=en&number=5") 179 | for word in response.json(): 180 | yield (individual, FOAF.knows, URIRef("http://inova8.com/"+word)) 181 | _result = getKnows(s)"""^^ . 182 | ``` 183 | When queried as an IntelligentGraph, it will appear that the graph contains the following: 184 | ```python 185 | @prefix foaf: . 186 | @prefix xsd: . 187 | 188 | foaf:age 72 ; 189 | foaf:birthday "1951-03-08"^^xsd:date ; 190 | foaf:knows , 191 | , 192 | , 193 | , 194 | . 195 | ``` 196 | # Script Writing 197 | 198 | Scripts are any valid Python. 199 | 200 | Context is provided to each script in the form of the following variables: 201 | 202 | - g: The IntelligentGraph object that contains the triples (or quads). This object can be 203 | - s: The subject node of the triple 204 | - p: The predicate node of the triple 205 | - o: The object node of the triple. This node is a literal containing the script. 206 | - ctx: the context of the triple. In the case of a conjunctive graph or dataset, it is the particular graph dataset that contains the triple. 207 | 208 | The result of the script is returned by assigning the value to _result. 209 | The _result value can be any of the following types: 210 | - A Python scalar, which will be converted to a corresponding literal scalar 211 | - A RDFLib Literal 212 | - A RDFLib URIRef 213 | - A triple 214 | - A set of triples, using a generator that yields each triple when requested. 215 | 216 | # Controlling Intelligence 217 | 218 | The capabilities of an IntelligentGraph to evaluate a script can be disabled with 219 | 220 | - IntelligentGraph.disableIntelligence() 221 | 222 | After which the IntelligentGraph behaves as a 'normal' RDFLib Graph. RTghis is useful if one wants to, say, serialize the graph. 223 | 224 | Intelligence (aka evaluation of scripts) is reenabled with: 225 | 226 | - IntelligentGraph.enableIntelligence() 227 | 228 | To check if an IntelligentGraph has intelligence enabled use: 229 | 230 | - IntelligentGrapg.isEnabled() 231 | 232 | # What Next? 233 | IntelligentGraph opens up all sorts of data analysis capabilities which can now become agents within the graph rather than external code. 234 | 235 | ## Data Analysis 236 | 237 | Often data analysis is done within a spreadsheet because it is so easy to add calculated columns, as well as aggregate column values. This can be performed just as easily within the IntelligentGraph: 238 | 239 | - Each class is another spreadsheet. 240 | - Consider each instance of that class or 'entity', aka subject of a triple, as the identity of the row. 241 | - Each property of the entity then becomes another column. 242 | - Aggregations are the properties associated with the class of the individual entities 243 | 244 | ## Integration with IoT and IIoT 245 | 246 | Internet of Things (IoT) and Industrial Internet of Things (IIoT) provide a source for all sorts of measurements. However, these IoT and IIoT systems often do not understand the context from which these measurements are taken. A graph model of the plant, building, geographical area, etc is the best way to capture that context. But then we are missing the actual measurements. IntelligentGraph allows agents within the context model to pull information in from the IoT or IIoT server just-in-time, rather than pushing as much information as one can into the graph just-in-case. Since these measurements are available within the graph, just like any other asserted triple, analysis agents can also be added to the graph to create a truly intelligent graph. 247 | 248 | ## Integration with Large Language Models (LLMs) 249 | 250 | Clearly, IntelligentGraph can pull structured data from external systems such as IoT and merge it with the existing asserted graph. LLM (Large Language Models) such as ChatGPT, Bard, LLama and others have opened up the possibility of merging unstructured data from the world of LLMs with the structure of graphs. 251 | 252 | An example Jupyter/Colab notebook demonstrating its use is here: https://github.com/peterjohnlawrence/IntelligentGraph/blob/main/IntelligentGraph%2BLLM.ipynb 253 | 254 | # Caveats 255 | - Scripts are evaluated using the Python exec() function. This can open expose you to malicious attacks if you allow open access to your intelligentGraphs. 256 | - Is IntelligentGraph fully debugged and tested? No, but to the best of my abilities. 257 | - IntelligentGraph does not cache retrieved results, ensuring that no results can become stale. However, this will come with a performance penalty in some cases. 258 | -------------------------------------------------------------------------------- /GettingStarted.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"toc_visible":true,"authorship_tag":"ABX9TyPSA2oAVJ7GebgXfK9i/oHn"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"markdown","source":["# Getting Started\n","\n","IntelligentGraph follows the same pattern as RDFLib, since IntelligentGraph is derived from Graph. So everything that works for RDFLib works the same for IntelligentGraph."],"metadata":{"id":"la_r7SAvYHuq"}},{"cell_type":"markdown","source":["## Installation\n","\n","The latest release of RDFLib may be installed with Python's package management tool pip. Since IntelligentGraph depends on rdflib, version >7 of rdflib will be installed. However, since IntelligentGraph is still experimental it is loaded directly from GitHub"],"metadata":{"id":"rklEnA5JYbLS"}},{"cell_type":"code","source":["!pip install \"git+https://github.com/peterjohnlawrence/IntelligentGraph.git\""],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fix-uuH5YgnY","executionInfo":{"status":"ok","timestamp":1703180761800,"user_tz":0,"elapsed":17782,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"e160bced-1045-4ee8-a421-abd5d33c3fda"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["Collecting git+https://github.com/peterjohnlawrence/IntelligentGraph.git\n"," Cloning https://github.com/peterjohnlawrence/IntelligentGraph.git to /tmp/pip-req-build-r0a9embc\n"," Running command git clone --filter=blob:none --quiet https://github.com/peterjohnlawrence/IntelligentGraph.git /tmp/pip-req-build-r0a9embc\n"," Resolved https://github.com/peterjohnlawrence/IntelligentGraph.git to commit 20cfcb1b992e645b4448a88aa89756d28dd5f4a1\n"," Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n","Collecting RDFLib>=7.0 (from IntelligentGraph==0.9.0)\n"," Downloading rdflib-7.0.0-py3-none-any.whl (531 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m531.9/531.9 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hCollecting isodate<0.7.0,>=0.6.0 (from RDFLib>=7.0->IntelligentGraph==0.9.0)\n"," Downloading isodate-0.6.1-py2.py3-none-any.whl (41 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m41.7/41.7 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hRequirement already satisfied: pyparsing<4,>=2.1.0 in /usr/local/lib/python3.10/dist-packages (from RDFLib>=7.0->IntelligentGraph==0.9.0) (3.1.1)\n","Requirement already satisfied: six in /usr/local/lib/python3.10/dist-packages (from isodate<0.7.0,>=0.6.0->RDFLib>=7.0->IntelligentGraph==0.9.0) (1.16.0)\n","Building wheels for collected packages: IntelligentGraph\n"," Building wheel for IntelligentGraph (setup.py) ... \u001b[?25l\u001b[?25hdone\n"," Created wheel for IntelligentGraph: filename=IntelligentGraph-0.9.0-py3-none-any.whl size=9022 sha256=08b2ccd8261a81725ae4840c88da5ba475a1ef0d3336e5c0bcbcc43a3f304a29\n"," Stored in directory: /tmp/pip-ephem-wheel-cache-07m5pwsh/wheels/22/92/0f/992eb2e9d779860f2cfa4e85160e886f0bc904eba6ecd09d81\n","Successfully built IntelligentGraph\n","Installing collected packages: isodate, RDFLib, IntelligentGraph\n","Successfully installed IntelligentGraph-0.9.0 RDFLib-7.0.0 isodate-0.6.1\n"]}]},{"cell_type":"markdown","source":["## Really simple start\n","\n","The simplest example is to create an IntelkligentGraph with a single triple, whose value is a script that returns a literal. the value is return by assigning it to the predefined _result variable. We don't need a script to do this, but let's build up simply:"],"metadata":{"id":"_oA-wKTEYOMz"}},{"cell_type":"code","execution_count":2,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"9IqD3k7qYByv","executionInfo":{"status":"ok","timestamp":1703180762221,"user_tz":0,"elapsed":423,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"f1c818af-f641-4eeb-dfb3-577a964275d4"},"outputs":[{"output_type":"execute_result","data":{"text/plain":[")>"]},"metadata":{},"execution_count":2}],"source":["import intelligentgraph\n","from intelligentgraph import IntelligentConjunctiveGraph, IntelligentDataset,IntelligentGraph,SCRIPT\n","from rdflib import Literal, URIRef\n","from rdflib.namespace import FOAF\n","from datetime import date\n","g = IntelligentGraph()\n","ig = URIRef(\"http://inova8.com/ig\")\n","g.add((ig, FOAF.birthday, Literal('''from datetime import date\n","_result =date(1951, 3, 8)''',datatype=SCRIPT.python)))"]},{"cell_type":"markdown","source":["We can query this graph (with one triple!) as follows:"],"metadata":{"id":"qt0sASnaY4oJ"}},{"cell_type":"code","source":["for triple in g.triples( (None , None, None)):\n"," print(triple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"IBL0V-36Y6m4","executionInfo":{"status":"ok","timestamp":1703180762221,"user_tz":0,"elapsed":5,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"3813396e-7677-40a0-af93-8c63e14350db"},"execution_count":3,"outputs":[{"output_type":"stream","name":"stdout","text":["(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/birthday'), rdflib.term.Literal('1951-03-08', datatype=rdflib.term.URIRef('http://www.w3.org/2001/XMLSchema#date')))\n"]}]},{"cell_type":"markdown","source":["Note that the object's script value has been replaced with a literal containing the xsd:date value that was returned from the script when it was evaluated."],"metadata":{"id":"BRkcM6yPY9HZ"}},{"cell_type":"markdown","source":["## Let's get a bit more real\n","If we wanted to know a person's age, we could of course query this graph, and as part of the SPARQL query, or Python code handling the returned values, calculate the age in years. For example"],"metadata":{"id":"EcMdoMXzY_yI"}},{"cell_type":"code","source":["s = URIRef(\"http://inova8.com/ig\")\n","\n","for triple in g.triples( (s , FOAF.birthday, None)):\n"," age= int((date.today()-triple[2].toPython()).days/365.25)\n"," print (age)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"NBffgp7sY_Lx","executionInfo":{"status":"ok","timestamp":1703180762221,"user_tz":0,"elapsed":4,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"f272f136-8110-46e8-b6d7-9bfe0495ecf9"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stdout","text":["72\n"]}]},{"cell_type":"markdown","source":["However, if we were to share the graph with someone, they would not have access to this code unless we shared that as well. Why not incorporate the age calculation within the graph? This is analogous to a spreadsheet in which some cell values are literals whilst others are calculations based on other cell values. Let's add a calculation script for the FOAF:age as follows. Note that the script will be initialized with values as follows:\n","\n","- The value 's' is supplied to the script as the subject of the triple with which the script is associated as the object.\n","- The predicate of the same triples is supplied a variable 'p'.\n","- If we are using 'quads' then the context is provided as variable 'ctx'.\n","- Finally, the graph within which the triple is defined is provided as variable 'g'"],"metadata":{"id":"a8XJ3Ix6ZliA"}},{"cell_type":"code","source":["g.add((ig, FOAF.age, Literal('''\n","from rdflib.namespace import FOAF\n","from datetime import date\n","for triple in g.triples( (s , FOAF.birthday, None)):\n"," age= int((date.today()-triple[2].toPython()).days/365.25)\n"," _result = age''',datatype=SCRIPT.python)))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"vXRogZ1qZtIG","executionInfo":{"status":"ok","timestamp":1703180762221,"user_tz":0,"elapsed":3,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"30c82168-d3bd-4dee-8846-08a563d39955"},"execution_count":5,"outputs":[{"output_type":"execute_result","data":{"text/plain":[")>"]},"metadata":{},"execution_count":5}]},{"cell_type":"markdown","source":["We can view the calculated graph using"],"metadata":{"id":"pdQFDEdpZv23"}},{"cell_type":"code","source":["print(g.serialize(format=\"n3\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"BmLLUlsyZ0GW","executionInfo":{"status":"ok","timestamp":1703180762221,"user_tz":0,"elapsed":3,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"c4f6bd26-d962-41f8-ba53-a1b42369651f"},"execution_count":6,"outputs":[{"output_type":"stream","name":"stdout","text":["@prefix foaf: .\n","@prefix xsd: .\n","\n"," foaf:age 72 ;\n"," foaf:birthday \"1951-03-08\"^^xsd:date .\n","\n","\n"]}]},{"cell_type":"markdown","source":["## Fetching External Data\n","\n","There are many occasions when we want to merge a graph with external information. Usually, this is done by running some code that retrieves the triples from the external data source, such as an IoT server. This data then has to be merged with the underlying graph.\n","IntelligentGraph offers a better alternative: add an agent *within* the graph that pulls this external data just-in-time, instead of just-in-case.\n","\n","Let's start by simulating an external service that returns the FOAF:knows triples about a particular individual. In reality, we will use an external service (https://random-word-api.herokuapp.com) that generates random names."],"metadata":{"id":"Rl9S9EtPaiQW"}},{"cell_type":"code","source":["s = URIRef(\"http://inova8.com/ig\")\n","import requests\n","def getKnows(individual):\n"," response = requests.get(\"https://random-word-api.herokuapp.com/word?lang=en&number=5\")\n"," for word in response.json():\n"," yield (individual, FOAF.knows, URIRef(\"http://inova8.com/\"+word))\n","for triple in getKnows(s):\n"," print(triple)"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"LyEHIgniamWm","executionInfo":{"status":"ok","timestamp":1703180762702,"user_tz":0,"elapsed":483,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"51b3eff6-0023-4d4c-ed1b-8cab9ea996ba"},"execution_count":7,"outputs":[{"output_type":"stream","name":"stdout","text":["(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/yeasayers'))\n","(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/massifs'))\n","(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/tittivate'))\n","(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/reechy'))\n","(rdflib.term.URIRef('http://inova8.com/ig'), rdflib.term.URIRef('http://xmlns.com/foaf/0.1/knows'), rdflib.term.URIRef('http://inova8.com/skreighing'))\n"]}]},{"cell_type":"markdown","source":["Instead of merging these two graphs, let's add an agent script that returns these results. we use the 'yield' pattern so that a script need not fetch all results. Instead, yield allows each value to be fetched on request:"],"metadata":{"id":"uuPowcqra4hN"}},{"cell_type":"code","source":["g.add((ig, FOAF.knows, Literal('''\n","import requests\n","def getKnows(individual):\n"," response = requests.get(\"https://random-word-api.herokuapp.com/word?lang=en&number=5\")\n"," for word in response.json():\n"," yield (individual, FOAF.knows, URIRef(\"http://inova8.com/\"+word))\n","_result = getKnows(s)''',datatype=SCRIPT.python)))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"EJt7vc06bBj8","executionInfo":{"status":"ok","timestamp":1703180762703,"user_tz":0,"elapsed":4,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"1d225ba4-a4db-4a35-87fb-51002ff7780d"},"execution_count":8,"outputs":[{"output_type":"execute_result","data":{"text/plain":[")>"]},"metadata":{},"execution_count":8}]},{"cell_type":"markdown","source":["We can again view the entire graph simply by serializing it as follows:"],"metadata":{"id":"OTipaTPtbGlM"}},{"cell_type":"code","source":["print(g.serialize(format=\"n3\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"IQsoA2P0bIlU","executionInfo":{"status":"ok","timestamp":1703180764389,"user_tz":0,"elapsed":1688,"user":{"displayName":"Peter Lawrence","userId":"18117469452547748318"}},"outputId":"cc8efd00-ddb6-48d4-9272-78a8f568bd4e"},"execution_count":9,"outputs":[{"output_type":"stream","name":"stdout","text":["@prefix foaf: .\n","@prefix xsd: .\n","\n"," foaf:age 72 ;\n"," foaf:birthday \"1951-03-08\"^^xsd:date ;\n"," foaf:knows ,\n"," ,\n"," ,\n"," ,\n"," .\n","\n","\n"]}]},{"cell_type":"markdown","source":["## Summary\n","\n","In this example, the asserted graph only contains three statements, each of which has a script for an object value:"],"metadata":{"id":"YMHQB3rWbOQD"}},{"cell_type":"markdown","source":["```python\n","@prefix foaf: .\n","\n"," foaf:birthday \"\"\"from datetime import date\n"," _result =date(1951, 3, 8)\"\"\"^^ ;\n"," foaf:age \"\"\"\n"," from rdflib.namespace import FOAF\n"," from datetime import date\n"," for triple in g.triples( (s , FOAF.birthday, None)):\n"," age= int((date.today()-triple[2].toPython()).days/365.25)\n"," _result = age\"\"\"^^ ;\n","\n"," foaf:knows \"\"\"\n"," import requests\n"," def getKnows(individual):\n"," response = requests.get(\"https://random-word-api.herokuapp.com/word?lang=en&number=5\")\n"," for word in response.json():\n"," yield (individual, FOAF.knows, URIRef(\"http://inova8.com/\"+word))\n"," _result = getKnows(s)\"\"\"^^ .\n"," ```"],"metadata":{"id":"YCytWosuc8Dp"}},{"cell_type":"markdown","source":["When queried as an IntelligentGraph, it will appear that the graph contains the following:\n","```python\n","@prefix foaf: .\n","@prefix xsd: .\n","\n"," foaf:age 72 ;\n"," foaf:birthday \"1951-03-08\"^^xsd:date ;\n"," foaf:knows ,\n"," ,\n"," ,\n"," ,\n"," .\n","```"],"metadata":{"id":"HqrDigcOeir-"}}]} --------------------------------------------------------------------------------