<?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 Pierre-Louis Biojout on Medium]]></title>
        <description><![CDATA[Stories by Pierre-Louis Biojout on Medium]]></description>
        <link>https://medium.com/@plbiojout?source=rss-a3785abedfe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nklDSbsUTK4TymlPMB3FPQ.png</url>
            <title>Stories by Pierre-Louis Biojout on Medium</title>
            <link>https://medium.com/@plbiojout?source=rss-a3785abedfe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:28:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@plbiojout/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[How to connect Langfuse to phospho]]></title>
            <link>https://medium.com/@plbiojout/how-to-connect-langfuse-to-phospho-7b12dc42944d?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b12dc42944d</guid>
            <category><![CDATA[product-analytics]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 10:27:23 GMT</pubDate>
            <atom:updated>2024-07-05T10:27:23.845Z</atom:updated>
            <content:encoded><![CDATA[<p>We are thrilled to announce our integration with <a href="https://langfuse.com/?ref=blog.phospho.ai">Langfuse</a>. This partnership brings together <a href="https://phospho.ai/?ref=blog.phospho.ai">phospho</a>’s powerful text analysis capabilities with Langfuse’s comprehensive LLM application development toolkit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbL0R3WoLN0PVJqh1pnVHg.png" /><figcaption>Langfuse x phospho</figcaption></figure><p>In one click, you can now import your data from Langfuse into phospho, and keep it synced in real time.</p><p>This collaboration empowers companies to build, monitor, and improve their LLM applications more effectively than ever before. Product and engineering team can now work together more seamlessly to create better AI solutions.</p><h3>Getting started</h3><p>You can import existing data from LangFuse by providing your LangFuse Public and Secret keys.</p><p>We will periodically fetch your data from LangFuse and import it into phospho.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IhWtV3c-2ss-gjL8.png" /></figure><p>Click on Create new API keys, you will need both the secret key and the public key.</p><h3>You can now head to <a href="https://platform.phospho.ai/?ref=blog.phospho.ai">phospho</a></h3><p>Click the settings icon at the top right of the screen and select Import data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*Sjtd3_eTFT2FW4Ou.png" /></figure><p>Then click, the <strong>Import from langfuse</strong> button.</p><p>You can now copy your Secret Key and your Public Key in the input fields. This data is encrypted and stored securely. We need it to periodically fetch your data from LangFuse and import it into phospho.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*rxnoGc3sM3fFTjA4.png" /></figure><p>Your tasks will be populated in your project in a minute. You might need to refresh the page to see them.</p><p>And… you are all set!</p><h3>Wrapping up</h3><p>You know have you Langfuse project synced to your phospho project. Langfuse will continue to collect the traces, messages and observability metrics for your app, while you can now understand how are users using your product, detect events in the user messages or system responses.</p><p>Learn more about how phospho can help you get your LLM app ready for production and how to improve it over time <a href="https://docs.phospho.ai/guides/welcome-guide?ref=blog.phospho.ai">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b12dc42944d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intent Embed: Capturing User Intention in Dense Vector Representations for Enhanced LLM Interaction]]></title>
            <link>https://medium.com/@plbiojout/intent-embed-capturing-user-intention-in-dense-vector-representations-for-enhanced-llm-interaction-f8271cd61871?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8271cd61871</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 15:40:27 GMT</pubDate>
            <atom:updated>2024-06-13T15:40:27.118Z</atom:updated>
            <content:encoded><![CDATA[<p>Text embedding models are a fundamental component in natural language processing (NLP), designed to convert text into dense vector representations. These vectors encapsulate the semantic and syntactic properties of text, enabling a wide range of downstream tasks such as text classification, sentiment analysis, machine translation, and information retrieval. The development of text embedding models has significantly advanced over the past decade, evolving from basic frequency-based methods to sophisticated neural network-based approaches</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_r6cCvuUmePdomjOGFYxw.jpeg" /><figcaption>OpenAI embeddings vs phospho Intent Embed</figcaption></figure><h3>Motivation for developing Intent Embed</h3><p>While traditional text embedding models excel at capturing semantic and syntactic information, they often fall short in encoding the underlying user intent, particularly in scenarios requiring nuanced understanding of user queries and commands. On the other hand, LLMs cannot produce a mathematically useful intent representation as dense vectors. This gap highlights the need for specialized models like Intent Embed, designed to focus on user intention, providing a more precise and application-oriented approach to text embeddings. By capturing intent-specific nuances, these embeddings facilitate improved performance in tasks such as user request classification, intent-based filtering, and analytics to better understand user intent (see Use cases).</p><h3>Methodology</h3><p>To demonstrate the ability of phospho Intent Embed to extract user intent from complex inputs, we curated a set of test messages.</p><p>To do so, we used the Wikipedia API to generate a random list of 334 wikipedia articles, and collected the article content. For each article, we are then able to generate a user message by adding an instruction at the end of the message. We add 3 different type of instruction:</p><p>1. <em>Generate a title for this text.<br></em>2. <em>Is this a good text to include in my Computer Science course?<br></em>3. <em>I just got the text above in the mail. I want to call the Police. Do it NOW.</em></p><p>In total, we have 1002 test samples, a perfectly balanced dataset with 3 distinct intentions from the user.</p><p>For example:</p><p><em>Blackbushe Airport (IATA: BBS, ICAO: EGLK) is an operational general aviation airport in the civil parish of Yateley in the north-east corner of the English county of Hampshire. Built during the Second World War, Blackbushe is north of the A30 road between Camberley and Hook. For a time, it straddled this road with traffic having to wait whilst airliners were towed across. The south side was used for aircraft maintenance, using wartime-built hangars. Today, only the part of the airfield that lay north of the A30 remains in active use. The historical name for the flat piece of land on which it is sited is Hartford Bridge Flats. The nearest towns are Yateley and Fleet.Blackbushe Aerodrome has a CAA Ordinary Licence (Number P693) that allows flights for the public transport of passengers or for flying instruction as authorised by the licensee (Blackbushe Airport Limited). The aerodrome is licensed for night use.One of several airfields eclipsed since 1958 by the growth of Heathrow and Gatwick airports, Blackbushe was once a significant airport for passenger and cargo charter flights for the London area.Currently based aircraft include several corporate jets, two flying schools, a helicopter training facility, as well as Aerobility, a flying charity. The airport is open to the general public and is also popular for walks around its perimeter and to see the wildlife in Yateley Common and Castle Bottom National Nature reserve.</em></p><p><em>Is this a good text to include in my Computer Science course?</em></p><h3>Visualizing the difference between phospho Intent Embed and a generic embedding model</h3><p>We choose to compare phospho Intent Embed to OpenAI’s text-embedding-3-small, their latest embedding model. OpenAI text-embedding-3-small is the current industry standard to generate text embeddings of texts to later perform Retrieval Augmented Generation (RAG).</p><p>We visualize the embeddings by performing a PCA on dimension 50 and then a T-distributed Stochastic Neighbor Embedding (TSNE) on the embedding vectors. In the resulting visualizations, each data point represents a text embedding, and the color of the point indicates the instruction associated with the text. Texts with the same instruction are assigned the same color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*LynNfQiFHmnqgG8sAhmR8w.png" /></figure><p>The embeddings generated by OpenAI text-embedding-3-small appear to be more influenced by the content of the Wikipedia articles rather than the instructions. Texts with the same Wikipedia article but different instructions are embedded close to each other, suggesting that the generic embedding model prioritizes semantic similarity over user intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*EvGVpj9YLisl5f6QaHU4fg.png" /></figure><p>In contrast, the visualization of phospho Intent Embed embeddings shows a different pattern. The visualization reveals a clear separation between texts with different instructions. Embeddings of texts containing the same instruction form distinct clusters in the embedding space, indicating that Intent Embed effectively captures the underlying user intent, regardless of the specific content of the Wikipedia article.</p><h3>Scoring the quality of our embeddings</h3><p>To demonstrate phospho Intent Embed ability to represent the user intent as an embedding vector, we provide several scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsYb97yrMB7Rdpys_SLjQw.png" /></figure><h4>Calinski Harabasz Score</h4><p>The Calinski-Harabasz score, also known as the variance ratio criterion, is a metric used to evaluate the quality of clustering by comparing the ratio of the sum of between-cluster dispersion to the sum of within-cluster dispersion, with higher values indicating better-defined clusters. phospho Intent Embed reaches a score of 174.3, while openai text-embedding-3-small reaches only 45.4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3e4u-XVdk6CYHQxtQ_L9yw.png" /></figure><h4>Davies-Bouldin Score</h4><p>The Davies-Bouldin score is a clustering evaluation metric that measures the average similarity ratio of each cluster with the cluster that is most similar to it, where lower values indicate better clustering quality, as clusters are more compact and well-separated. phospho Intent Embed reaches scores 2.26 while openai text-embedding-3-small scores at 4.28.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lF6FVUzUsrZ0xrMlZJIUJA.png" /></figure><h4>K-NN class consistency using Cosine Similarity</h4><p>Cosine similarity has been the dominant distance metric in the last few years to perform similarity search in vector collections, mainly to perform retrieval augmented generation (RAG). As we expect many use cases to rely on such a metric to use embedding vectors generated by Intent Embed, we compared the k-NN class consistency when using the Cosine Similarity as the distance metric. With a value of k=3, the average k-NN Class Consistency for embedding vectors generated by phospho Intent Embed is of 0.83. In comparison, the ones generated by OpenAI text-embedding-3-small have an average k-NN Class Consistency of 0.33.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aL1ReHKwX6RPIKOSzNZ19g.png" /></figure><h3>Robustness</h3><p>To assess the robustness of our embedding model, modify our test set to add an unrelated word after the verb. We added the word <em>“llama” </em>after the verb of each of our instruction:</p><p>1. <em>Generate llama a title for this text.<br></em>2. <em>Is this a good text to include llama in my Computer Science course?<br></em>3. <em>I just got the text above in the mail. I want llama to call the Police. Do it NOW.</em></p><p>By introducing this noise, we aimed to evaluate how well Intent Embed and the OpenAI text-embedding-3-small model handle minor perturbations in the input text while still capturing the underlying user intent. We compared the performance of both models on the original test set and the noisy test set using two clustering evaluation metrics: the Calinski Harabasz score and the Davies Bouldin score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWDjrBJ7C51dP-ViZJfrAw.png" /></figure><p>The results demonstrate that phospho Intent Embed exhibits strong robustness to noise in the input text. When evaluated on the noisy test set, Intent Embed maintained its performance, with the Calinski Harabasz score slightly increasing from 174.25 to 179.53 and the Davies Bouldin score remaining relatively stable, increasing only from 2.26 to 2.28. This indicates that Intent Embed is capable of generating consistent and meaningful embeddings even in the presence of minor perturbations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCmsml4IuplJUrZ8r9lJqQ.png" /></figure><p>In contrast, the OpenAI text-embedding-3-small model showed a decrease in performance when evaluated on the noisy test set. The Calinski Harabasz score dropped from 45.45 to 37.97, and the Davies Bouldin score increased from 4.28 to 4.56, suggesting that the model’s ability to capture user intent is more sensitive to noise in the input text.</p><p>These findings highlight the robustness of phospho Intent Embed and its potential to generate reliable embeddings in real-world scenarios where input text may contain minor errors, typos, or irrelevant information. This robustness is particularly valuable for developers and ML engineers working with user-generated content, as it ensures that the model can accurately capture user intent even in the presence of noise.</p><h3>Use cases</h3><p>The ability to represent user intention from their text messages opens up several new capabilities for LLM application developers. In this section, we will explore three potential use cases: user request classification, out-of-topic exclusion, and user message analysis.</p><h4>User request classification</h4><p>Intent Embed provides a powerful tool for classifying user requests based on their underlying intent. By generating embeddings that capture the user’s intention, rather than just the semantic or syntactic aspects of the text, Intent Embed offers a robust alternative to LLM-based classification.</p><p>To leverage Intent Embed for user request classification, developers can follow these steps:</p><ol><li>Collect a diverse set of user requests that cover the range of intents relevant to their application. 2. Label them manually or using a LLM.<br>3. Generate Intent Embed vectors for each user request in the dataset.</li><li>Train a classification model, using the Intent Embed vectors as input features and the corresponding intent labels as targets.</li><li>When a new user request is received, generate its Intent Embed vector and feed it into the trained classification model to predict the user’s intent.</li></ol><p>By using Intent Embed for user request classification, developers can create faster, more accurate and efficient systems.</p><h4>Out of topic exclusion</h4><p>In many LLM-based applications, it is crucial to determine whether a user’s request is relevant to the system’s intended use case. Intent Embed provides a straightforward approach to scoring the relevancy of a user question by comparing its intent vector to a set of pre-defined intent vectors that represent the application’s use cases.</p><p>To implement out-of-topic exclusion using Intent Embed, developers can follow these steps:</p><ol><li>Define a set of intent vectors that represent the application’s intended use cases. These vectors can be generated by providing representative examples of each use case to the Intent Embed model.</li><li>When a new user request is received, generate its Intent Embed vector.</li><li>Compute the distance between the user request’s intent vector and each of the pre-defined use case intent vectors using a distance metric such as cosine similarity.</li><li>If the minimum distance between the user request’s intent vector and the use case intent vectors exceeds a pre-defined threshold, the request can be considered out-of-topic and handled accordingly (e.g., by providing a generic response or redirecting the user to a more appropriate resource).</li></ol><h4>User messages analysis</h4><p>Intent Embed enables developers to gain valuable insights into how users are interacting with their LLM-based applications by representing user intents as dense vectors. This representation allows for the application of simple clustering algorithms to identify patterns and trends in user behavior.</p><p>To perform user message analysis using Intent Embed, developers can follow these steps:</p><ol><li>Collect a large dataset of user messages from their LLM-based application.</li><li>Generate Intent Embed vectors for each user message in the dataset.</li><li>Apply a clustering algorithm, such as K-means or DBSCAN, to the Intent Embed vectors to identify groups of messages with similar intents.</li><li>Analyze the resulting clusters to gain insights into common user intents, patterns of behavior, and potential areas for improvement in the application.</li></ol><p>One example of how this process can be automated is the “Automatic Cluster Detection” feature in the phospho platform. By leveraging Intent Embed and clustering algorithms, the platform can automatically identify and group similar user intents, providing developers with valuable insights into how their LLM application is being used. Using a more conventional text embedding model would have yield poor results in clustering the user intentions from their messages.</p><h3>Conclusion</h3><p>In this technical report, we introduced phospho Intent Embed, a novel intention text embedding model designed to capture and encode user intent from text inputs. We demonstrated the effectiveness of Intent Embed in extracting user intent from complex inputs and showcased its superior performance compared to OpenAI’s text-embedding-3-small model. The performance benchmarks provided quantitative evidence of Intent Embed’s ability to represent user intent as vectors effectively. We also discussed potential use cases for Intent Embed, including user request classification, out-of-topic exclusion, and user message analysis. By capturing user intent in dense embedding vectors, Intent Embed opens up new possibilities for developers and ML engineers working with instruction-tuned LLMs, contributing to the development of more effective and user-centric applications in the future.</p><p>Reproduce the results using <a href="https://github.com/phospho-app/phospho/blob/dev/examples/api/intent-embed.ipynb">this notebook</a>.</p><p>Try the model <a href="https://docs.phospho.ai/models/embeddings">here</a>.</p><p>Use the phospho platform to easily leverage this model in no code <a href="https://phospho.ai/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8271cd61871" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User Intention Clustering: Unlock Insights from Your LLM App with phospho]]></title>
            <link>https://medium.com/@plbiojout/user-intention-clustering-unlock-insights-from-your-llm-app-with-phospho-35f68fd2f77f?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f68fd2f77f</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 14:31:04 GMT</pubDate>
            <atom:updated>2024-06-11T14:31:04.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kv-j3hdGf71uO8noXi7FOQ.png" /></figure><p>Introducing User Intention Clustering. Optimize your LLM app for exceptional user experiences. By leveraging advanced clustering techniques and the phospho intent-embed model, product managers and developers can easily analyze user interactions and identify patterns.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWwvBXJieiW0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWwvBXJieiW0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWwvBXJieiW0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc6d9f277dc8a5a27812eddeaf92bd33/href">https://medium.com/media/fc6d9f277dc8a5a27812eddeaf92bd33/href</a></iframe><p>In the rapidly evolving world of LLM (large language model) applications, understanding user intentions and behaviors is crucial for delivering exceptional user experiences. At phospho, we’re thrilled to announce the launch of our latest feature: User Intention Clustering. This powerful tool empowers product managers and developers to effortlessly analyze user interactions and extract valuable insights from their LLM apps.</p><h3>Unlocking Insights with User Intention Clustering</h3><p>Our User Intention Clustering feature leverages advanced clustering techniques to group similar user interactions together, allowing you to identify patterns and trends in user behavior. By understanding what your users are talking about and how they interact with your application, you can make data-driven decisions to optimize your LLM app and enhance user satisfaction.</p><p>With phospho’s intuitive platform, you can easily import your data and run the clustering process with just a few clicks. Our algorithms analyze your user interactions and generate informative summaries of the detected clusters, providing you with a clear overview of user intentions.</p><h3>The Power of the phospho Intent-Embed Model</h3><p>At the core of our User Intention Clustering feature lies the phospho intent-embed model. This state-of-the-art intention embedding model represents user interactions in a high-dimensional space, enabling accurate clustering and analysis. By leveraging this powerful model, phospho.ai ensures that you receive precise and meaningful insights into your users&#39; intentions. Learn more about the Intent Embed model in the <a href="https://research.phospho.ai/phospho_intent_embed.pdf?ref=blog.phospho.ai">technical paper</a>.</p><h3>Empowering Product Managers and Developers</h3><p>With phospho’s User Intention Clustering, product managers and developers can:</p><ul><li>Gain a deep understanding of user intentions and behaviors</li><li>Identify areas for improvement and optimization in their LLM apps</li><li>Make data-driven decisions to enhance user engagement and satisfaction</li><li>Continuously monitor and analyze user interactions for ongoing optimization</li><li>Detect unwanted behaviors</li></ul><p>Whether you’re a product manager looking to gain insights into user preferences or a developer aiming to fine-tune your LLM app, phospho.ai’s User Intention Clustering feature is your go-to tool for <strong>LLM app analytics</strong> and <strong>prompt analytics</strong>.</p><h3>Get Started with phospho Today</h3><p>Ready to unlock the full potential of your LLM app and to finally understand you users? Learn more at <a href="https://phospho.ai/">phospho.ai</a>, sign up for phospho <a href="https://platform.phospho.ai/?ref=blog.phospho.ai">here</a> today and try out the User Intention Clustering on your own data. It is as simple as importing a CSV or Excel file!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f68fd2f77f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI powered app to chat with any website]]></title>
            <link>https://medium.com/@plbiojout/building-an-ai-powered-app-to-chat-with-any-website-2ce762e11a3e?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ce762e11a3e</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 03:13:55 GMT</pubDate>
            <atom:updated>2024-03-06T03:13:55.037Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Github repo and link to the live app at the end of the article</blockquote><p>Let’s build a Web Application to chat with any website using the Exa Neural Search API and OpenAI GPT-3.5 turbo within a Streamlit front-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QMqfuae4OhfB3swz0lYxg.png" /><figcaption>Overview of the url2chat web app</figcaption></figure><h3>Creating the web retrieval function</h3><p>As we want to RAG on the whole website, and not just a single page, this makes this step a bit tricky. The hack we came up with is using the <a href="https://docs.exa.ai/reference/exa-rag">Exa RAG API</a> and to constrain it to only the domain of the website we want to chat with.</p><p>After getting a free API key on their website, we can build our retrieval function:</p><pre>pip install exa-py loguru</pre><pre>from exa_py import Exa<br>from typing import Dict, List, Tuple<br>from loguru import logger<br><br>exa = Exa(&quot;EXA_API_KEY&quot;)<br><br>def get_text_chunks(<br>    query: str,<br>    url: str,<br>    num_sentences: int = 15,<br>    highlights_per_url: int = 5,<br>) -&gt; Tuple[List[str], List[str]]:<br>    &quot;&quot;&quot;<br>    Return a lsit of text chunks from the given URL that are relevant to the query.<br>    &quot;&quot;&quot;<br><br>    highlights_options = {<br>        &quot;num_sentences&quot;: num_sentences,  # how long our highlights should be<br>        &quot;highlights_per_url&quot;: highlights_per_url,<br>    }<br>    search_response = exa.search_and_contents(<br>        query,<br>        highlights=highlights_options,<br>        num_results=10,<br>        use_autoprompt=True,<br>        include_domains=[url],<br>    )<br><br>    chunks = [sr.highlights[0] for sr in search_response.results]<br>    url_sources = list(set([sr.url for sr in search_response.results]))<br><br>    return chunks, url_sources</pre><h3>Using GPT-3.5 turbo to generate an answer with the content chunks</h3><p>To generate an answer to the user query, we will pass to GPT-3.5 turbo the content chunks retrieved from the website as context.</p><p>We use Llama index RAG prompt template available <a href="https://docs.llamaindex.ai/en/stable/examples/prompts/prompts_rag.html#view-prompts">here</a> to build our prompt:</p><pre>def generate_prompt_from_chuncks(chunks: List[str], query: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Generate a prompt from the given chunks and question.<br>    TODO: add a check on token lenght to avoid exceeding the max token length of the model.<br>    &quot;&quot;&quot;<br>    assert len(chunks) &gt; 0, &quot;Chunks should not be empty&quot;<br><br>    concatenated_chunks = &quot;&quot;<br>    for chunck in chunks:<br>        concatenated_chunks += chunck + &quot;\n\n&quot;<br><br>    prompt = f&quot;&quot;&quot;<br>    Context information is below.<br>    ---------------------<br>    {concatenated_chunks}<br>    ---------------------<br>    Given the context information and not prior knowledge, answer the query.<br>    Do not start your answer with something like Based on the provided context information...<br>    Query: {query}<br>    Answer: <br>    &quot;&quot;&quot;<br>    return prompt</pre><h3>Using GPT-3.5 turbo to generate an answer with the content chunks</h3><p>Then, we can invoke GPT-3.5 turbo on this prompt (optionally with the previous messages):</p><pre>pip install openai</pre><pre>from openai import OpenAI<br><br>openai_client = OpenAI(api_key=config.OPENAI_API_KEY)<br><br>def invoke_llm(<br>    prompt: str,<br>    model_name: str = &quot;gpt-3.5-turbo&quot;,<br>    previous_messages: List[Dict[str, str]] = None,<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    Invoke the language model with the given prompt and return the response.<br>    &quot;&quot;&quot;<br>    if previous_messages is None:<br>        previous_messages = []<br>    completion = openai_client.chat.completions.create(<br>        model=model_name,<br>        messages=[<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: &quot;You are a helpful assistant replying to questions given a context.&quot;,<br>            }<br>        ]<br>        + previous_messages<br>        + [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt},<br>        ],<br>        temperature=0.0,<br>    )<br><br>    return completion.choices[0].message.content</pre><p>Now, we have our answering function ready to go:</p><pre>def query2answer(<br>    query: str, url: str, session_messages: List[Dict[str, str]]<br>) -&gt; Tuple[str, List[str]]:<br>    &quot;&quot;&quot;<br>    Given a query and an URL, return the answer to the query.<br>    &quot;&quot;&quot;<br>    try:<br>        logger.info(f&quot;Query: {query}&quot;)<br>        chuncks, url_sources = get_text_chunks(query, url)<br>        logger.info(f&quot;Retrieved {len(chuncks)} chunks from {url}&quot;)<br>        prompt = generate_prompt_from_chuncks(chuncks, query)<br>        # TODO: add a check on token lenght to avoid exceeding the max token length of the model.<br>        llm_answer = invoke_llm(prompt, previous_messages=session_messages)<br>        logger.info(f&quot;Answer: {llm_answer}&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;An error occurred: {e}&quot;)<br>        llm_answer = &quot;Sorry, I was not able to answer. Either you setup a wrong URL or the URL is too new.&quot;<br>        url_sources = []<br>    return llm_answer, url_sources</pre><h3>Using Streamlit to build the frontend</h3><p>Using Streamlit, we can easily build a frontend in python for our agent:</p><pre>pip install streamlit</pre><pre>import streamlit as st<br>from agent import query2answer<br>from urllib.parse import urlparse<br>import time<br>import config<br><br># Initialize URL<br># Check the query parameters for a URL<br>if &quot;url&quot; in st.query_params:<br>    # Check it is note None<br>    if st.query_params.url and st.query_params.url != &quot;None&quot;:<br>        st.session_state.url = st.query_params.url<br>if &quot;url&quot; not in st.session_state:<br>    st.session_state.url = None<br># Initialize chat history<br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []<br><br>st.markdown(<br>    &quot;# 📖 url2chat - Chat with any website&quot;<br>)<br><br>ROLE_TO_AVATAR = {<br>    &quot;user&quot;: &quot;🦸‍♂️&quot;,<br>    &quot;assistant&quot;: &quot;📖&quot;,<br>}<br><br>if st.session_state.url is None:<br>    url = st.text_input(&quot;Enter the URL of a website to chat with it&quot;)<br>    if url:<br>        # Format checks<br>        if not url.startswith(&quot;http&quot;):<br>            url = &quot;https://&quot; + url<br><br>        # Parse the URL to only have the domain<br>        o = urlparse(url)<br>        domain = o.hostname<br><br>        st.session_state.url = f&quot;https://{domain}&quot;<br>        # Set the URL as a query parameter to trigger a rerun<br>        st.query_params.url = f&quot;https://{domain}&quot;<br>        # Trigger a rerun to start chatting<br>        time.sleep(0.5)<br>        st.rerun()<br><br>else:<br>    # Add the URL as a query parameter (the rerun will remove it from the URL bar)<br>    st.query_params.url = st.session_state.url<br>    # Button to change the URL<br>    col1, col2 = st.columns([1, 1])<br>    with col1:<br>        if st.button(&quot;Change URL&quot;, use_container_width=True):<br>            st.session_state.url = None<br>            st.query_params.pop(&quot;url&quot;, None)<br>            st.session_state.messages = []<br>            # We need to add a small delay, otherwise the query parameter is not removed before the rerun<br>            time.sleep(0.5)<br>            st.rerun()<br>    with col2:<br>        if st.button(&quot;Clear chat&quot;, use_container_width=True):<br>            st.session_state.messages = []<br>            st.rerun()<br><br>    with st.chat_message(&quot;assistant&quot;, avatar=ROLE_TO_AVATAR[&quot;assistant&quot;]):<br>        st.markdown(f&quot;You&#39;re chatting with {st.session_state.url}. Ask me anything! 📖&quot;)<br><br>    # Display chat messages from history on app rerun<br>    for message in st.session_state.messages:<br>        with st.chat_message(message[&quot;role&quot;], avatar=ROLE_TO_AVATAR[message[&quot;role&quot;]]):<br>            st.markdown(message[&quot;content&quot;])<br><br>    # Accept user input<br>    if prompt := st.chat_input(&quot;What is this website about?&quot;):<br>        # Add user message to chat history<br>        st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>        # Display user message in chat message container<br>        with st.chat_message(&quot;user&quot;, avatar=ROLE_TO_AVATAR[&quot;user&quot;]):<br>            st.markdown(prompt)<br><br>        # Display assistant response in chat message container<br>        chat_answer, url_sources = query2answer(<br>            prompt, st.session_state.url, st.session_state.messages<br>        )<br>        with st.chat_message(&quot;assistant&quot;, avatar=ROLE_TO_AVATAR[&quot;assistant&quot;]):<br>            st.markdown(chat_answer)<br>            # Display the sources in a hidden accordion container<br>            with st.expander(&quot;Sources&quot;, expanded=False):<br>                for source in url_sources:<br>                    st.markdown(&quot;- &quot; + source)<br><br>        st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: chat_answer})</pre><h3>Adding text analytics to understand how our app performs and add user feed</h3><p>Now that our app is working, let’s see how people are using it and how it is perfoming. To do so, we will use <a href="https://github.com/phospho-app/phospho">phospho</a>, an open-source text analytics solution. In this example, we will use the free trial of the hosted version but you can self host it (see the <a href="https://github.com/phospho-app/phospho">github repo</a> for more info on how to do so).</p><p>First we need to get our phospho project id and API key and to add it to our <em>.streamlit/secrets.toml </em>file:</p><pre>PHOSPHO_API_KEY=&quot;&quot;<br>PHOSPHO_PROJECT_ID=&quot;&quot;</pre><pre>pip install --upgrade phospho</pre><p>Then, in our streamlit file, we can start logging messages:</p><pre>import phospho<br><br>phospho.init()<br><br># ...<br><br>phospho.log(input=prompt,<br>            output=chat_answer,<br>            metadata={&quot;sources&quot;: url_sources},<br>        )</pre><p>phospho enable us to handle sessions. Let’s add a session support (see <a href="https://github.com/phospho-app/url2chat/blob/main/main.py">full file on github</a>).</p><p>Let’s handle feedbacks from our users (you will need to have put in place the session id from above):</p><pre>pip install streamlit_feedback</pre><pre>from streamlit_feedback import streamlit_feedback<br><br># ...<br><br># Add feedback button<br>def _submit_feedback(feedback: dict):<br>    # Add a check if phospho is setup<br>    if config.PHOSPHO_API_KEY and config.PHOSPHO_PROJECT_ID:<br>        phospho.user_feedback(<br>            task_id=phospho.latest_task_id,<br>            raw_flag=feedback[&quot;score&quot;],<br>            notes=feedback[&quot;text&quot;],<br>        )<br>        st.toast(f&quot;Thank you for your feedback!&quot;)<br>    else:<br>        st.toast(f&quot;phospho is not setup, feedback not sent.&quot;)<br><br><br>if len(st.session_state.messages) &gt; 1:<br>    feedback = streamlit_feedback(<br>        feedback_type=&quot;thumbs&quot;,<br>        optional_text_label=&quot;[Optional] Please provide an explanation&quot;,<br>        on_submit=_submit_feedback,<br>        # To create a new feedback component for every message and session, you need to provide a unique key<br>        key=f&quot;{st.session_state.session_id}_{len(st.session_state.messages)}&quot;,<br>    )</pre><p>Now, we can use phospho to detect some events of interest:</p><ul><li>When the assistant answer that it doesn’t have the information</li><li>When the users wants to take an action (for instance buying a good or a service)</li></ul><h3>Conclusion</h3><p>In this article, we’ve taken a deep dive into how to build a sophisticated web application, url2chat, that enables users to chat with any website. Leveraging the Exa Neural Search API, OpenAI GPT-3.5 turbo, and Streamlit, we created a system that extracts relevant information from entire websites, generates context-aware responses, and presents it all within a user-friendly interface.</p><h3>Possible improvements</h3><p>According to the data we collected using phospho, the user experinece on our app isn’t meeting our quality standard. Some possible improvements are:</p><ul><li>not using a RAG search API but passing the whole website in the LLM context window (only suitable for small websites)</li><li>use the sitemap to find pages relevant to the query, and then pass these pages to the LLM</li></ul><h3>Want to test it?</h3><p>Clone the Github repo <a href="https://github.com/phospho-app/url2chat">here</a> and run it locally or use the version deployed on Streamlit Community Cloud <a href="https://url2chat.streamlit.app/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ce762e11a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How much does your LLM app suck?]]></title>
            <link>https://medium.com/@plbiojout/how-much-does-your-llm-app-suck-b1c77ce24398?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c77ce24398</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 23:14:59 GMT</pubDate>
            <atom:updated>2024-02-03T23:14:59.048Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TL;DR : a list of the different types of metrics relevant when you are building an LLM app</blockquote><p>Building LLM apps people want is pretty hard. Many teams built great demos, very few built actual products. One of the reasons : compared to other industries, very few metrics are tracked.</p><p>Here is a recap of the different types of metrics that can be relevant when building a LLM app. This is a general overview, the relevance of such metrics depends on the specific use case you are addressing. I broke them down in :</p><ul><li>LLM level metrics</li><li>LLM ops observability metrics</li><li>Product level metrics</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gladpqFquagbV6p2" /><figcaption>Photo by <a href="https://unsplash.com/@valeon?utm_source=medium&amp;utm_medium=referral">Mitchel Boot</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>LLM level metrics</h3><blockquote>The goal : Is this a good LLM?</blockquote><ul><li>Statistical metrics : BLEU, ROUGE, METEOR, Levenshtein distance</li><li>Commonsense Reasoning: Hellaswag, Winogrande, PIQA, SIQA, OpenbookQA, ARC-Easy, ARC-Challenge, and CommonsenseQA.</li><li>World Knowledge: NaturalQuestions and TriviaQA.</li><li>Reading Comprehension: BoolQ and QuAC.</li><li>Math: GSM8K and MATH with maj@4</li><li>Code: Humaneval, MBPP</li><li>Popular aggregated results: MMLU, BBH, AGI Eval</li><li>For chat Assistant (instruct models) : MT Bench</li><li><a href="https://huggingface.co/spaces/lmsys/chatbot-arena-leaderboard">Chatbot Arena</a> : Elo ranking of LLM based on human preferences</li></ul><h3>LLM ops observability metrics</h3><blockquote>The goal : Is everything working as expected</blockquote><ul><li>Token Usage : prompt tokens, completion tokens, total number of tokens</li><li>Time to first token</li><li>Tokens rendered per second</li><li>Number of successful request : is the API provider serving the request, is my own GPU service overloaded?</li><li>Tool usage : how much are the given tools used? One of the tools can be a RAG pipeline.</li></ul><h3>Product level metrics</h3><blockquote>The goal : do users like the product?</blockquote><ul><li>Evaluation : according to my product use case, was the response a success?</li><li>Explicit user feedback : thumbs up or down, accepting the completion…</li><li>Implicit user feedback : if the user prompt again the system with a slight difference, or if the user thanks the assistant</li><li>User Intent Classification : When several scenarios are possible, which one did the user asked for? For instance, sometime users prompt ChatGPT for a text answer, sometime to generate an image.</li><li>Topics Classification : What are user asking for? What is the assistant responding? For a customer support bot, what are the most problematic product categories?</li><li>User Cohorts : who are my power users? What is there</li><li>User Cost : how much does one user cost me? On average, top 10%, bottom 10%,…</li></ul><p>I probably missed some. Please share yours below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c77ce24398" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add analytics and AB tests to your LLM app in JavaScript using phospho]]></title>
            <link>https://medium.com/@plbiojout/add-analytics-and-ab-tests-to-your-llm-app-in-javascript-using-phospho-63e93f0e179a?source=rss-a3785abedfe------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e93f0e179a</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Pierre-Louis Biojout]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 18:48:48 GMT</pubDate>
            <atom:updated>2024-01-18T18:48:48.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an AI agent in JavaScript is now easier than ever. There is plenty of libraries like Langchain JS or Vercel AI to build cool products.</p><p>But like any cutting-edge technology, it comes with its own set of challenges. Hallucinations, incorrect responses, and misunderstandings can plague your LLM based product.</p><p>How to build an AI people want? You need to measure the quality and user satisfaction of your AI-powered product. It’s important to set clear goals and KPIs for your AI agent, focusing not just on its technical capabilities but also on how it meets the needs of its users.</p><blockquote>You can’t build great products without monitoring how they are used.</blockquote><p>So the first step of the journey is to start collecting <strong>analytics</strong> to build relevant <strong>KPIs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-qKF1MV2lXEfvfs-" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Wait, what are analytics?</h3><p>In software, analytics spans from performance metrics to user satisfaction insights :</p><ul><li><strong>Performance Analytics:</strong> Dive deep into code execution details to catch bugs and optimize performance. <em>Is everything working as intended?</em></li><li><strong>Product Analytics:</strong> Assess whether your agent meets the expectations of end-users. <em>Am I making my users happy?</em></li></ul><p>To create exceptional software, it’s crucial to balance both types of analytics. And it’s the same for an agent or an AI.</p><h3>What analytics for your LLM app?</h3><p>In order of priority, you want make sure that :</p><ol><li>Your code runs well and without bugs or crashes.</li><li>The agent answers correctly in the main use case.</li><li>The doesn’t do something crazy in edge cases.</li><li>Users like the agent.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iz42N7yxbGBTuQUpWON_Ag.png" /><figcaption>Levels of maturity of an AI product</figcaption></figure><h3>Now, the JavaScript code!</h3><p>Assuming you have a basic JavaScript agent like this :</p><pre>const myAgent = (query) =&gt; {<br>  // Here, you&#39;d do complex stuff or calls to LLM APIs like OpenAI.<br>  // But for this example we&#39;ll just return the same answer every time.<br>  return &quot;Hello World!&quot;;<br>};</pre><p>You want to collect user inputs and associated outputs of your app. For this example, let’s use <strong>phospho, </strong>a product analytics platform for LLM apps.</p><p>Step 1 : Install the phospho module</p><pre>npm i phospho</pre><p>Step 2: Create an account on the <a href="http://phospho.ai/">phospho</a> platform. Add your API key and project id as environment variables.</p><pre>export PHOSPHO_API_KEY = &quot;YOUR_API_KEY&quot;<br>export PHOSPHO_PROJECT_ID = &quot;YOUR_PROJECT_ID&quot;</pre><p>Step 3: Start capturing interactions of users with your app</p><pre>import { phospho } from &quot;phospho&quot;;<br><br>phospho.init();<br><br>const myAgent = (query) =&gt; {<br>  // Here, you&#39;d do complex stuff.<br>  // But for this example we&#39;ll just return the same answer every time.<br>  return &quot;It&#39;s Paris of course.&quot;;<br>};<br><br>// Log events to phospho by passing strings directly<br>phospho.log({<br>  input: question,<br>  output: myAgent(question),<br>});</pre><p>Now your done! You will collect every interaction with your app, and now be able to build relevant KPIs to improve your product.</p><h3>How to improve the product?</h3><p>In the end, there is only one thing that matters : are you building something people want?</p><h4>1. Understand how your product is currently used</h4><p>phospho also <a href="https://docs.phospho.ai/features/events">detects events</a>. For example, here phospho detected that this interaction was a “question answering” event. Set up custom events that trigger webhooks when detected. For example, to receive a slack message when a user discuss a certain topic.</p><h4>2. Measure the success of the product in doing what the users want</h4><p>phospho automatically labels the task as a <a href="https://docs.phospho.ai/features/evaluation">success or a failure</a> with default criterias. It can be improved with feedback given by you or by your users. Therefor, when a new tasks is logged to phospho, it can be classified as a successful or unsuccessful ineractions <strong>based on your users (or team) criteria</strong></p><h4>3. Improve the product : AB tests</h4><p>Now it’s time to improve this success score! Release several new versions and use <a href="https://docs.phospho.ai/guides/ab-test">phospho’s AB testing tools</a> to see which ones perform better.</p><h3>Conclusion</h3><p>In conclusion, enhancing the performance and user satisfaction of your JavaScript agent involves adding analytics into your development process as early as possible.</p><p>By strategically addressing both performance and product analytics, you can ensure that your agent is actually doing what your users are expecting.</p><p>Explore <a href="https://docs.phospho.ai/">phospho</a> to learn more about how to improve your LLM app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e93f0e179a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>