<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Herambh Athavale on Medium]]></title>
        <description><![CDATA[Stories by Herambh Athavale on Medium]]></description>
        <link>https://medium.com/@herambh?source=rss-23cde6b9cfd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pNAQWLvQZNmaJEg6.png</url>
            <title>Stories by Herambh Athavale on Medium</title>
            <link>https://medium.com/@herambh?source=rss-23cde6b9cfd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@herambh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Augmented Reality and Google Gemini Pro Vision: Evaluating an AR use case using simple Flask app]]></title>
            <link>https://medium.com/@herambh/augmented-reality-and-google-gemini-pro-vision-evaluating-an-ar-use-case-using-simple-flask-app-9940c2aded7b?source=rss-23cde6b9cfd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9940c2aded7b</guid>
            <category><![CDATA[google-gemini-pro]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <dc:creator><![CDATA[Herambh Athavale]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 22:41:06 GMT</pubDate>
            <atom:updated>2024-02-05T15:12:40.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNwZUQaAErB5tNLaa_ON2A.jpeg" /></figure><h3>Introduction</h3><p>Image LLMs such as Google Gemini Pro Vision possess a mix of computer vision capabilities and natural language processing that can be leveraged for Augmented Reality applications. Imagine using your AR headset looking at an image, or a document, and wanting to obtain a quick summary of what you are looking at. Or may be you had a specific question to ask when viewing your own messy room like, ‘How do I get started with cleaning my room?’ Imagine looking at a web page and thinking, ‘What are the key takeaways from this article that I am reading?’.</p><p>Or imagine reading through a large document of 30+ pages, and wondering, ‘Can I get a summary of this document to evaluate if I am interested in reading this further?’ This will be particularly useful when you have little context about what you are looking at. In other cases, when looking at a document in a different language, this can help translate and provide a gist. These are potential use cases where such an AR app can help.</p><h3>Google Gemini Pro Vision</h3><p>Google Gemini Pro advertises itself as a cutting edge platform that delivers groundbreaking advances in augmented reality (AR). Gemini Pro Vision claims to have the ability to drive immersive experiences by blending digital seamlessly with our surroundings.</p><p>In this article I try to validate this by presenting an image to Gemini Pro Vision and asking it a question. For this I have constructed a simple image summarizer app. From the perspective of an AR headset user, where when asked to make sense of what the user is seeing, Gemini Pro Vision should help interpret this for the user.</p><h3>The Image Summarizer App</h3><p>The image summarizer app can be thought of as a test bed for an AR application. Inputs are served as a PDF image and the app provides a quick summary of the same. If presented with a PDF of multiple images or a long article, the app can summarize this page by page. This app has been built using Flask, a popular micro-web framework known for its simplicity, and very extendible when needed. Here are the steps you can use to set this up for your own investigation.</p><h4>Getting Started</h4><p>The first step is to set up a python virtual environment using steps as highlighted on the <a href="https://flask.palletsprojects.com/en/2.3.x/installation/">Flask website</a>. Ensure you have the activated the virtual environment, and installed the required packages such as Flask, werkzeug.utils, PDF2Image, PIL or Pillow, and Google Generative AI packages.</p><blockquote><em>Note:<br></em>PIL is deprecated, but this example uses it by installing Pillow.<br>Google Generative AI by running pip install google-generativeai. See <a href="https://pypi.org/project/google-generativeai/">link</a>.</blockquote><p>Flask can be started by executing flask run from the project folder.</p><h4>The Application</h4><p><em>app.py :</em></p><pre>import os<br> from flask import Flask, render_template, request, redirect, url_for, session<br> from werkzeug.utils import secure_filename<br> from pdf2image import convert_from_path<br> from PIL import Image<br> import google.generativeai as genai<br> ​<br> ​<br> app = Flask(__name__)<br> app.config[&#39;UPLOAD_FOLDER&#39;] = &#39;uploads/&#39;<br> app.config[&#39;IMAGE_FOLDER&#39;] = &#39;images/&#39;<br> app.secret_key = &#39;MyVERYSecretKey&#39;  # Security key for sessions<br> ​<br> @app.route(&#39;/&#39;)<br> def home():<br>     return render_template(&#39;index.html&#39;)<br> ​<br> @app.route(&#39;/upload&#39;, methods=[&#39;POST&#39;])<br> def upload_file():<br>     if request.method == &#39;POST&#39;:<br>         # Check if the post request has the file part<br>         if &#39;file&#39; not in request.files:<br>             return redirect(request.url)<br>         file = request.files[&#39;file&#39;]<br>         # If the user does not select a file, the browser submits an<br>         # empty file without a filename.<br>         if file.filename == &#39;&#39;:<br>             return redirect(request.url)<br>         if file:<br>             filename = secure_filename(file.filename)<br>             file.save(os.path.join(app.config[&#39;UPLOAD_FOLDER&#39;], filename))<br>             # Redirect to home or a confirmation page <br>             return redirect(url_for(&#39;home&#39;))<br>             <br>     return redirect(url_for(&#39;home&#39;))<br> ​<br> @app.route(&#39;/submit_text&#39;, methods=[&#39;POST&#39;])<br> def submit_text():<br>     prompt = request.form.get(&#39;text_input&#39;)<br>     if prompt == &quot;&quot;:<br>       prompt =&quot;Summarize the content on this page.&quot; <br> ​<br>     if request.method == &#39;POST&#39;:<br>         session[&#39;response&#39;] = &quot;&quot;<br>         upload_folder_path = app.config[&#39;UPLOAD_FOLDER&#39;]<br>         image_folder_path = app.config[&#39;IMAGE_FOLDER&#39;]<br>         for filename in os.listdir(upload_folder_path):<br>             if filename.endswith(&quot;.pdf&quot;):<br>                 images = convert_from_path(os.path.join(upload_folder_path, filename))<br>                 for i in range(len(images)):<br>                     images[i].save(os.path.join(app.config[&#39;IMAGE_FOLDER&#39;], &#39;page-&#39;+ str(i) + &#39;.jpg&#39;))<br> ​<br>         for filename in sorted(os.listdir(image_folder_path)):<br>             if filename.endswith(&quot;.jpg&quot;):<br>                 image_path = os.path.join(image_folder_path, filename)<br>                 try:<br>                     with Image.open(image_path) as image:<br>                         print(f&quot;Processing image: {image_path}&quot;)  # Example action<br>                         genai.configure(api_key=&quot;GeminiAIKEYGoesHere&quot;)<br>                         model = genai.GenerativeModel(&#39;gemini-pro-vision&#39;)<br>                         response = model.generate_content(image)<br>                         response = model.generate_content([prompt , image], stream=False)<br>                         response.resolve()<br>                         for chunk in response:<br>                             session[&#39;response&#39;] = session[&#39;response&#39;] + &quot; \n &quot; + filename + &quot; &lt;hr&gt; &quot; + chunk.text + &quot;  \n &lt;hr&gt;&quot;<br>                             print(session[&#39;response&#39;])<br> ​<br> ​<br>                 except OSError as e:<br>                     print(f&quot;Error processing image {image_path}: {e}&quot;)<br> ​<br>     print(&quot;Deleting uploaded files...&quot;)<br>     delete_all_files()<br>     return redirect(url_for(&#39;home&#39;))<br> ​<br>         <br> if __name__ == &#39;__main__&#39;:<br>     app.run(debug=True)</pre><h4>The Web UI</h4><p>The Web UI is a simple <em>index.html</em> page in the templates folder:</p><pre>&lt;!DOCTYPE html&gt;<br> &lt;html lang=&quot;en&quot;&gt;<br> &lt;head&gt;<br>     &lt;meta charset=&quot;UTF-8&quot;&gt;<br>     &lt;title&gt;What I am looking at&lt;/title&gt;<br>     &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;style.css&#39;) }}&quot;&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br>     &lt;header&gt;<br>         &lt;h3&gt;What am I looking at?&lt;/h3&gt;<br>     &lt;/header&gt;<br> ​<br>     &lt;h4&gt;Upload a PDF image of what you need summarized or interpreted.&lt;/h4&gt;<br>     &lt;form id=&quot;form1&quot; action=&quot;/upload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>         &lt;input type=&quot;file&quot; name=&quot;file&quot;&gt;<br>         &lt;input type=&quot;submit&quot; value=&quot;Upload&quot;&gt;<br>     &lt;/form&gt;<br> ​<br>     &lt;hr&gt;<br> ​<br>     &lt;h4&gt;Ask any question you had about about the uploaded PDF. &lt;/h4&gt;<br>     &lt;form id=&quot;form2&quot; action=&quot;/submit_text&quot; method=&quot;post&quot;&gt;<br>         &lt;textarea name=&quot;text_input&quot; rows=&quot;2&quot; cols=&quot;50&quot;&gt;&lt;/textarea&gt;<br>         &lt;input type=&quot;submit&quot; value=&quot;Ask a question.&quot;&gt;<br>     &lt;/form&gt;<br> ​<br>     &lt;hr&gt;<br> ​<br>     &lt;div id=&quot;response_area&quot;&gt;<br>         &lt;p&gt;<br>           {{session[&#39;response&#39;]|safe}}<br>         &lt;/p&gt;<br>     &lt;/div&gt;<br> &lt;/body&gt;<br> &lt;/html&gt;</pre><p>Pick any CSS that would help beautify the above page as needed. This needs to go into the static folder.</p><blockquote>Note:<br>The UPLOAD FOLDER is set as uploads/<br>The IMAGES FOLDER is set as images/<br>Ensure that both these folders are deleted of their contents at the end of the operation.</blockquote><h3>Callouts</h3><p>This is not a production ready app and hence care must be taken before publishing this for public or general use. Note that api_key is embedded within the app.py code, which is not best practice. It has been masked for the purposes of this article. Also, rendering the display using {{session[&#39;response&#39;]|safe}} is an entry point for a potential XSS attacks. The purpose of this article is not to deliver a production ready app, but to illustrate a concept. Do not use the above code besides for your own exploration and understanding of the current AI, AR scenario. Review any copyrights, fair use guidelines for images or pdfs being used, before using the same on this application.</p><h3>Using the App</h3><p><em>Example 1: A random photo of a living space.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9W_7SQ1TQ6aDL5qjn6BEHQ.png" /><figcaption>The Flask Application Interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*g-A0k1POvQn46b_SwgD9hw.png" /><figcaption>MyMessyRoom PDF file uploaded</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNIJ_sVniY8U7FBBF2Vgcw.png" /><figcaption>The prompt provided</figcaption></figure><p><em>The Result :</em></p><pre>1. **Start by decluttering.** This is the most important step, and it will make everything else easier. Go through your room and get rid of anything you don&#39;t use or need. Be ruthless! If you haven&#39;t used it in the past year, it&#39;s probably time to let it go.<br>2. **Clean your room thoroughly.** Once you&#39;ve decluttered, it&#39;s time to clean. Dust, vacuum, and mop the floors. Clean your windows and mirrors. Get rid of any cobwebs. Make sure your room is spotless.<br>3. **Rearrange your furniture.** This is a great way to give your room a fresh look. Try moving your bed to a different wall or rearranging your dresser and desk. You might be surprised at how much difference it makes.<br>4. **Add some personal touches.** Hang some posters or pictures on the walls. Put up a shelf and display some of your favorite books or knick-knacks. Add a few plants to bring some life into the room.<br>5. **Make your bed.** This is one of the simplest things you can do, but it makes a big difference. Make your bed every morning, and it will help your room look more put-together.<br>​6. **Keep your room tidy.** The key to keeping your room clean is to tidy up every day. Put things away after you use them, and don&#39;t let clutter build up. A few minutes of tidying up each day will make a big difference.</pre><p><em>Example 2: Looking at the first 3 pages of a Wikipedia article on the Mexican American War:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8Kfs0DosfzVeZGHDfjXJw.png" /><figcaption>Uploading a PDF containing the first 3 pages of a Wikipedia article.</figcaption></figure><p>Note the <a href="https://en.wikipedia.org/wiki/Mexican%E2%80%93American_War">Wikipedia article</a> being referred…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Vpbs9iGBTPjj3lqQuCHaw.png" /><figcaption>The prompt provided.</figcaption></figure><p><em>The Result:</em></p><pre>The key takeaways from the article you are reading are:<br> ​<br> 1. The Mexican-American War was a war between the United States and Mexico that lasted from 1846 to 1848.<br> 2. The war resulted in the United States gaining control of Texas, as well as the present-day states of California, Nevada, Utah, Arizona, and New Mexico.<br> 3. The war was a significant event in the history of both the United States and Mexico.</pre><h3>Costs</h3><p>Google Gemini Pro Vision itself is priced at US $0.0025 / image, US$0.002 / second , or US$0.00025 / 1k characters. Assuming approximately 2000 images, or approximately 50–100 tasks taking around 30 seconds each each day, approximately translates to $5 a day, or $150 a month of heavy personal use. An AR application that leverages this service is likely to net $50 per user per month considering a simple 25% premium over service costs.</p><p>Another service to consider is Amazon Rekognition that allows for Content Moderation, Face Detection, Text Detection, Celebrity Recognition, among other features. Costs can be evaluated using <a href="https://calculator.aws/#/createCalculator/Rekognition">pricing calculators</a>. However, similar usage is likely to have similar costs.</p><h3>Conclusion</h3><p>Augmented reality has the potential for significantly altering our lives in the near to distant future. It has the ability to provide new applications and services in Retail, Healthcare, Education, Manufacturing, and a host of other industries. It will transform how we learn or connect with others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9940c2aded7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Neo4J Graphs using Python]]></title>
            <link>https://medium.com/@herambh/creating-neo4j-graphs-using-python-bd59662cbad6?source=rss-23cde6b9cfd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd59662cbad6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neo4j-graph-database]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Herambh Athavale]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 23:56:19 GMT</pubDate>
            <atom:updated>2024-01-29T00:13:02.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*hW5B1Jz3T17CNTHGq1OQJA.jpeg" /></figure><h3>Introduction</h3><p>Graphs are a unique data structure that can be used to represent relationships between data in a way that traditional relational databases cannot. Neo4j is a popular graph database that allows users to create and manipulate graphs using a powerful query language called Cypher. Python is a popular programming language that can be used to interact with Neo4j and create graphs in a variety of ways. In this article, we explore the different ways to create graphs in Neo4j using Python.</p><h3>Setting up a Neo4J running instance</h3><p>There are different ways of getting started with a Neo4J instance. One can download the latest version of Neo4j Desktop from the official website <a href="https://neo4j.com/deployment-center/">https://neo4j.com/deployment-center/</a> . This was the was the preferred way to get started a couple of years back. More recently, Neo4j recommends starting a free instance of Neo4J Aura DB on the Cloud. This is supported by GCP or AWS. For the sake of this article, we will leverage a free AuraDB instance (for more details : <a href="https://neo4j.com/cloud/aura-free/">https://neo4j.com/cloud/aura-free/</a>)</p><h3>Ways to connect to Neo4j via Python</h3><h4>1. Using the Py2Neo Library</h4><p><em>Py2Neo</em> is a Python library that provides a simple and intuitive way to interact with Neo4j. It allows users to create nodes and relationships in a graph, as well as perform queries using Cypher. Here is an example of how to create a graph using py2neo:</p><pre>from py2neo import Graph, Node, Relationship<br> ​<br> # Create a graph object<br> graph = Graph(&quot;neo4j+s://c8xxxxxx.databases.neo4j.io:7687&quot;, auth=(&quot;neo4j&quot;, &quot;pA5sw0rD&quot;))<br> ​<br> # Create a node representing a person<br> person = Node(&quot;Person&quot;, name=&quot;John Doe&quot;)<br> graph.create(person)<br> ​<br> # Create a node representing a movie<br> movie = Node(&quot;Movie&quot;, title=&quot;The Matrix&quot;)<br> graph.create(movie)<br> ​<br> # Create a relationship between the person and the movie<br> person_movie = Relationship(person, &quot;LOVES&quot;, movie)<br> graph.create(person_movie)</pre><p>This code creates a graph with two nodes, representing a person and a movie, and a relationship between them indicating that the person loves the movie. Py2Neo provides a convenient way to create and manipulate graphs in Neo4j, making it a popular choice for developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nKsi01HZiNQ3D8cCZ3IpQ.jpeg" /><figcaption>The result viewed within Neo4j browser</figcaption></figure><p><em>Side Note</em>: Deleting all nodes and relationships can be achieved using the following command…</p><pre>MATCH (x) DETACH DELETE x;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVlJh0vIW6zzODAVU9-4Pg.png" /></figure><h4>2. Using Neo4j Python Driver</h4><p>Install the neo4j driver:</p><pre>!pip install neo4j</pre><p>Connect to neo4j Graph database …</p><pre>from neo4j import GraphDatabase<br> ​<br> URI = &quot;neo4j+s://c8xxxxxx.databases.neo4j.io:7687&quot;<br> AUTH = (&quot;neo4j&quot;, &quot;pA5sw0rD&quot;)<br> ​<br> with GraphDatabase.driver(URI, auth=AUTH) as driver:<br>     driver.verify_connectivity()</pre><p>Connect to and execute commands via Python …</p><pre>records, summary, keys = driver.execute_query(<br>     &quot;MATCH (p:Person)-[r]-&gt;(m:Movie) RETURN p.name,m.title&quot;,<br>     movie=&quot;The Matrix&quot;,<br>     database_=&quot;neo4j&quot;<br> )<br> ​<br> # Loop through results and do something<br> for record in records:<br>     print(record)<br>     <br> print(&quot;The query `{query}` returned {records_count} records in {time} ms.&quot;.format(<br>     query=summary.query, records_count=len(records),<br>     time=summary.result_available_after,<br> ))</pre><pre><em>/var/folders/y0/8tbjscewdj6f9df7p68d7r3ddh0000gn/T/ipykernel_60751/34892138293.py:1: DeprecationWarning: Using a driver after it has been closed is deprecated. Future versions of the driver will raise an error.<br>   records, summary, keys = driver.execute_query(<br>&lt;Record p.name=&#39;John Doe&#39; m.title=&#39;The Matrix&#39;&gt;<br>The query `MATCH (p:Person)-[r]-&gt;(m:Movie) RETURN p.name,m.title` returned 1 records in 12 ms.</em></pre><p>Always close the driver after use.</p><pre>driver.close()</pre><h4>3. Using the Neo4j REST API</h4><p>Neo4j also provides a REST API that allows users to interact with the graph database using HTTP requests. Python can be used to make these requests and create graphs in Neo4j. Here is an example of how to create a graph using the Neo4j REST API:</p><pre>import requests<br> ​<br> # Create a request to create a node representing a person<br> person_request = requests.post(&quot;http://localhost/db/data/node&quot;,<br>                              json={&quot;labels&quot;: [&quot;Person&quot;], &quot;properties&quot;: {&quot;name&quot;: &quot;John Doe&quot;}})<br> ​<br> # Create a request to create a node representing a movie<br> movie_request = requests.post(&quot;http://localhost/db/data/node&quot;,<br>                              json={&quot;labels&quot;: [&quot;Movie&quot;], &quot;properties&quot;: {&quot;title&quot;: &quot;The Matrix&quot;}})<br> ​<br> # Create a request to create a relationship between the person and the movie<br> relationship_request = requests.post(&quot;http://localhost/db/data/relationship&quot;,<br>                                   json={&quot;start_node&quot;: person_request.json()[&quot;id&quot;],<br>                                         &quot;end_node&quot;: movie_request.json()[&quot;id&quot;],<br>                                         &quot;type&quot;: &quot;LOVES&quot;})</pre><p>This code creates the same graph, as with the examples above, with two nodes and a relationship between them, and using HTTP requests made to the Neo4j REST API. The Neo4j REST API provides a flexible way to interact with the graph database, allowing users to use different programming languages and tools.</p><p>However, Note that HTTP API is currently not available on Neo4j Aura. This can be used for a Neo4j instance running locally.</p><h4>4. Using Graph Data Science Server</h4><p>The advantages of <em>Neo4j Aura Datascience </em>Instance on Neo4j Aura include, to name a few…</p><ul><li>Easy Setup: The Aura Datascience Instance comes pre-configured with a range of tools and libraries for data science and machine learning, including Python, R, and Jupyter Notebooks, making it easy for data scientists to get started.</li><li>Can be easily scaled up or down as needed.</li><li>Includes integrated visualization tools. (Graph Visualization, Network Analysis, etc.)</li><li>Access to algorithms and machine learning support (includes support for machine learning libraries such as scikit-learn and TensorFlow)</li></ul><p><em>Here are the steps to install and use graphdatascience package:</em></p><pre>!pip install graphdatascience</pre><p>You should see …</p><pre><em>Collecting graphdatascience<br>   Downloading graphdatascience-1.9-py3-none-any.whl.metadata (7.7 kB)<br>   ...<br>   ...<br> Successfully installed graphdatascience-1.9 multimethod-1.10 textdistance-4.6.1</em></pre><p>Next, connect to Graph Datascience Server</p><pre>from graphdatascience import GraphDataScience<br> ​<br> host=&#39;neo4j+s://c8xxxxxx.databases.neo4j.io:7687&#39;<br> user=&#39;neo4j&#39;<br> password=&#39;pA5sw0rD&#39;<br> ​<br> gds = GraphDataScience(host, auth=(user, password))</pre><p>In this example, we will do a bulk load using a csv file available on GitHub:</p><pre>query = &quot;&quot;&quot;<br> LOAD CSV WITH HEADERS FROM $url AS row<br> MERGE (p:Person {name:row.name})<br> MERGE (m:Movie {title:row.title})<br> MERGE (p)-[i:row.edge]-&gt;(m)<br> &quot;&quot;&quot;<br> params = {&#39;url&#39;: &#39;https://raw.githubusercontent.com/xxxx&#39;}<br> gds.run_cypher(query, params)</pre><p>The hosted csv on GitHub is as formatted as below.</p><pre>name, title, edge<br> &quot;John Doe&quot;, &quot;The Matrix&quot;, &quot;Loves&quot;</pre><blockquote><strong><em>!! Caution : </em></strong><em>When using Neo4j Aura DS Instance:<br>The costs per hour running a Neo4j Aura DS instance can be very high, so one must take care to monitor costs incurred using the billings tab. Billing is based on GB hours provisioned, irrespective to whether these instances being used, or idle.</em></blockquote><h3>In Conclusion:</h3><p>The above are different ways to create graphs in Neo4j using Python. Some potential use cases for creating graphs in Neo4j, such as recommendation systems, fraud detection, social networks, and knowledge graphs. Neo4j can be a powerful tool for solving complex problems and uncovering insights in data.</p><h3>Credits</h3><ol><li>Python Manual on the Neo4j site : <a href="https://neo4j.com/docs/python-manual/current/">https://neo4j.com/docs/python-manual/current/</a></li><li>Analytics Vidhya : <a href="https://www.analyticsvidhya.com/blog/2023/02/understanding-neo4j-comprehensive-guide-for-data-enthusiasts/">https://www.analyticsvidhya.com/blog/2023/02/understanding-neo4j-comprehensive-guide-for-data-enthusiasts/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd59662cbad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Compression to optimize LLM costs]]></title>
            <link>https://medium.com/@herambh/prompt-compression-to-optimize-llm-costs-e4bf81733030?source=rss-23cde6b9cfd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4bf81733030</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Herambh Athavale]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 22:55:50 GMT</pubDate>
            <atom:updated>2024-01-08T02:57:04.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Prompt compression can be a useful and effective tool enabling the better use of Language Models (LMs), such as GPT-3. LLMs are incredibly powerful tools that can generate human-like text based on given prompts. However, their usefulness can be hindered by constraints on the length and format of the prompts they can handle. Prompt compression helps overcome these constraints, making LLMs more efficient by keeping costs lower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IQAzb4FjLn3RLwKcTmsy7A.jpeg" /><figcaption>Prompt compression saves costs</figcaption></figure><p>Here are some reasons why prompt compression is important for effective use of LLMs:</p><ol><li><em>Increased efficiency and Enhanced Context:</em> LLMs have limits on the maximum token length they can process due to computational constraints. By compressing prompts, we can fit more information within these token limits, maximizing the efficiency of the LLM’s computational resources, including increasing the effective length of the prompts that can be submitted. This can enhance the contextual information within the limited token space, resulting in more accurate and relevant responses from the LLM.</li><li><em>Reduced noise:</em> Long prompts may contain unnecessary or irrelevant information that can distract the LLM from generating the desired response. By compressing prompts, we can remove redundant details, noise, or unrelated parts, increasing the signal-to-noise ratio and enabling the LLM to focus on the core information.</li></ol><p>To illustrate the difference before and after prompt compression, consider the example below:</p><p><em>Before compression:</em></p><blockquote>“I am writing an article about the benefits of exercise for cardiovascular health. Could you please provide me with some statistics, research studies, and expert quotes on this topic that I can include in my article?”</blockquote><p><em>After compression:</em></p><blockquote>“Stats, studies, quotes on exercise for cardiovascular health?”</blockquote><p>Before compression : <em>27 tokens<br></em>After compression : <em>9 tokens<br>… a 67% reduction in the number of tokens provided. Note that both prompts will deliver the same or similar response from LLMs.</em></p><p>The compressed prompt conveys a more concise and compressed form that can make the prompt becomes more efficient, providing the LLM with the necessary context to generate a comprehensive response within assigned token limits.</p><h3>Approaches to Prompt Compression</h3><h4>Summarization and Creativity</h4><p>Prompt compression encourages users to distill their queries or prompts into shorter, more precise forms. Creative thinking can lead users to express their ideas or questions in innovative ways.</p><h4>Script based approaches</h4><p>Using scripts to reduce unnecessary words, text can be useful. One such approach I found to be interesting was gptrim.</p><p>See: <a href="https://pypi.org/project/gptrim/">https://pypi.org/project/gptrim/</a></p><pre>from gptrim import trim<br> ​<br> text = &quot;What are the ideas and feelings being expressed in the following text? Wanted to save some to bring to my Chicago family but my North Carolina family ate all 4 boxes before I could pack. These are excellent..could serve to anyone.This sauce is hot, tasty and spicy! Much hotter than other Datil pepper sauces, and full of smokey flavor, like a bar-b-que sauce with a kick! I love it!.My kids love these Earnest Eats snacks. I like that they are more nutritional and healthier that traditional snack bars in the grocery store. I also admire the use non-oil alternative products such as almond butter and non-processed sugar such as dried fruit for sweetness. I have already ordered these bars 3 times and will continue!&quot;<br> ​<br> trimmed_text = trim(text)<br> print(trimmed_text)</pre><p>The above text is derived from a publicly available food review corpus.</p><p>The following response is observed:</p><pre>ideasfeelingsexpressedfollowingtext?WantedsavebringChicagofamilyNorthCarolinafamilyate4boxescouldpack.excellent..couldserveanyone.Thissaucehot,tastyspicy!MuchhotterDatilpeppersauces,fullsmokeyflavor,likebar-b-quesaucekick!love!.MykidsloveEarnestEatssnacks.likenutritionalhealthiertraditionalsnackbarsgrocerystore.alsoadmireusenon-oilalternativeproductsalmondbutternon-processedsugardriedfruitsweetness.alreadyorderedbars3timescontinue!</pre><p>This is unreadable by humans, but understood by LLMs. Some of the optimizations include removal of …</p><ul><li>Spaces between words</li><li>Stop words ‘a’, ‘an’ , ‘the’, ‘and’, ‘of’ to name a few.</li><li>Removing punctuation in most cases does not impact content or context.</li></ul><p>Other aspects …</p><ul><li>Reducing words to their stems, like “running” becomes “run”.</li><li>Converting words to their base forms such as “better” becoming “good”.</li></ul><p>Note that any approach used for prompt compression has a tendency to add ambiguity. However, in most cases, LLMs are able to compensate for the same owing to their construction and training.</p><h4>LongLLMLingua</h4><p>LongLLMLingua recently, is the most talked about approach for prompt compression. It boasts of dramatic improvements by using a lower level model such as Llama, or GPT2, or using a different pre-trained model to ‘minimize’ prompts before calling the higher language model like GPT3.</p><p>The barebones approach can be viewed here on <a href="https://colab.research.google.com/drive/1qn2iKpyHPSSt9NJ7rjf_oLh4k0bzfN9j?usp=sharing">Google Collab</a> that looks up pages on Wikipedia for an article on the Mexican American War using <em>llama_index</em> using a Wikipedia Reader. cohere, llama_index, openai, llmlingua, accelerate are packages that need to be installed before this script can be run. The runtime needs to be restarted after accelerate is installed. The proposed sequence is as below. A standard runtime leveraging Python 3 can be used.</p><pre>!pip install cohere<br> !pip install llama_index<br> !pip install openai<br> !pip install llmlingua<br> !pip install accelerate</pre><p>Note the results of the exercise…</p><pre>original_contexts = &quot;\n\n&quot;.join([n.get_content() for n in retrieved_nodes])<br> compressed_contexts = &quot;\n\n&quot;.join([n.get_content() for n in new_retrieved_nodes])<br> original_tokens = node_postprocessor._llm_lingua.get_token_length(original_contexts)<br> compressed_tokens = node_postprocessor._llm_lingua.get_token_length(compressed_contexts)<br> print(compressed_contexts)<br> print()<br> print(&quot;Original Tokens:&quot;, original_tokens)<br> print(&quot;Compressed Tokens:&quot;, compressed_tokens)<br> print(&quot;Compressed Ratio:&quot;, f&quot;{original_tokens/(compressed_tokens + 1e-5):.2f}x&quot;)</pre><p>Result response is as below indicating a <strong>6.9 times compression</strong> of the original text (or, in other words, an <strong>87% reduction</strong> of the original prompt length.)</p><pre>Has the Mexican, how Are beaten you know of any bes Hadley [assachusetts], me of, I would be glad of escape,ed [our teacher Missary Lyoner ofoke College]ish us allgers and order us fight for our lives ... month before the of the, Pol was critic a United States Housement billising for &quot;a wararily and un begun by President of the.&quot;, whichman Abraham played an important role with his Sp Resolutions, followedal of thesings, including to Presidentk. party with alligs supportingment. Lincolns won lukearm support fellow Whigs Illinois counter attacked by who r pro-war Illinoiss Spotutions state Illinois by his his.While Ralphdoerson rejected waras means of achieving toward of the war he: &quot;The United will conquer, man swows, which brings him down. Mexico will poison us.&quot; He later accepted that the are about bycred means War historian James M an of Pul winning War history to theAmerican, &quot;Mison Us Mcersonues that the Mexican and was a key territorial event leadup to the Civil WarVeterans of the were. &quot; sick ands campaigns their way from to the States conditioned. Husands,, in health some with missingbs88Republic Text by theessional Committee describes theFruption and &quot; and high-k inement of the slave oligarchy.&quot;<br> Following the signing of the 1848 treaty, Polk sought to send troops to Yucatan, where there was a civil war between secessionists and those supporting the Mexican government. The U.S. Congress refused his request. The Mexican War was supposed to be short and nearly bloodless. It was neither. Congress did not support more foreign conflict.<br> ​<br> Original Tokens: 2568<br> Compressed Tokens: 371<br> Compressed Ratio: 6.92x</pre><h4>Conclusion</h4><p>Prompt compression is going to play a vital role in making LLMs more effective, as it increases efficiency, enhances context, and reduces noise of the underlying prompts. On the overall, this trend is neither new or unique within software. One must take notice that <a href="https://en.wikipedia.org/wiki/Minification_(programming)"><em>Minification</em></a> has been around for some time now, and that this goes a long way improving website performance. Also, the objective of minification is not to obfuscate, through it can have that outcome sometimes. Likewise, in the case of prompt compression. Prompt compression is undergoing some evolution today, and could likely become a standard feature for LLMs in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4bf81733030" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Semantic Search at Large Enterprises]]></title>
            <link>https://medium.com/@herambh/leveraging-semantic-search-at-large-enterprises-cbfea0116ccf?source=rss-23cde6b9cfd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbfea0116ccf</guid>
            <category><![CDATA[semantic-search]]></category>
            <dc:creator><![CDATA[Herambh Athavale]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 02:48:30 GMT</pubDate>
            <atom:updated>2024-01-02T03:00:27.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Enterprises look for help framed within the context of their own business. While AI and Large Language Models have helped reach out to large audiences worldwide, their applicability within the specific confines of a domain or business has been limited. However, Semantic Search is fast becoming a way by which these technologies can be utilized. The below article illustrates one such approach.</p><h3><strong>The Beginnings of GPT-3 and ChatGPT:</strong></h3><p>ChatGPT, also known as GPT-3, advanced AI language model developed by OpenAI, since its launch in mid-2020, has revolutionized the world of natural language processing and communication. It started when OpenAI made a limited access beta version of GPT-3 available to developers for testing. This led to a surge in interest and excitement among the tech community. As more and more use cases and demos of the model were shared, the hype around it has continued to grow. Major tech companies such as Microsoft and Salesforce soon collaborated with OpenAI to utilize GPT-3 in their products, and many others are rolling out, or planning to rollout their own integrations. Facebook, Google, X, and others, have their versions of LLMs jockeying for the same domain/ space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*Dl09NZ93luJRNyJNb_2HOA.png" /></figure><h3><strong>Limitations of LLMs in addressing Enterprise use cases and concerns:</strong></h3><p>In the many months since their launch, enterprises may have caught up with the level of technical understanding and complexity that is associated with these AI models, some concerns and challenges continue to be predominant. Most notably:</p><ol><li><em>Data Privacy and Security</em> are major concerns when using 3rd party AI solutions. Prompt Engineering has frequent new reveals on how LLMs can be coaxed into revealing details from within its training that it should normally not sharing with end users. LLMs may also store and remember data from previous interactions, that could lead to data breaches of confidential or secret information.</li><li><em>Ethical Considerations and Bias</em> need to be addressed when using 3rd party LLMs, as there may be inherent biases in any machine learning model. Enterprises need to be wary of perpetuating and amplifying these biases, which could result in sub-optimal outcomes for end-users.</li><li><em>Quality Control and Error Mitigation</em> is an active focus area for LLMs. In spite of their sophistication, LLMs still tend to <em>‘hallucinate’</em> or make up facts that look real, but may not be.</li><li><em>Cost and Scalability</em> is probably one of the most significant factors in the use of LLMs. In the enterprise scenario, feeding the specific context to the LLM to get a suitable response can get very expensive. LLMs charge by the number of tokens consumed. Stateless transactions with an LLM can result in huge overheads when context information has to be first shared to get responses related to that context.</li><li><em>Lack of Intuitive or ‘Human Like’ Reasoning </em>is an inhibiting factor as well. More recent versions of LLMs also not expected to demonstrate a genuine understanding of cause and effect. This limitation can become apparent in tasks that require a genuine understanding of cause and effect, or logical deduction.</li></ol><h3>Strategies to leverage LLMs on Enterprise Scale</h3><p><em>Embeddings</em> is one way enterprises can scale in order to leverage LLMs and sophisticated AI technology, while addressing some of the above key concerns. Embeddings are numerical representations of text, images, or other data types where similar items are represented by points close to each other in a vector space. In the context of enterprises, embedding-based strategies can enhance various business applications, from semantic search to personalization. Here’s how an enterprise might leverage embeddings:</p><ol><li><em>Customer Support Automation</em> <em>(see below quote — “How this works”) </em>can leverage embeddings by looking up existing knowledge base articles against customer asks and display the related relevant information based on the similarity index.</li><li><em>Semantic Search</em>: Embed both search queries and documents in the same vector space to retrieve documents that have similar meanings to the query, even if they don’t contain the exact keywords.</li><li><em>Fraud Detection:</em> Train embeddings to identify patterns of normal user behavior, and apply anomaly detection to spot outlier embeddings that could indicate fraudulent activities.</li><li><em>Content Recommendation:</em> Apply embeddings to understand user preferences and content features deeply, allowing for more nuanced recommendations that go beyond collaborative filtering.</li></ol><blockquote><strong>How this works</strong> : Customer Support knowledge articles for instance are vectorized into embeddings and stored. Incoming questions, also vectorized can be compared against a database of such embeddings. This is far more relevant than a keyword search used today, to match words or phrases against articles in the database or search index, owing to the nature of the high order representation of vector space. For example, the <em>`text-embedding-ada-002`</em> embeddings offers a 1536 dimension vector. Higher order vector spaces can capture and store more information, given adequate and proper training.</blockquote><h3>Using Embeddings to enable a Customer Support Solution</h3><p>Using embeddings has several advantages, such as, scalability, security and privacy, evaluation and iteration. In the below exercise, I evaluated a publicly available fine food reviews dataset with the objective of uncovering key aspects of customer feedback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezzun3KaF87-oO_JkXPaGw.png" /></figure><p>Initially reducing the dataset for iterative script development, and to limit costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeRr81ILllkCqp9byo8sog.png" /></figure><p>Using Embeddings model `<em>text-embedding-ada-002`</em> to vectorize customer reviews in the Text column as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDUgEkRvNp1hkPUx210AOA.png" /></figure><p>Search embeddings as provided in the OpenAI cookbook that doesn’t work after the latest upgrade, and switching to a workaround published on openAI site:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTsi7NK-karOJcCyzeztEQ.png" /><figcaption>Note: openai.emebeddings_utils has been removed from latest versions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ru6yP5hWpig_bTh7wrEbMA.png" /><figcaption>Workaround to help execute same functionality</figcaption></figure><p>Finally, running the comparator to look for specific reviews…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-E8LdwUSbqqz-ZATENjLA.png" /></figure><p>A more detailed look at what reviews were returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znaO3iFT1PwBQQo1QnLI5A.png" /></figure><p>We finally have the top 3 reviews that match our search for spicy treats that will be loved by the family. Next, we want to comprehend what the reviews are saying by feeding the result to text completions api.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypMBNfjbrMFGFYUgHy9bqg.png" /><figcaption>Limiting the size of each review being fed into Chat Completions so as to limit costs</figcaption></figure><p>Responses from across the different Chat Completions model results in different levels of analysis of the same text. The below compares results from <em>gpt-3.5-turbo-16k</em> vs <em>gpt-1106-preview </em>Models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh9rcEKusENFNOZdInL3-w.png" /><figcaption>Output from Chat Completions model `<em>gpt-3.5-turbo-16k`</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FDxX2WZk8DqnlaMykY8jQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gko-xNd7se21GbyMbPGuLw.png" /><figcaption>Output from Chat Completions model `<em>gpt-1106-preview`</em></figcaption></figure><h3>Conclusion</h3><p>Using some LLM models such as Chat Completions API within OpenAI can be expensive and not scalable. It is possible to vectorize a much larger corpus of documents or records using Embeddings API and then use techniques such as Cosine Similarity to select only those records similar to what you are searching for. These can then be fed to Chat Completions API for interpretation purposes. This represents a significant optimization of resources when leveraging LLMs.</p><h3>Next Steps</h3><p>In a customer service scenario, Semantic Search can be used to pre-select corpus or records matching certain intents to pre-train a chatbot in a very economical way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbfea0116ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>