# Compress Prompt API Source: https://docs.llumo.ai/cost-saving/api-reference/compress-prompt-api post /api/compress Compresses a prompt for query # Setup prompt compression API Source: https://docs.llumo.ai/cost-saving/how-to-docs/compress-first-prompt Start cutting AI cost in just 10 minutes ## Integrating Llumo in LLM Pipeline This guide will explain how to integrate Llumo's prompt compression into a LLM pipeline build on top of OpenAI APIs. Llumo can help reduce token usage and potentially lower costs when working with large language models. We'll go through the process step-by-step to make it easy for developers of all levels. ### Prerequisites * Python 3.7+ * Installed libraries: openai, and requests * Llumo API key * OpenAI API key # Setting up the environment ## Importing libraries: * os: This module provides a way to use operating system dependent functionality, like reading environment variables. * OpenAI: This is the official OpenAI Python client, used to interact with OpenAI's API. * requests: A popular library for making HTTP requests in Python. * json: Used for parsing JSON data, which is common in API responses. * logging: Provides a flexible framework for generating log messages in Python. * getpass: Allows secure password prompts where the input is not displayed on the screen. ## Setting up logging: * We use `logging.basicConfig()` to configure the logging system. The `level=logging.INFO` argument sets the threshold for logging messages to INFO level and above. * We create a logger object named logger that we'll use throughout our script to log important information and errors. This setup ensures we have all necessary tools to interact with APIs, handle data, and track any issues that might occur during execution. ```python theme={null} !pip install openai import os from openai import OpenAI import requests import json import logging from getpass import getpass # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) print("Libraries imported and logging set up successfully.") ``` # Secure API key handling ## Secure API key input: * We use `getpass()` to prompt the user for their API keys. This function hides the input, making it more secure than using regular input(). * This approach is safer than hardcoding API keys in your script, which could accidentally be shared or exposed. ## Setting environment variables: * We use `os.environ` to set environment variables for both API keys. * Environment variables are a secure way to store sensitive information, as they're not part of your code and are only accessible within the current process. ## Initializing the OpenAI client: * We create an instance of the OpenAI client using the API key we just set. * Using `os.getenv("OPENAI_API_KEY")` retrieves the API key from the environment variables. This method ensures that your API keys are handled securely and are readily available for use in your script. ```python theme={null} # Cell 2: Secure API key handling # Securely input API keys openai_api_key = getpass("Enter your OpenAI API key: ") llumo_api_key = getpass("Enter your Llumo API key: ") # Set environment variables os.environ['OPENAI_API_KEY'] = openai_api_key os.environ['LLUMO_API_KEY'] = llumo_api_key # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) print("API keys securely set and OpenAI client initialized.") ``` # Define Llumo compression function ## Function definition: * We define a function `compress_with_llumo` that takes a text input and an optional topic. ## API setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ## Payload preparation: * We create a payload dictionary with the input text. * If a topic is provided, we add it to the payload. ## API request: * We use `requests.post()` to send a POST request to the Llumo API. `response.raise_for_status()` will raise an exception for HTTP errors. ## Response parsing: * We parse the JSON response and extract the compressed text and token counts. * We calculate the compression percentage. ## Error handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * Unexpected response structure * If an error occurs, we log it and return the original text with failure indicators. ## Return values: * The function returns a tuple containing: * Compressed text (or original if compression failed) * Success boolean * Compression percentage * Initial token count * Final token count This function encapsulates the entire process of interacting with the Llumo API for text compression, including error handling and result processing. ```python theme={null} def compress_with_llumo(text, topic=None): # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') # Define the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" # Set the headers for the API request headers = { "Content-Type": "application/json", # Specify the content type as JSON "Authorization": f"Bearer {LLUMO_API_KEY}" # Authorization header with the API key } # Create the payload for the API request with the provided text payload = {"prompt": text} # If a topic is provided, add it to the payload if topic: payload["topic"] = topic try: # Make a POST request to the Llumo API with the payload and headers response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) # Raise an exception if the request was unsuccessful response.raise_for_status() # Parse the JSON response from the API result = response.json() # Extract the 'data' field from the JSON response data = result['data']['data'] # Parse the JSON string in the 'data' field data_content = json.loads(data) # Get the compressed text from the parsed JSON compressed_text = data_content.get('compressedPrompt', text) # Get the initial and final token counts from the parsed JSON initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) # Calculate the compression percentage if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 # Return the compressed text, success flag, compression percentage, and token counts return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: # Print an error message if an exception occurs print(f"Error compressing text: {str(e)}") # Return the original text, failure flag, and zeroed metrics return text, False, 0, 0, 0 ``` # Define example prompt and test without compression ## Defining the prompt: * We create a detailed prompt about photosynthesis. This serves as our example text for compression. ## Testing without compression: * We use the OpenAI client to send a request to the GPT-3.5-turbo model. * The messages parameter follows the chat format: * A system message sets the AI's role. * A user message contains our prompt. ## Displaying results: * We print the AI's response to the prompt. * We also print the total number of tokens used, which is important for understanding API usage and costs. This cell demonstrates how the API would typically be used without any compression, providing a baseline for comparison. ```python theme={null} # Cell 4: Define example prompt and test without compression # Example prompt prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ topic= "what is the moral of story" print("Without Llumo Compression:") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}\n") ``` # Test with Llumo compression ## Applying Llumo compression: * We call compress\_with\_llumo() with our example prompt. * The function returns multiple values, which we unpack into separate variables. ## Checking compression success: * We use an if statement to check if compression was successful. * If successful, we print compression statistics: percentage, initial and final token counts. ## Using the compressed prompt: * If compression succeeded, we use the compressed prompt in our API call to GPT-3.5-turbo. * We use the same message structure as before, but with the compressed prompt. ## Displaying results: * We print the AI's response to the compressed prompt. * We print the number of tokens used with the compressed prompt. ## Handling compression failure: * If compression fails, we print a message indicating this. * In a real application, you might want to fall back to using the original prompt in this case. This cell demonstrates the full process of compressing a prompt with Llumo and using it with the OpenAI API. By comparing the results and token usage with the previous cell, you can see the potential benefits of using Llumo compression in terms of token efficiency and cost savings. ```python theme={null} # Cell 5: Test with Llumo compression print("With Llumo Compression:") compressed_prompt, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(prompt, topic) if success: print(f"Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}, Final tokens: {final_tokens}") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": compressed_prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}") else: print("Compression failed. Using original prompt.") # Use the original prompt if compression fails ``` # LLUMO Compressor API with Langchain Source: https://docs.llumo.ai/cost-saving/how-to-docs/llumo-compressor-langchain Save cost in Langchain pipeline using LLUMO compressor API # Introduction Welcome to this Colab Notebook tutorial! In this guide, we will demonstrate how to efficiently incorporate the LLUMO Compressor API into your Langchain pipeline to save costs while utilizing Large Language Models (LLMs). Specifically, we will walk you through the process of extracting answers from a PDF document by integrating Langchain for vector search, OpenAI for generating answers, and LLUMO to compress prompts before sending them to OpenAI. ## What You'll Learn 1. **Langchain Integration**: How to use Langchain for efficient vector search to locate relevant text passages within a PDF document. 2. **OpenAI Integration**: How to utilize OpenAI's LLM for generating answers based on the extracted text passages. 3. **LLUMO Compressor API**: How to integrate the LLUMO Compressor API into your pipeline to compress prompts, reducing the amount of data sent to OpenAI and thus saving on API usage costs. ## Why This Tutorial? Using LLMs like OpenAI's GPT-4 can be expensive, especially when dealing with large documents or frequent queries. The LLUMO Compressor API helps mitigate these costs by compressing prompts before they are sent to the LLM, ensuring you get the same high-quality responses at a lower cost. This tutorial is particularly useful for developers and data scientists who want to optimize their Langchain pipelines by incorporating cost-saving measures without compromising on performance. By the end of this tutorial, you will have a fully functional pipeline that efficiently extracts and processes information from PDFs, providing accurate answers while minimizing costs through prompt compression. Let's get started! # Step 1: Installing Required Python Libraries In this first step, we will install several essential Python libraries that are required to build our Langchain pipeline with the LLUMO Compressor API. Each library serves a specific purpose in our workflow, enabling us to handle natural language processing, PDF reading, environment variable management, similarity search, and interaction with OpenAI's API. Here's a detailed overview of each library we will be using: 1. **Langchain**: This library and its components provide a robust framework for natural language processing tasks. Langchain offers tools for constructing, training, and deploying language models, making it an integral part of our pipeline for vector search and text processing. 2. **PyPDF2**: PyPDF2 is a pure Python library that allows us to read and manipulate PDF files. In this tutorial, we will use PyPDF2 to extract text from PDF documents, which will then be processed and analyzed using our natural language processing tools. 3. **python-dotenv**: This library is used for managing environment variables in Python. By using python-dotenv, we can securely store and access sensitive information such as API keys and other configuration settings needed for our project. 4. **faiss-cpu**: Developed by Facebook AI Research, faiss-cpu is a powerful library for efficient similarity search and clustering of dense vectors. We will use faiss-cpu to perform vector search on the text extracted from PDF documents, enabling us to find relevant passages quickly and accurately. 5. **openai**: The openai library allows us to interact with OpenAI's API, enabling us to use their powerful language models for generating answers. This library will be crucial for sending prompts and receiving responses from OpenAI's LLM. 6. **requests and json**: These libraries are used for making HTTP requests and handling JSON data, respectively. We will use requests to communicate with external APIs, including the LLUMO Compressor API, and json to parse and manipulate JSON data returned by these APIs. Let's start by installing these libraries using the following pip command. This command will ensure that all the necessary libraries are installed and ready to use in our Colab environment. ```python theme={null} !pip install langchain==0.1.7 langchain-openai==0.0.5 langchain-community==0.0.20 PyPDF2==3.0.1 python-dotenv==1.0.1 faiss-cpu==1.7.4 openai==1.12.0 ``` # Step 2: Importing Required Libraries Before we dive into the specific functions and steps of our pipeline, it's important to import all the necessary libraries that we'll be using throughout this notebook. ```python theme={null} import os from getpass import getpass from PyPDF2 import PdfReader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_community.vectorstores import FAISS from langchain.chains.question_answering import load_qa_chain from langchain.callbacks import get_openai_callback from langchain.schema import Document import requests import json ``` # Step 3: Setting Up API Keys To interact with OpenAI's API and the LLUMO Compressor API, we need to provide our unique API keys for authentication. These keys are sensitive pieces of information that should be handled securely. In this step, we will use Python's `getpass` module to safely input our API keys and then store them in environment variables for later use. ### Explanation: 1. **Importing Required Modules**: * `getpass`: This module provides a way to securely prompt the user for input without echoing the input back to the screen. This is particularly useful for handling sensitive information like API keys. * `os`: This module provides a way to interact with the operating system, including setting environment variables. 2. **Prompting for OpenAI API Key**: * `openai_api_key = getpass("Enter your OpenAI API key: ")`: This line prompts the user to enter their OpenAI API key. The input is not displayed on the screen for security reasons. 3. **Prompting for LLUMO API Key**: * `llumo_api_key = getpass("Enter your LLUMO API key: ")`: Similarly, this line prompts the user to enter their LLUMO API key securely. 4. **Storing API Keys in Environment Variables**: * `os.environ['OPENAI_API_KEY'] = openai_api_key`: This line stores the OpenAI API key in an environment variable named `OPENAI_API_KEY`. * `os.environ['LLUMO_API_KEY'] = llumo_api_key`: This line stores the LLUMO API key in an environment variable named `LLUMO_API_KEY`. 5. **Deleting the Variables**: * `del openai_api_key`: This line deletes the variable `openai_api_key` from memory to ensure that the API key is not accidentally exposed or misused later in the code. * `del llumo_api_key`: This line deletes the variable `llumo_api_key` for the same reason. By following these steps, we ensure that our API keys are securely handled and stored, reducing the risk of accidental exposure. This setup is crucial for maintaining the security and integrity of our project. ```python theme={null} # Prompting the user to securely input their OpenAI API key openai_api_key = getpass("Enter your OpenAI API key: ") # Prompting the user to securely input their LLUMO API key llumo_api_key = getpass("Enter your LLUMO API key: ") # Storing the OpenAI API key in an environment variable os.environ['OPENAI_API_KEY'] = openai_api_key # Storing the LLUMO API key in an environment variable os.environ['LLUMO_API_KEY'] = llumo_api_key # Deleting the variables that hold the API keys to prevent them from being exposed in the code del openai_api_key del llumo_api_key ``` # Step 4: Loading and Extracting Text from PDF In this step, we define a function to read a PDF file and extract all its text content. This function, `load_pdf`, utilizes the `PdfReader` class from the `PyPDF2` library to achieve this. By looping through each page in the PDF and using the `extract_text()` method, it collects all the text and returns it as a single string. This function is a key component of our pipeline, as it allows us to convert the PDF content into a format that can be further processed and analyzed using natural language processing tools. ### Explanation: 1. **Importing the PdfReader Class**: * `from PyPDF2 import PdfReader`: This line imports the `PdfReader` class from the `PyPDF2` library. `PdfReader` is used to read and manipulate PDF files. 2. **Defining the `load_pdf` Function**: * `def load_pdf(pdf):`: This line defines a function named `load_pdf` that takes a single argument, `pdf`, which is the path to the PDF file we want to read. 3. **Creating a PdfReader Instance**: * `pdf_reader = PdfReader(pdf)`: This line creates an instance of `PdfReader` for the given PDF file. This instance allows us to access the contents of the PDF. 4. **Initializing a Text Variable**: * `text = ""`: This line initializes an empty string variable `text` that will be used to accumulate the extracted text from each page of the PDF. 5. **Looping Through the Pages**: * `for page in pdf_reader.pages:`: This line starts a loop that iterates over each page in the PDF. `pdf_reader.pages` is a list of all the pages in the PDF. 6. **Extracting Text from Each Page**: * `text += page.extract_text()`: Within the loop, this line extracts the text content from the current page using the `extract_text()` method and appends it to the `text` variable. This method is provided by the `PyPDF2` library and returns the text found on the page. 7. **Returning the Extracted Text**: * `return text`: After the loop has processed all the pages, this line returns the accumulated text as a single string. ```python theme={null} def load_pdf(pdf): pdf_reader = PdfReader(pdf) text = "" for page in pdf_reader.pages: text += page.extract_text() return text ``` # Step 5: Splitting Text into Manageable Chunks In this step, we define a function to split a large block of text into smaller, manageable chunks. This is important for efficiently processing the text with natural language processing tools, as working with smaller chunks can improve performance and accuracy. The function `split_text` uses `RecursiveCharacterTextSplitter`, imported above, to achieve this. ### Explanation: 1. **Importing the RecursiveCharacterTextSplitter Class**: * `from langchain.text_splitter import RecursiveCharacterTextSplitter`: This line imports the `RecursiveCharacterTextSplitter` class from the `langchain.text_splitter` module. This class is designed to split text into smaller chunks based on specified parameters. 2. **Defining the `split_text` Function**: * `def split_text(text):`: This line defines a function named `split_text` that takes a single argument, `text`, which is the large block of text we want to split into smaller chunks. 3. **Creating an Instance of RecursiveCharacterTextSplitter**: * `text_splitter = RecursiveCharacterTextSplitter(`: This line initializes an instance of `RecursiveCharacterTextSplitter` with specific parameters: * `chunk_size=1000`: This parameter sets the maximum size of each text chunk to 1000 characters. This ensures that each chunk is not too large to handle efficiently. * `chunk_overlap=200`: This parameter sets the overlap between consecutive chunks to 200 characters. Overlapping chunks can help maintain context between chunks, which can be important for tasks like text analysis and question answering. * `length_function=len`: This parameter specifies the function used to measure the length of the text. In this case, the built-in `len` function is used, which measures the length in characters. 4. **Splitting the Text**: * `return text_splitter.split_text(text=text)`: This line uses the `split_text` method of the `RecursiveCharacterTextSplitter` instance to split the input `text` into smaller chunks based on the specified parameters. The method returns a list of text chunks. ```python theme={null} def split_text(text): text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, length_function=len ) return text_splitter.split_text(text=text) ``` # Step 6: Loading Embeddings and Creating a Vector Store In this step, we define a function to create embeddings for text chunks and store them in a vector store. This is essential for performing efficient similarity searches and finding relevant text passages. The function `load_embeddings` uses the `OpenAIEmbeddings` class and the `FAISS` vector store. ### Explanation: 1. **Importing Necessary Classes**: * `from langchain_openai import OpenAIEmbeddings`: This import statement brings in the `OpenAIEmbeddings` class, which is used to generate embeddings for text using OpenAI's models. * `from langchain_community.vectorstores import FAISS`: This import statement brings in the `FAISS` class, which is used to create and manage a vector store for efficient similarity search. 2. **Defining the `load_embeddings` Function**: * `def load_embeddings(store_name, chunks):`: This line defines a function named `load_embeddings` that takes two arguments: * `store_name`: A placeholder for the name of the vector store (not used in this specific function but can be useful for future extensions). * `chunks`: A list of text chunks for which embeddings will be generated. 3. **Creating an OpenAIEmbeddings Instance**: * `embeddings = OpenAIEmbeddings()`: This line initializes an instance of the `OpenAIEmbeddings` class. This instance will be used to generate embeddings for the text chunks. 4. **Creating a FAISS Vector Store**: * `vector_store = FAISS.from_texts(chunks, embedding=embeddings)`: This line creates a `FAISS` vector store from the list of text chunks. The `from_texts` method generates embeddings for each chunk using the `embeddings` instance and stores them in the FAISS vector store. This vector store enables efficient similarity search, allowing us to quickly find the most relevant text chunks based on query embeddings. 5. **Returning the Vector Store**: * `return vector_store`: This line returns the created FAISS vector store. The vector store contains the embeddings for all the text chunks and is ready for similarity search operations. ```python theme={null} def load_embeddings(store_name, chunks): embeddings = OpenAIEmbeddings() vector_store = FAISS.from_texts(chunks, embedding=embeddings) return vector_store ``` # Step 7: Compressing Text with LLUMO API In this step, we define a function to compress text using the LLUMO Compressor API. This function sends a request to the LLUMO API, receives the compressed text, and calculates the compression percentage. The function also handles any errors that might occur during the process. Let's understand each step one by one #### Retrieving the LLUMO API Key ```python theme={null} # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') ``` * This line retrieves the LLUMO API key from the environment variables using `os.getenv()`. The API key is essential for authenticating the request to the LLUMO API. #### Setting the LLUMO API Endpoint ```python theme={null} # Set the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" ``` * This line sets the endpoint URL for the LLUMO API that handles text compression. #### Preparing Headers for the API Request ```python theme={null} # Prepare headers for the API request headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } ``` * This block prepares the headers required for the API request, including the content type (`application/json`) and the authorization token (`Bearer {LLUMO_API_KEY}`). #### Preparing the Payload for the API Request ```python theme={null} # Prepare the payload for the API request payload = {"prompt": text} if topic: payload["topic"] = topic # Add topic to payload if provided ``` * This block prepares the payload (data to be sent in the request) with the text to be compressed. If a topic is provided, it adds the topic to the payload. #### Sending the POST Request to LLUMO API ```python theme={null} try: # Send POST request to Llumo API response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) response.raise_for_status() # Raise an exception for bad status codes ``` * This block sends a POST request to the LLUMO API with the prepared payload and headers. The `raise_for_status()` method raises an exception if the request fails. #### Parsing the JSON Response ```python theme={null} # Parse the JSON response result = response.json() data = result['data']['data'] data_content = json.loads(data) ``` * This block parses the JSON response from the API. It extracts the relevant data and converts it from a JSON string to a Python dictionary. #### Extracting Compressed Text and Token Counts ```python theme={null} # Extract compressed text and token counts from the response compressed_text = data_content.get('compressedPrompt', text) # Use original text if compression fails initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) ``` * This block extracts the compressed text and token counts (initial and final) from the response. If compression fails, it defaults to using the original text. #### Calculating Compression Percentage ```python theme={null} # Calculate compression percentage if token counts are available if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 ``` * This block calculates the compression percentage based on the initial and final token counts. If these counts are not available, the compression percentage is set to 0. #### Returning the Results ```python theme={null} # Return compressed text, success status, and compression statistics return compressed_text, True, compression_percentage, initial_tokens, final_tokens ``` * This block returns the compressed text, a success status, and the compression statistics (compression percentage, initial tokens, and final tokens). #### Handling Exceptions ```python theme={null} except Exception as e: # If an error occurs, print the error and return original text with failure status print(f"Error compressing text: {str(e)}") return text, False, 0, 0, 0 ``` * This block handles any exceptions that occur during the process, printing an error message and returning the original text with a failure status. ### Final Code Integration We will now combine everything to get the final code. ```python theme={null} def compress_with_llumo(text, topic=None): LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } payload = {"prompt": text} if topic: payload["topic"] = topic try: response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) response.raise_for_status() result = response.json() data = result['data']['data'] data_content = json.loads(data) compressed_text = data_content.get('compressedPrompt', text) initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: print(f"Error compressing text: {str(e)}") return text, False, 0, 0, 0 ``` # Step 8: Main Function - Integrating All Steps The `main` function serves as the entry point for our PDF Query Assistant. It integrates all the steps discussed previously, from uploading and processing a PDF file to querying the content and using LLUMO compression to optimize costs. We will go in details of each part of the `main` function: #### Initialization and PDF Upload ```python theme={null} print("PDF Query Assistant with Llumo Compression") # Upload PDF from google.colab import files uploaded = files.upload() if uploaded: pdf_file = list(uploaded.keys())[0] ``` * **Printing the Title**: Displays the title of the assistant. * **Uploading the PDF**: Uses Google Colab's `files.upload()` to upload a PDF file. * **Retrieving the File Name**: Gets the name of the uploaded file. #### Processing the PDF ```python theme={null} # Process the PDF text = load_pdf(pdf_file) chunks = split_text(text) store_name = pdf_file[:-4] ``` * **Loading PDF**: Calls the `load_pdf` function to extract text from the PDF. * **Splitting Text**: Calls the `split_text` function to split the extracted text into manageable chunks. * **Store Name**: Generates a name for the vector store by removing the file extension from the PDF file name. #### Creating the Vector Store ```python theme={null} # Create vector store vector_store = load_embeddings(store_name, chunks) ``` * **Loading Embeddings**: Calls the `load_embeddings` function to create a vector store using the text chunks. #### Handling User Query ```python theme={null} # User Query Input query = input("Ask any question related to the content of the PDF: ") if query: # Similarity Search docs = vector_store.similarity_search(query=query, k=3) # Prepare context for compression context = " ".join([doc.page_content for doc in docs]) ``` * **User Query Input**: Prompts the user to input a query related to the PDF content. * **Similarity Search**: Performs a similarity search using the vector store to find the most relevant text chunks. * **Preparing Context**: Joins the content of the retrieved documents to form the context for compression. #### Compressing Context with LLUMO ```python theme={null} # Compress context using Llumo compressed_text, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(context, topic=query) if success: print(f"Llumo Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}") print(f"Final tokens: {final_tokens}") ``` * **Compressing Context**: Calls the `compress_with_llumo` function to compress the context using LLUMO API. * **Handling Success**: If compression is successful, prints the compression percentage and token counts. #### Generating Response with Compressed Context ```python theme={null} # Generate response using compressed text llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) chain = load_qa_chain(llm=llm, chain_type="stuff") with get_openai_callback() as cb: response = chain.run(input_documents=[Document(page_content=compressed_text)], question=query) print("Answer:") print(response) print(f"Cost of this query: ${cb.total_cost:.5f}") ``` * **LLM Initialization**: Initializes a language model (`ChatOpenAI`) with specified parameters. * **Loading QA Chain**: Loads a question-answering chain using `load_qa_chain`. * **Generating Response**: Runs the QA chain with the compressed text and prints the answer along with the cost of the query. #### Handling Compression Failure ```python theme={null} else: print("Failed to compress the text with Llumo. Using original context.") # Fallback: Use original context if compression fails llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) chain = load_qa_chain(llm=llm, chain_type="stuff") with get_openai_callback() as cb: response = chain.run(input_documents=docs, question=query) print("Answer:") print(response) print(f"Cost of this query: ${cb.total_cost:.5f}") ``` * **Compression Failure**: If compression fails, prints a message indicating the failure and uses the original context to generate a response. * **Fallback Response Generation**: Runs the QA chain with the original text chunks and prints the answer along with the cost. ### Final Code Integration We have now integrated all the steps to get the final code in the `main` function. This comprehensive function handles PDF uploading, text extraction, text chunking, embedding generation, similarity search, text compression with LLUMO, and generating a response to the user's query using the compressed or original text. ```python theme={null} def main(): print("PDF Query Assistant with Llumo Compression") # Upload PDF from google.colab import files uploaded = files.upload() if uploaded: pdf_file = list(uploaded.keys())[0] # Process the PDF text = load_pdf(pdf_file) chunks = split_text(text) store_name = pdf_file[:-4] # Create vector store vector_store = load_embeddings(store_name, chunks) # User Query Input query = input("Ask any question related to the content of the PDF: ") if query: # Similarity Search docs = vector_store.similarity_search(query=query, k=3) # Prepare context for compression context = " ".join([doc.page_content for doc in docs]) # Compress context using Llumo compressed_text, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(context, topic=query) if success: print(f"Llumo Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}") print(f"Final tokens: {final_tokens}") # Generate response using compressed text llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) chain = load_qa_chain(llm=llm, chain_type="stuff") with get_openai_callback() as cb: response = chain.run(input_documents=[Document(page_content=compressed_text)], question=query) print("Answer:") print(response) print(f"Cost of this query: ${cb.total_cost:.5f}") else: print("Failed to compress the text with Llumo. Using original context.") # Fallback: Use original context if compression fails llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) chain = load_qa_chain(llm=llm, chain_type="stuff") with get_openai_callback() as cb: response = chain.run(input_documents=docs, question=query) print("Answer:") print(response) print(f"Cost of this query: ${cb.total_cost:.5f}") ``` # Step 9 : Running the main function By including this check, we ensure that the main() function is only executed when the script is run directly, providing flexibility and preventing unintended behavior when the script is imported elsewhere. It will ask you to upload a PDF and then when uploaded, it will receive input for the question you want to be answered. ```python theme={null} if __name__ == '__main__': main() ``` # LLUMO Compressor API with Llama Index Source: https://docs.llumo.ai/cost-saving/how-to-docs/llumo-compressor-llama Save cost in Llama Index pipeline using LLUMO compressor API # Introduction Welcome to this Colab Notebook tutorial! In this guide, we will demonstrate how to efficiently incorporate the LLUMO Compressor API into your LlamaIndex pipeline to save costs while utilizing Large Language Models (LLMs). Specifically, we will walk you through the process of extracting answers from a PDF document by integrating LlamaIndex for vector search, OpenAI for generating answers, and LLUMO to compress prompts before sending them to OpenAI. ## What You'll Learn 1. **LlamaIndex Integration**: How to use LlamaIndex for efficient vector search to locate relevant text passages within a PDF document. 2. **OpenAI Integration**: How to utilize OpenAI's LLM for generating answers based on the extracted text passages. 3. **LLUMO Compressor API**: How to integrate the LLUMO Compressor API into your pipeline to compress prompts, reducing the amount of data sent to OpenAI and thus saving on API usage costs. ## Why This Tutorial? Using LLMs like OpenAI's GPT-4 can be expensive, especially when dealing with large documents or frequent queries. The LLUMO Compressor API helps mitigate these costs by compressing prompts before they are sent to the LLM, ensuring you get the same high-quality responses at a lower cost. This tutorial is particularly useful for developers and data scientists who want to optimize their LlamaIndex pipelines by incorporating cost-saving measures without compromising on performance. By the end of this tutorial, you will have a fully functional pipeline that efficiently extracts and processes information from PDFs, providing accurate answers while minimizing costs through prompt compression. Let's get started! # Step 1: Installing Required Python Libraries In this first step, we will install several essential Python libraries that are required to build our LlamaINdex pipeline with the LLUMO Compressor API. Each library serves a specific purpose in our workflow, enabling us to handle natural language processing, PDF reading, environment variable management, similarity search, and interaction with OpenAI's API. Here's a detailed overview of each library we will be using: 1. **llama-index**: Specifically, we will walk you through the process of extracting answers from a PDF document by integrating LlamaIndex for vector search, OpenAI for generating answers, and LLUMO to compress prompts before sending them to OpenAI. 2. **PyPDF2**: PyPDF2 is a pure Python library that allows us to read and manipulate PDF files. In this tutorial, we will use PyPDF2 to extract text from PDF documents, which will then be processed and analyzed using our natural language processing tools. 3. **python-dotenv**: This library is used for managing environment variables in Python. By using python-dotenv, we can securely store and access sensitive information such as API keys and other configuration settings needed for our project. 4. **openai**: The openai library allows us to interact with OpenAI's API, enabling us to use their powerful language models for generating answers. This library will be crucial for sending prompts and receiving responses from OpenAI's LLM. 5. **requests and json**: These libraries are used for making HTTP requests and handling JSON data, respectively. We will use requests to communicate with external APIs, including the LLUMO Compressor API, and json to parse and manipulate JSON data returned by these APIs. Let's start by installing these libraries using the following pip command. This command will ensure that all the necessary libraries are installed and ready to use in our Colab environment. ```python theme={null} !pip install llama-index==0.9.48 PyPDF2==3.0.1 python-dotenv==1.0.1 openai==1.12.0 pypdf ``` # Step 2: Importing Required Libraries Before we dive into the specific functions and steps of our pipeline, it's important to import all the necessary libraries that we'll be using throughout this notebook. ### Explanation: 1. **`import os`**: This module provides a way to interact with the operating system, including setting and retrieving environment variables. 2. **`from getpass import getpass`**: This module allows us to securely prompt the user for sensitive information, such as API keys, without echoing the input back to the screen. 3. **`from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, Document`**: These classes are core components of LlamaIndex. They are used for creating and querying vector indexes, reading documents, and configuring the indexing and querying process. 4. **`from llama_index.llms import OpenAI`**: This class is used to interact with OpenAI's API for generating responses from their language models. 5. **`import requests`**: This library is used for making HTTP requests, which we will need to communicate with external APIs, including the LLUMO Compressor API. 6. **`import json`**: This library is used for parsing and manipulating JSON data, which is often the format of data exchanged between APIs. ```python theme={null} import os from getpass import getpass from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, Document from llama_index.llms import OpenAI import requests import json ``` # Step 3: Setting Up API Keys To interact with OpenAI's API and the LLUMO Compressor API, we need to provide our unique API keys for authentication. These keys are sensitive pieces of information that should be handled securely. In this step, we will use Python's `getpass` module to safely input our API keys and then store them in environment variables for later use. ### Explanation: 1. **Importing Required Modules**: * `getpass`: This module provides a way to securely prompt the user for input without echoing the input back to the screen. This is particularly useful for handling sensitive information like API keys. * `os`: This module provides a way to interact with the operating system, including setting environment variables. 2. **Prompting for OpenAI API Key**: * `openai_api_key = getpass("Enter your OpenAI API key: ")`: This line prompts the user to enter their OpenAI API key. The input is not displayed on the screen for security reasons. 3. **Prompting for LLUMO API Key**: * `llumo_api_key = getpass("Enter your LLUMO API key: ")`: Similarly, this line prompts the user to enter their LLUMO API key securely. 4. **Storing API Keys in Environment Variables**: * `os.environ['OPENAI_API_KEY'] = openai_api_key`: This line stores the OpenAI API key in an environment variable named `OPENAI_API_KEY`. * `os.environ['LLUMO_API_KEY'] = llumo_api_key`: This line stores the LLUMO API key in an environment variable named `LLUMO_API_KEY`. 5. **Deleting the Variables**: * `del openai_api_key`: This line deletes the variable `openai_api_key` from memory to ensure that the API key is not accidentally exposed or misused later in the code. * `del llumo_api_key`: This line deletes the variable `llumo_api_key` for the same reason. By following these steps, we ensure that our API keys are securely handled and stored, reducing the risk of accidental exposure. This setup is crucial for maintaining the security and integrity of our project. ```python theme={null} # Prompting the user to securely input their OpenAI API key openai_api_key = getpass("Enter your OpenAI API key: ") # Prompting the user to securely input their LLUMO API key llumo_api_key = getpass("Enter your LLUMO API key: ") # Storing the OpenAI API key in an environment variable os.environ['OPENAI_API_KEY'] = openai_api_key # Storing the LLUMO API key in an environment variable os.environ['LLUMO_API_KEY'] = llumo_api_key # Deleting the variables that hold the API keys to prevent them from being exposed in the code del openai_api_key del llumo_api_key ``` # Step 4: Loading and Extracting Text from PDF In this step, we define a function to read a PDF file, extract its text content, and process it for indexing. This function, load\_and\_process\_pdf, utilizes the SimpleDirectoryReader class from LlamaIndex to read the PDF, and then manually chunks the text for more efficient processing. This function is a key component of our pipeline, as it allows us to convert the PDF content into a format that can be efficiently indexed and queried using LlamaIndex 1. **Defining the load\_and\_process\_pdf Function:** * def `load_and_process_pdf(file_path):`: This line defines a function named `load_and_process_pdf` that takes a single argument, `file_path`, which is the path to the PDF file we want to read and process. 2. **Loading the PDF**: * `raw_documents = SimpleDirectoryReader(input_files=[file_path]).load_data()`: This line uses LlamaIndex's `SimpleDirectoryReader` to load the PDF file. It returns a list of `Document` objects, each representing a page or section of the PDF. 3. **Creating Smaller Text Chunks**: * We iterate through each `Document` object in `raw_documents` and split its text content into smaller chunks. This is done to ensure that each chunk is of a manageable size for processing and indexing. * `text_chunks = [doc.text[i:i+1000] for i in range(0, len(doc.text), 800)]`: This line creates chunks of 1000 characters with an overlap of 200 characters between chunks. 4. **Creating Document Objects from Chunks:** * `documents.extend([Document(text=chunk) for chunk in text_chunks])`: This line creates new `Document` objects for each text chunk and adds them to the `documents` list. 5. **Configuring the Service Context**: * `service_context = ServiceContext.from_defaults(llm=OpenAI(temperature=0, model_name="gpt-3.5-turbo"))`: This line sets up the service context for LlamaIndex, specifying the OpenAI model to use for text generation. 6. **Creating the Vector Store Index**: * `index = VectorStoreIndex.from_documents(documents, service_context=service_context)`: This line creates a `VectorStoreIndex` from the processed documents, using the specified service context. 7. **Returning the Index:** * `return index`: After processing and indexing the PDF content, this line returns the created index. This function effectively loads the PDF, breaks it down into manageable chunks, and creates an index that can be efficiently queried. By using LlamaIndex's built-in classes and methods, we ensure that the PDF content is properly prepared for our question-answering system. ```python theme={null} def load_and_process_pdf(file_path): # Load the PDF raw_documents = SimpleDirectoryReader(input_files=[file_path]).load_data() # Create documents with smaller chunk sizes documents = [] for doc in raw_documents: text_chunks = [doc.text[i:i+1000] for i in range(0, len(doc.text), 800)] # 1000 chunk size, 200 overlap documents.extend([Document(text=chunk) for chunk in text_chunks]) # Configure Service Context service_context = ServiceContext.from_defaults(llm=OpenAI(temperature=0, model_name="gpt-3.5-turbo")) # Create index index = VectorStoreIndex.from_documents(documents, service_context=service_context) return index ``` # Step 5: Compressing Text with LLUMO API In this step, we define a function to compress text using the LLUMO Compressor API. This function sends a request to the LLUMO API, receives the compressed text, and calculates the compression percentage. The function also handles any errors that might occur during the process. Let's understand each step one by one 1. **Retrieving the LLUMO API Key** ```python theme={null} # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') ``` * This line retrieves the LLUMO API key from the environment variables using `os.getenv()`. The API key is essential for authenticating the request to the LLUMO API. 2. **Setting the LLUMO API Endpoint** ```python theme={null} # Set the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" ``` * This line sets the endpoint URL for the LLUMO API that handles text compression. 3. **Preparing Headers for the API Request** ```python theme={null} # Prepare headers for the API request headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } ``` * This block prepares the headers required for the API request, including the content type (`application/json`) and the authorization token (`Bearer {LLUMO_API_KEY}`). 4. **Preparing the Payload for the API Request** ```python theme={null} # Prepare the payload for the API request payload = {"prompt": text} if topic: payload["topic"] = topic # Add topic to payload if provided ``` * This block prepares the payload (data to be sent in the request) with the text to be compressed. If a topic is provided, it adds the topic to the payload. 5. **Sending the POST Request to LLUMO API** ```python theme={null} try: # Send POST request to Llumo API response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) response.raise_for_status() # Raise an exception for bad status codes ``` * This block sends a POST request to the LLUMO API with the prepared payload and headers. The `raise_for_status()` method raises an exception if the request fails. 6. **Parsing the JSON Response** ```python theme={null} # Parse the JSON response result = response.json() data = result['data']['data'] data_content = json.loads(data) ``` * This block parses the JSON response from the API. It extracts the relevant data and converts it from a JSON string to a Python dictionary. 7. **Extracting Compressed Text and Token Counts** ```python theme={null} # Extract compressed text and token counts from the response compressed_text = data_content.get('compressedPrompt', text) # Use original text if compression fails initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) ``` * This block extracts the compressed text and token counts (initial and final) from the response. If compression fails, it defaults to using the original text. 8. **Calculating Compression Percentage** ```python theme={null} # Calculate compression percentage if token counts are available if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 ``` * This block calculates the compression percentage based on the initial and final token counts. If these counts are not available, the compression percentage is set to 0. 9. **Returning the Results** ```python theme={null} # Return compressed text, success status, and compression statistics return compressed_text, True, compression_percentage, initial_tokens, final_tokens ``` * This block returns the compressed text, a success status, and the compression statistics (compression percentage, initial tokens, and final tokens). 10. **Handling Exceptions** ```python theme={null} except Exception as e: # If an error occurs, print the error and return original text with failure status print(f"Error compressing text: {str(e)}") return text, False, 0, 0, 0 ``` * This block handles any exceptions that occur during the process, printing an error message and returning the original text with a failure status. 11. **Final Code Integration** We will now combine everything to get the final code. ```python theme={null} def compress_with_llumo(text, topic=None): LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } payload = {"prompt": text} if topic: payload["topic"] = topic try: response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) response.raise_for_status() result = response.json() data = result['data']['data'] data_content = json.loads(data) compressed_text = data_content.get('compressedPrompt', text) initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: print(f"Error compressing text: {str(e)}") return text, False, 0, 0, 0 ``` # Step 6: Main Function - Integrating All Steps The `main` function serves as the entry point for our PDF Query Assistant. It integrates all the steps discussed previously, from uploading and processing a PDF file to querying the content and using LLUMO compression to optimize costs. We will go in details of each part of the `main` function: #### Initialization and PDF Upload ```python theme={null} print("PDF Query Assistant with Llumo Compression") # Upload PDF from google.colab import files uploaded = files.upload() if uploaded: pdf_file = list(uploaded.keys())[0] ``` * **Printing the Title**: Displays the title of the assistant. * **Uploading the PDF**: Uses Google Colab's `files.upload()` to upload a PDF file. * **Retrieving the File Name**: Gets the name of the uploaded file. #### Processing the PDF ```python theme={null} # Process the PDF print("Processing PDF...") index = load_and_process_pdf(pdf_file) ``` Calls the `load_and_process_pdf` function to extract text from the PDF and convert into chunks. #### Handling User Query ```python theme={null} # User Query Input query = input("Ask any question related to the content of the PDF: ") if query: ## Similarity Search retriever = index.as_retriever(similarity_top_k=3) retrieved_nodes = retriever.retrieve(query) # Prepare context for compression context = " ".join([node.node.text for node in retrieved_nodes]) ``` * **User Query Input**: Prompts the user to input a query related to the PDF content. * **Similarity Search**: This block checks if the user provided a query. If so, it creates a retriever object using the processed PDF content (index) and retrieves the top 3 most similar nodes to the query. * **Preparing Context**:This block prepares the context for compression by concatenating the text of the retrieved nodes. #### Compressing Context with LLUMO ```python theme={null} # Compress context using Llumo compressed_text, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(context, topic=query) if success: print(f"Llumo Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}") print(f"Final tokens: {final_tokens}") ``` * **Compressing Context**: Calls the `compress_with_llumo` function to compress the context using LLUMO API. * **Handling Success**: If compression is successful, prints the compression percentage and token counts. #### Generating Response with Compressed Context ```python theme={null} # Generate response using compressed text llm = OpenAI(model="gpt-3.5-turbo", temperature=0) response = llm.complete(compressed_text + "\n\nQuestion: " + query + "\nAnswer:") print("Answer:") print(response.text) ``` * **LLM Initialization**: Initializes a language model (`ChatOpenAI`) with specified parameters. * This block checks if the compression was successful. If so, it prints the compression statistics and generates a response using the compressed text and the query. The response is generated using an OpenAI model (GPT-3.5-turbo) and is printed. #### Handling Compression Failure ```python theme={null} else: print("Failed to compress the text with Llumo. Using original context.") # Fallback: Use original context if compression fails llm = OpenAI(model="gpt-3.5-turbo", temperature=0) response = llm.complete(context + "\n\nQuestion: " + query + "\nAnswer:") print("Answer:") print(response.text) ``` * This block handles the case where the compression fails. It prints a message indicating the failure and falls back to using the original context to generate the response using the OpenAI model. #### Final Code Integration We have now integrated all the steps to get the final code in the `main` function. This comprehensive function handles PDF uploading, text extraction, text chunking, embedding generation, similarity search, text compression with LLUMO, and generating a response to the user's query using the compressed or original text. ```python theme={null} def main(): print("PDF Query Assistant with Llumo Compression") # Upload PDF from google.colab import files uploaded = files.upload() if uploaded: pdf_file = list(uploaded.keys())[0] # Process the PDF print("Processing PDF...") index = load_and_process_pdf(pdf_file) # User Query Input query = input("Ask any question related to the content of the PDF: ") if query: # Similarity Search retriever = index.as_retriever(similarity_top_k=3) retrieved_nodes = retriever.retrieve(query) # Prepare context for compression context = " ".join([node.node.text for node in retrieved_nodes]) # Compress context using Llumo compressed_text, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(context, topic=query) if success: print(f"Llumo Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}") print(f"Final tokens: {final_tokens}") # Generate response using compressed text llm = OpenAI(model="gpt-3.5-turbo", temperature=0) response = llm.complete(compressed_text + "\n\nQuestion: " + query + "\nAnswer:") print("Answer:") print(response.text) else: print("Failed to compress the text with Llumo. Using original context.") # Fallback: Use original context if compression fails llm = OpenAI(model="gpt-3.5-turbo", temperature=0) response = llm.complete(context + "\n\nQuestion: " + query + "\nAnswer:") print("Answer:") print(response.text) ``` # Step 7 : Running the main function By including this check, we ensure that the main() function is only executed when the script is run directly, providing flexibility and preventing unintended behavior when the script is imported elsewhere. It will ask you to upload a PDF and then when uploaded, it will receive input for the question you want to be answered. ```python theme={null} if __name__ == '__main__': main() ``` # LLUMO Compressor API with OpenAI Source: https://docs.llumo.ai/cost-saving/how-to-docs/llumo-compressor-openai Save cost in OpenAI API calls using LLUMO compressor API # Setting up the environment ## Importing libraries: * os: This module provides a way to use operating system dependent functionality, like reading environment variables. * OpenAI: This is the official OpenAI Python client, used to interact with OpenAI's API. * requests: A popular library for making HTTP requests in Python. * json: Used for parsing JSON data, which is common in API responses. * logging: Provides a flexible framework for generating log messages in Python. * getpass: Allows secure password prompts where the input is not displayed on the screen. ## Setting up logging: * We use `logging.basicConfig()` to configure the logging system. The `level=logging.INFO` argument sets the threshold for logging messages to INFO level and above. * We create a logger object named logger that we'll use throughout our script to log important information and errors. This setup ensures we have all necessary tools to interact with APIs, handle data, and track any issues that might occur during execution. ```python theme={null} !pip install openai import os from openai import OpenAI import requests import json import logging from getpass import getpass # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) print("Libraries imported and logging set up successfully.") ``` # Secure API key handling ## Secure API key input: * We use `getpass()` to prompt the user for their API keys. This function hides the input, making it more secure than using regular input(). * This approach is safer than hardcoding API keys in your script, which could accidentally be shared or exposed. ## Setting environment variables: * We use `os.environ` to set environment variables for both API keys. * Environment variables are a secure way to store sensitive information, as they're not part of your code and are only accessible within the current process. ## Initializing the OpenAI client: * We create an instance of the OpenAI client using the API key we just set. * Using `os.getenv("OPENAI_API_KEY")` retrieves the API key from the environment variables. This method ensures that your API keys are handled securely and are readily available for use in your script. ```python theme={null} # Cell 2: Secure API key handling # Securely input API keys openai_api_key = getpass("Enter your OpenAI API key: ") llumo_api_key = getpass("Enter your Llumo API key: ") # Set environment variables os.environ['OPENAI_API_KEY'] = openai_api_key os.environ['LLUMO_API_KEY'] = llumo_api_key # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) print("API keys securely set and OpenAI client initialized.") ``` # Define Llumo compression function ## Function definition: * We define a function `compress_with_llumo` that takes a text input and an optional topic. ## API setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ## Payload preparation: * We create a payload dictionary with the input text. * If a topic is provided, we add it to the payload. ## API request: * We use `requests.post()` to send a POST request to the Llumo API. `response.raise_for_status()` will raise an exception for HTTP errors. ## Response parsing: * We parse the JSON response and extract the compressed text and token counts. * We calculate the compression percentage. ## Error handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * Unexpected response structure * If an error occurs, we log it and return the original text with failure indicators. ## Return values: * The function returns a tuple containing: * Compressed text (or original if compression failed) * Success boolean * Compression percentage * Initial token count * Final token count This function encapsulates the entire process of interacting with the Llumo API for text compression, including error handling and result processing. ```python theme={null} def compress_with_llumo(text, topic=None): # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') # Define the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" # Set the headers for the API request headers = { "Content-Type": "application/json", # Specify the content type as JSON "Authorization": f"Bearer {LLUMO_API_KEY}" # Authorization header with the API key } # Create the payload for the API request with the provided text payload = {"prompt": text} # If a topic is provided, add it to the payload if topic: payload["topic"] = topic try: # Make a POST request to the Llumo API with the payload and headers response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) # Raise an exception if the request was unsuccessful response.raise_for_status() # Parse the JSON response from the API result = response.json() # Extract the 'data' field from the JSON response data = result['data']['data'] # Parse the JSON string in the 'data' field data_content = json.loads(data) # Get the compressed text from the parsed JSON compressed_text = data_content.get('compressedPrompt', text) # Get the initial and final token counts from the parsed JSON initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) # Calculate the compression percentage if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 # Return the compressed text, success flag, compression percentage, and token counts return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: # Print an error message if an exception occurs print(f"Error compressing text: {str(e)}") # Return the original text, failure flag, and zeroed metrics return text, False, 0, 0, 0 ``` # Define example prompt and test without compression ## Defining the prompt: * We create a detailed prompt about photosynthesis. This serves as our example text for compression. ## Testing without compression: * We use the OpenAI client to send a request to the GPT-3.5-turbo model. * The messages parameter follows the chat format: * A system message sets the AI's role. * A user message contains our prompt. ## Displaying results: * We print the AI's response to the prompt. * We also print the total number of tokens used, which is important for understanding API usage and costs. This cell demonstrates how the API would typically be used without any compression, providing a baseline for comparison. ```python theme={null} # Cell 4: Define example prompt and test without compression # Example prompt prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ topic= "what is the moral of story" print("Without Llumo Compression:") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}\n") ``` # Test with Llumo compression ## Applying Llumo compression: * We call compress\_with\_llumo() with our example prompt. * The function returns multiple values, which we unpack into separate variables. ## Checking compression success: * We use an if statement to check if compression was successful. * If successful, we print compression statistics: percentage, initial and final token counts. ## Using the compressed prompt: * If compression succeeded, we use the compressed prompt in our API call to GPT-3.5-turbo. * We use the same message structure as before, but with the compressed prompt. ## Displaying results: * We print the AI's response to the compressed prompt. * We print the number of tokens used with the compressed prompt. ## Handling compression failure: * If compression fails, we print a message indicating this. * In a real application, you might want to fall back to using the original prompt in this case. This cell demonstrates the full process of compressing a prompt with Llumo and using it with the OpenAI API. By comparing the results and token usage with the previous cell, you can see the potential benefits of using Llumo compression in terms of token efficiency and cost savings. ```python theme={null} # Cell 5: Test with Llumo compression print("With Llumo Compression:") compressed_prompt, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(prompt, topic) if success: print(f"Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}, Final tokens: {final_tokens}") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": compressed_prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}") else: print("Compression failed. Using original prompt.") # Use the original prompt if compression fails ``` # LLUMO Compressor API with Google Vertex Source: https://docs.llumo.ai/cost-saving/how-to-docs/llumo-compressor-vertex Save cost in Google Vertex pipeline using LLUMO compressor API # Installing Necessary Libraries This cell installs or upgrades the necessary Python packages for the project: * google-cloud-aiplatform: The Google Cloud AI Platform SDK, used for interacting with Vertex AI. * requests: A popular HTTP library for making API calls (will be used for the Llumo API). * nltk: Natural Language Toolkit, a leading platform for building Python programs to work with human language data. * beautifulsoup4: A library for pulling data out of HTML and XML files, useful for web scraping. The ! at the beginning allows running shell commands in Jupyter notebooks or Google Colab. ```python theme={null} !pip install --upgrade google-cloud-aiplatform requests nltk beautifulsoup4 ``` # Setting Up VertexAI This cell mounts your Google Drive to the Colab environment: * It imports the `os` module for operating system operations and the drive module from `google.colab`. * `drive.mount()` attaches your Google Drive to the '/content/drive' directory in the Colab environment. * `force_remount=True` ensures that the drive is remounted even if it was previously mounted, which can help resolve connection issues. ```python theme={null} import os from google.colab import drive drive.mount('/content/drive',force_remount=True) ``` Now we will sets up the Google Cloud credentials: * It sets the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to your Google Cloud service account key file. * The file path suggests that your credentials JSON file is stored in your Google Drive under the 'MyDrive/vertex/' directory. * This step is crucial for authenticating your script with Google Cloud services. ```python theme={null} os.environ['GOOGLE_APPLICATION_CREDENTIALS']='/content/drive/MyDrive/vertex/googleCred.json' ``` # Importing Libraries This cell imports all necessary Python modules: * `os`: For operating system operations and environment variables. * `requests`: For making HTTP requests (will be used for Llumo API calls). * `json`: For JSON parsing and manipulation. * `logging`: For setting up logging in the script. * `getpass`: For securely inputting passwords or API keys. * `aiplatform`: The main module for interacting with Vertex AI. * `TextGenerationModel`: Specific class for text generation tasks in Vertex AI. ```python theme={null} import os import requests import json import logging from getpass import getpass from google.cloud import aiplatform from vertexai.language_models import TextGenerationModel ``` # Setting up Basic Logging This cell sets up logging for the script: * `logging.basicConfig()` configures the logging system with INFO level, meaning it will capture all info, warning, and error messages. * `logger = logging.getLogger(__name__)` creates a logger object.` __name__` is a special Python variable that gets set to the module's name when the module is executed. ```python theme={null} logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` # Setting up Llumo API This cell securely handles the Llumo API key: * It uses `getpass()` to prompt for the Llumo API key without displaying it on the screen as it's typed. * The API key is then stored as an environment variable named 'LLUMO\_API\_KEY'. * This approach keeps the API key secure by not hardcoding it in the script. ```python theme={null} llumo_api_key = getpass("Enter your Llumo API key: ") os.environ['LLUMO_API_KEY'] = llumo_api_key ``` # Define Llumo compression function ## Function definition: * We define a function `compress_with_llumo` that takes a text input and an optional topic. ## API setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ## Payload preparation: * We create a payload dictionary with the input text. * If a topic is provided, we add it to the payload. ## API request: * We use `requests.post()` to send a POST request to the Llumo API. `response.raise_for_status()` will raise an exception for HTTP errors. ## Response parsing: * We parse the JSON response and extract the compressed text and token counts. * We calculate the compression percentage. ## Error handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * Unexpected response structure * If an error occurs, we log it and return the original text with failure indicators. ## Return values: * The function returns a tuple containing: * Compressed text (or original if compression failed) * Success boolean * Compression percentage * Initial token count * Final token count This function encapsulates the entire process of interacting with the Llumo API for text compression, including error handling and result processing. ```python theme={null} def compress_with_llumo(text, topic=None): # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') # Define the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" # Set the headers for the API request headers = { "Content-Type": "application/json", # Specify the content type as JSON "Authorization": f"Bearer {LLUMO_API_KEY}" # Authorization header with the API key } # Create the payload for the API request with the provided text payload = {"prompt": text} # If a topic is provided, add it to the payload if topic: payload["topic"] = topic try: # Make a POST request to the Llumo API with the payload and headers response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) # Raise an exception if the request was unsuccessful response.raise_for_status() # Parse the JSON response from the API result = response.json() # Extract the 'data' field from the JSON response data = result['data']['data'] # Parse the JSON string in the 'data' field data_content = json.loads(data) # Get the compressed text from the parsed JSON compressed_text = data_content.get('compressedPrompt', text) # Get the initial and final token counts from the parsed JSON initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) # Calculate the compression percentage if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 # Return the compressed text, success flag, compression percentage, and token counts return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: # Print an error message if an exception occurs print(f"Error compressing text: {str(e)}") # Return the original text, failure flag, and zeroed metrics return text, False, 0, 0, 0 ``` # Define example prompt and test without compression ## Defining the prompt: * We create a detailed prompt about photosynthesis. This serves as our example text for compression. ## Testing without compression: * We use the VertexAI client to send a request to the text-bison model. * The messages parameter follows the chat format: * A system message sets the AI's role. * A user message contains our prompt. ## Displaying results: * We print the AI's response to the prompt. * Vertex AI doesn't provide any token usage. So, it's not possible to print token usage for checking. This cell demonstrates how the API would typically be used without any compression, providing a baseline for comparison. ```python theme={null} prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ topic = "what is the moral of story" print("Without Llumo Compression:") model = TextGenerationModel.from_pretrained("text-bison") parameters = { "max_output_tokens": 1024, "temperature": 0.2, "top_p": 0.8, "top_k": 40 } response = model.predict(prompt, **parameters) print(response.text) ``` # Test with Llumo compression ## Applying Llumo compression: * We call compress\_with\_llumo() with our example prompt. * The function returns multiple values, which we unpack into separate variables. ## Checking compression success: * We use an if statement to check if compression was successful. * If successful, we print compression statistics: percentage, initial and final token counts. ## Using the compressed prompt: * If compression succeeded, we use the compressed prompt in our API call to vertexAI. * We use the same message structure as before, but with the compressed prompt. ## Displaying results: * We print the AI's response to the compressed prompt. * We print the number of tokens used with the compressed prompt. ## Handling compression failure: * If compression fails, we print a message indicating this. * In a real application, you might want to fall back to using the original prompt in this case. This cell demonstrates the full process of compressing a prompt with Llumo and using it with the Vertex API. By comparing the results and token usage with the previous cell, you can see the potential benefits of using Llumo compression in terms of token efficiency and cost savings. ```python theme={null} print("\nWith Llumo Compression:") compressed_prompt, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(prompt, topic) if success: print(f"Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}, Final tokens: {final_tokens}") response = model.predict(compressed_prompt, **parameters) print(response.text) else: print("Compression failed. Using original prompt.") ``` # Setup prompt compression API Source: https://docs.llumo.ai/cost-saving/setup/api Start cutting AI cost in just 2 minutes ## Getting Started with Prompt Compression API This guide provides step-by-step instructions on setting up prompt compression API, that compresses input prompts before passing it to LLMs, helping you save cost and reduce inference speed. ### 1. Open compressor setup modal The "Compressor setup modal" provides your essential connection details: API endpoint, key, and sample request bodies. This ensures a smooth setup for compressing your prompts. If you've already done demo call and got the access to the LLUMO app, this step is complete. If you are a new user for [LLUMO AI](https://www.llumo.ai), please refer to [Create Account](https://docs.llumo.ai/setup-llumo/create-account) and [Activate your account](https://docs.llumo.ai/setup-llumo/activate-account) After you have access and you login to LLUMO for the first time, you will see a modal asking you to select the journey - Cost saving and Evaluation. You need to select the Cost Saving option. If you have already selected the Evaluation option, no worries. If you see the left navigation bar, you will see the compressor option. Then you can see a banner on the top of the page, asking you to set up. Click on “Setup Now” Now, you can see the setup modal for the compressor. If you are not able to see the below modal, [contact our support team](mailto:product@llumo.ai). If you close the modal window, you can access it again by clicking “Setup Now” CTA on the banner at the top of the page. ### 2. Access your API keys The API keys equips you with the credentials needed to connect with Prompt Compression API. This unlocks the power to compress your prompts and experience cost savings. We suggest you to keep your API keys very safely. If you experience any misuse, [contact our support team](mailto:product@llumo.ai). The setup modal provides an overview of Compressor and a "Connect Now" CTA. Click on "Connect Now" and it will open the API connection detail modal * API endpoint: The URL you will use to send requests to the Compressor API. * API key: Your unique API key, which is required for authentication. You will be given one API key by default. But, if you want to create multiple API keys, refer to [managing your keys](https://docs.llumo.ai). Examples of codes containing request bodies in different languages is provided, that you can use to send a request to the Compressor API. Copy the sample code block and paste into editor of your choice. Below is an example of sample code block in python. ```python compressPrompt.py theme={null} import requests url = "https://app.llumo.ai/api/compress" payload = {"prompt": ""} headers = { "Content-Type": "application/json" "Authorization": "Bearer " } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) ``` The request body includes the following important parameters: * prompt: (Mandatory) The text prompt you want to compress. * topic: (Optional) The topic of the prompt. We highly recommend providing a topic for better compression results. Here is an example of these two parameters. ```json theme={null} "prompt": "In a forgotten corner of the universe, a nomadic tribe journeys across a desolate wasteland on colossal, bio-engineered sandworms. These colossal creatures, revered as both gods and transportation, are on the verge of extinction due to a mysterious blight. A young rider, ostracized for their curiosity about the world beyond the sand, discovers a hidden cache of ancient technology. This technology offers a glimmer of hope for saving the sandworms, but it also unlocks forbidden knowledge that threatens to shatter the tribe's long-held beliefs. Torn between tradition and the promise of progress, the young rider must embark on a perilous quest to uncover the truth about the blight and the tribe's origins. Their journey will lead them to face colossal sand creatures, navigate treacherous landscapes, and confront a powerful ruling class determined to maintain the status quo. Will they succeed in saving the sandworms and their people, or will they succumb to the dangers that lie hidden beneath the sands? Write a story about their fight for survival and the burden of knowledge." "topic": "What are the potential consequences of the young rider's choice between tradition and progress in saving the sandworms?" ``` For fine-grained control over logging and cost visualization, explore the optional parameters within the request body. These parameters allow you to tailor metrics to your specific needs and visualize cost breakdowns on the dashboard. For a detailed breakdown on the API request and response, please refer to the [API reference page](https://docs.llumo.ai/cost-saving/api-reference/compress-prompt-api). ### 3. Send first request to Prompt Compression API Once you have your request setup for a sample body, you can send a request to the Compressor API to compress your own prompts. 1. Open your directory where LLM project reside in editor of your choice. 2. Edit the sample code snippet you copied from LLUMO setup modal. 3. Replace the placeholder values for prompt and topic with your specific prompt and topic. 4. Include your API key in the header of the request. 5. Run the code snippet. You can find detailed instructions on setting up the API in your code on the dedicated [guide page](https://docs.llumo.ai/cost-saving/how-to-docs/compress-first-prompt). For a more interactive experience, we recommend using API testing tools like Postman or Thunder Client. Below is the step-by-step detailed video explaing the complete process. API testing tools After sending the request, you can view the logs and metrics generated on the dashboard to see how the compression process performed. This information can help you optimize your requests for better results. ### All Done! Congrats! You've set up your LLUMO's Prompt Compression API and it has started saving your cost with each inference! If you encounter any difficulties while setting up, please refer to the troubleshooting section of the guide or, contact our support team at [connect@llumo.ai](mailto:connect@llumo.ai). ``` ``` # null Source: https://docs.llumo.ai/developer-tools/sample-projects/compression-openai # null Source: https://docs.llumo.ai/developer-tools/setup-llumo/setup-cost-saving/api # null Source: https://docs.llumo.ai/developer-tools/setup-llumo/setup-evaluation/api # null Source: https://docs.llumo.ai/developer-tools/troubleshoot/prompt-compression-api # Experiment Source: https://docs.llumo.ai/experiment LLUMO AI Experiment is a purpose-built platform designed to systematically test, evaluate, and debug at 10X faster rate. It enables AI teams to move beyond intuition-based development by providing use case based Evals, various AI models and fine-tuning options, helping businesses to build AI systems at a much faster rate. *** ## Why You Need LLUMO AI Experiment If your AI development process faces challenges like: * **Unreliable Model Performance:** Struggling to measure accuracy, relevance, or hallucination rates effectively. * **Slow Experimentation:** Testing models manually, leading to bottlenecks in iteration and deployment. * **Lack of Use Case-Specific Evaluations:** Generic benchmarks that don’t reflect your business needs. * **High Debugging Effort:** No structured way to trace and fix model failures at scale. *** ## Core Features of LLUMO AI Experiment * **Test Multiple AI Models in One View:** Evaluate a range of AI models and compare them side by side, all from a single interface. * **Use Case-Specific Evals:** Assess the performance of your AI workflows using evaluations tailored to your specific use case. * **Cutting-Edge KPIs for Conversational AI:** Measure outputs against various KPIs like RAGAs, hallucinations, and other in-house metrics. * **One-Click Deployment:** Deploy with ease using a simple one-click setup that works with your software or platform, and integrate seamlessly with other tools. *** ## Quick Start - Related Documentation The Quick Start section is designed to help you get up and running with LLUMO AI’s evaluation tools in the fastest and most efficient way. Whether you're setting up for the first time or integrating evaluations into production, these guides provide step-by-step instructions tailored to different use cases. LLUMO AI’s Experiment Playground allows you to tailor the evaluation process to meet your unique requirements. Whether you’re analyzing customer service data, academic content, or any other dataset, this powerful tool enables users to assess AI-generated outputs against tailored metrics and criteria that align with their specific needs and objectives. Unlike pre-defined evaluation methods, which may not fully capture the nuances of different use cases, LLUMO AI’s evaluation allows users to define their own parameters, ensuring the evaluation process is both relevant and effective. This guide will walk you through the steps of using Experiment playground to perform a detailed and personalized evaluation of your datasets. *** ### Step-by-Step Instructions: Evaluating using Custom Evaluation *** #### Step 1: Upload Your Dataset **Option 1: Upload File** * Log into LLUMO AI Platform and navigate to the "Eval LM" section. * **Upload Your Dataset:** Click "Upload File" and select your dataset. Supported file formats include CSV, JSON, and Excel. * **Review Your Data:** A preview of the uploaded data will appear. Check that the structure and content are correct before moving forward. **Option 2: Upload via API** * **Enter URL:** You can enter either a private or public URL that returns data in JSON format. * **Enter Headers:** In the request, include any necessary headers. Typically, headers are used to pass authentication keys (like API keys) or specify content types. * **Enter JSON Payload:** The JSON payload is where you attach the data to be sent, including any filters or data for processing. This can be used to send files, parameters, or other information. * **Enter JSON Path:** After the request is processed, you may need to extract specific data from the API response. Use a JSON path to locate and retrieve the relevant part of the response. **Option 3: Import from Hugging Face** * **Open Hugging Face:** Go to [Huggingface Datasets](https://huggingface.co/datasets) * **Copy the Dataset Name:** Find the dataset you want to use and copy its name. * **Open LLUMO:** Go to [Experiments page on LLUMO AI](https://app.llumo.ai/evallm) * **Upload Dataset:** Click on Upload and select Import from Hugging Face * **Paste the Dataset Name:** Paste the name of the dataset you copied from Hugging Face * **Select Subset and Tree:** Choose the appropriate subset and tree for your dataset * **Import the Data:** Click Run Dataset to bring the dataset into LLUMO * **Perform Evaluation:** Once the dataset is imported, you can start the evaluation process. Hugging Face is a platform for sharing and accessing machine learning models and datasets.\ A dataset is a collection of data used for training or evaluation.\ A subset refers to a specific portion of the dataset.\ A tree may refer to a hierarchical structure within the dataset or model. **Option 4: Manually**\ Here, you can create a custom dataset by starting with a blank dataset. *** #### Step 2: Click on the Write Prompt card in the command centre. Here, you can follow these steps: * **Column Name:** Enter the column name. * **Write Prompt:** Enter your prompt by providing the desired query or instruction to guide the AI model in generating the results you expect. * **Create a Smart Prompt (optional):** Smart Prompt refines your written prompt, making it more specific and detailed to generate more accurate and focused results. * **Select Your LLM Provider:** Choose your preferred provider from the drop-down list (LLUMO supports multiple LLM providers). * **Choose the Model:** Select the specific AI model you want to use for generating the results, based on your needs. * **Adjust Parameters:** Fine-tune the model’s parameters as per your requirements. *** #### Step 3: Click on the “Create and Run all Columns” button. * Allow the system to complete processing your prompts. * Once the outputs are ready, proceed to the evaluation step. *** #### Step 4: Evaluation * Click on the “Evaluate” card in the command center. * Now, enter the column name and select the “KPI” as per your use case. **Note:** You can customize your evaluations to align with your unique use case and industry requirements. * Select your Evaluation model from the drop-down list. * Select the prompt you want to evaluate. * “Pass & Fail” criteria **Set Rule for KPIs:** Each KPI allows you to set a specific threshold to define a “pass” or “fail.”\ **Example for confidence:** If the confidence score is more than 50, it passes. *** #### Step 5: Run the Evaluation * **Start the Evaluation:** After confirming your settings, click the “Create and Run All Columns” button to begin processing your evaluation. * **Review Evaluation Results:** The evaluation will return detailed results, including Pass/Fail status for each KPI along with the scores. *** **Tailor evaluation metrics and configurations to suit your specific use case** *** This Quick Start guide ensures you can navigate LLUMO AI’s evaluation framework effortlessly, saving time and enhancing the quality of your LLM deployments. *** ## API Integration Integrating LLUMO AI’s evaluation API into your codebase allows for seamless automation of LLM performance tracking, enabling large-scale and efficient evaluations. Follow these steps to get started: * **Set Up API Access** * Obtain your API key from the LLUMO AI dashboard. * Install required dependencies for API communication. * Configure authentication for secure API access. * **Read the Full API Setup Guide** * **Evaluate LLMs Using API** * **For OpenAI models:** Run evaluations on OpenAI’s GPT-based models using LLUMO AI’s API. * Evaluate OpenAI Models * **For Vertex AI models:** Perform evaluations on Google Cloud’s Vertex AI models. * Evaluate Vertex AI Models * **Make Your First API Call** * Authenticate your request using your API key. * Send evaluation requests with input prompts and expected responses. * Define custom evaluation metrics to measure LLM output quality. * Integrate API into Your Codebase * **Create Evaluation Analytics API** * Generate detailed analytics for LLM evaluation runs. * Monitor performance trends and optimize responses over time. * Create Eval Analytics API This guide ensures a smooth and efficient integration process, allowing you to optimize model performance effortlessly. *** ## FAQ **Q. What is LLUMO AI Experiment?**\ LLUMO AI Experiment is a powerful platform designed to help teams test, evaluate, and optimize their LLM applications efficiently. It provides end-to-end tracking, customizable evaluation metrics, and structured experimentation workflows. **Q. How does LLUMO AI Experiment help improve LLM performance?**\ It allows users to: * Run structured experiments to compare model outputs. * Identify failure points with detailed tracing. * Leverage automated and custom evaluation metrics. * Optimize configurations based on real-time insights. **Q. What evaluation metrics are available in LLUMO AI Experiment?**\ LLUMO AI offers: * **Prebuilt Metrics:** Guardrail metrics for accuracy, coherence, relevance, and hallucination detection. * **Custom Metrics:** Define your own KPIs based on your specific use case. **Q. How do I integrate LLUMO AI’s API into my workflow?** * Obtain an API key and configure authentication. * Send evaluation requests with input prompts and expected outputs. * Automate and scale evaluations using scheduled API calls.\ **Read the Full API Integration Guide** **Q. Can I evaluate bulk datasets with LLUMO AI?**\ Yes! LLUMO AI allows you to evaluate large datasets using multiple key metrics to assess LLM performance at scale.\ **Guide to Bulk Evaluation** **Q. Does LLUMO AI support OpenAI and Vertex AI models?**\ Yes, LLUMO AI supports evaluation for: * **OpenAI models** – Evaluate OpenAI Models * **Vertex AI models** – Evaluate Vertex AI Models **Q. How can I track my experiments over time?**\ LLUMO AI Experiment includes an Experiment Management feature that logs all test runs, allowing you to compare different configurations and monitor long-term performance. **Q. How do I create analytics for my evaluation runs?**\ LLUMO AI provides an Evaluation Analytics API that generates performance insights and trends.\ **Create Eval Analytics API** # Getting started with LLUMO AI Source: https://docs.llumo.ai/getting-started-with-llumo LLUMO AI is designed to empower AI teams by making the development of Large Language Models (LLMs) faster, more reliable, precise, and cost-effective. It’s a one-stop solution that simplifies working with LLMs, allowing you to focus on building great AI models without the hassle or high costs. This guide will walk you through how to get started and make the most of LLUMO AI to bring your AI projects to life effortlessly. *** ## Why Choose LLUMO AI? ### Key Features * **Data Upload Made Easy**: Test with your data directly, ensuring tailored results. * **Advanced Evaluation Tools**: Use cutting-edge techniques like RAGAs and LLUMO Eval LM for one-click evaluations. * **Customizable KPIs**: Tailor over 50 metrics to measure what matters most to your project. * **Actionable Insights**: Real-time data to refine your models for speed, accuracy, and cost-efficiency. * **Multi-Industry Applications**: From legal research to customer service, LLUMO AI adapts to any domain. *** ## Getting Started with LLUMO AI ### Step 1: Create an Account * **Action**: Sign up for a LLUMO AI account \[here]. * **Why**: Gain access to the full range of features for testing, optimizing, and improving your AI models. ### Step 2: Upload Your Data * **Action**: Upload data in formats like CSV, JSON, or plain text. * **Why**: Tailor results specific to your needs by securely uploading your data. ### Step 3: Experiment with Prompts * **Action**: Use the Playground to create and test prompts for your project. * **Why**: Crafting the right prompts ensures accurate and relevant AI responses. ### Step 4: Evaluate Performance * **Action**: Compare prompts and results using tools like RAGAs and LLUMO Eval LM. * **Why**: Quickly identify what works best for smarter decision-making. ### Step 5: Customize KPIs * **Action**: Set metrics like accuracy, speed, or relevance to align with your goals. * **Why**: Tailored KPIs give you more control over your project’s success. ### Step 6: Iterate and Optimize * **Action**: Refine prompts and workflows using insights from LLUMO AI. * **Why**: Continuous improvements lead to better results and a smoother workflow. ### Step 7: API Integration * **Action**: Use the Connect API section to integrate LLUMO AI with your models. * **Why**: Automate tasks and streamline workflows efficiently. *** ## Tools and Techniques ### LLUMO AI Playground * **Problem**: Testing and improving AI models can be time-consuming. * **Solution**: A one-stop shop to upload data, test prompts, and evaluate performance. ### Customizable Evaluation Metrics * **Problem**: Standard metrics may not suit your needs. * **Solution**: Tailor KPIs to measure what matters for your project. ### Advanced Evaluation Tools * **Problem**: Evaluating AI performance without the right tools is difficult. * **Solution**: Tools like RAGAs and LLUMO Eval LM provide clear insights for improvements. ### Prompt Compression * **Problem**: Running LLMs with lengthy prompts is expensive. * **Solution**: Compress prompts to save costs while maintaining performance. ### Real-Time Insights * **Problem**: Tracking AI performance in real-time can be challenging. * **Solution**: View and refine performance instantly with LLUMO AI’s real-time insights. *** ## Basic Definitions for LLUMO AI ### Playground A hands-on space to upload data, test ideas, and refine solutions. ### Knowledge Base A central hub of resources for guidance and support. ### User Question The query provided by a user for AI to process. ### Prompt Input instructions guiding the AI’s response. ### Evaluate Testing how well a prompt or model performs. ### Evaluation Metrics Criteria to measure the performance of your AI model. ### KPI (Key Performance Indicator) Benchmarks to track the success of your AI workflows. ### Variables Dynamic placeholders used in prompts for flexibility. ### Write Prompt Crafting input instructions for accurate AI responses. ### Evaluation Reviewing AI’s output against required standards. ### Custom Evaluation Tailored criteria for performance testing. ### Ground Truth The benchmark or correct answer for comparison. ### API Calls Requests sent to LLUMO AI for specific tasks. ### Classification Categorizing data into predefined groups. ### Extract a JSON Key Pulling specific data points from a JSON file. ### Execute Custom Code Running scripts or code within the LLUMO AI platform. *** ## FAQs ### What data formats can I upload to LLUMO AI? You can upload datasets in formats like CSV, JSON, and plain text. ### Is LLUMO AI secure? Absolutely! LLUMO AI adheres to strict data privacy and security protocols. ### Can I integrate LLUMO AI with other tools? Yes, LLUMO AI supports integrations with popular tools and platforms. ### How can I get support? Our support team is available 24/7 # null Source: https://docs.llumo.ai/how-to-docs/annotate-human-feedback/production # null Source: https://docs.llumo.ai/how-to-docs/annotate-human-feedback/testing # Guide to Prompt Compress with LLUMO AI Source: https://docs.llumo.ai/how-to-docs/compress-prompts/compress-prompt-doc Start cutting AI cost in just 2 minutes The Prompt Compression Tool in LLUMO AI is designed to optimize your prompts for better efficiency and cost-effectiveness. By reducing the length of the input while retaining essential meaning and context, the tool helps lower costs and speeds up processing without sacrificing the output quality. Below, we walk through the detailed steps for using prompt compression effectively, with a focus on sales transcripts as an example. *** ## Step 1: Access the Compressor Tool * **Log in to LLUMO AI**: Start by logging into your LLUMO AI dashboard using your credentials. * **Navigate to the Compressor Tab**: Once logged in, you can go to the compress screen using two different ways: 1. By clicking **Save on AI Cost** 2. Click the **Compressor** tab on the sidebar menu to access the tool. ## Step 2: Prepare Your Input Data Here, we are using a sales transcript as an example of input data, but you can apply this tool to any type of data, such as summarization tasks or document Q\&A. Before you start using the tool, make sure you have all necessary variables in place. In this case, prepare your sales transcript, as it will serve as the input data for the compression process. ### Here's how: * **Sales Transcript**: This is the conversation you want to analyze and compress for AI processing. It can be a real-world sales call, a meeting transcript, or any type of dialogue that you need summarized or analyzed. ## Step 3: Configure the Prompt Once you have the sales transcript ready, configure your prompt: 1. **Upload the Transcript**: Upload the full sales transcript into the Transcript in the Compressor tool. This is where the AI model will retrieve the content for analysis. 2. **Enter the Query**: The Query field is where you specify what you want the AI to do with the transcript. The query could be any task such as summarizing, extracting key insights, or answering a question based on the transcript. **Example Query**:\ `"Summarize the key pain points and solutions discussed in this sales transcript."` 3. **Create Additional Variables**: If needed, you can define additional variables to make the task more specific. 4. **Formulate the Prompt**: Structure the full prompt, which combines the transcript and the query, like so:\ `Summarize the key pain points and solutions discussed in this sales transcript: {{Transcript}}, based on the query {{Query}}.` 5. **Select the AI Model Version**: Choose the version of the AI model you’d like to use for processing. For example, GPT-4 can be selected for high-quality responses. ## Step 4: Run Compression After you’ve configured your input, it’s time to run the compression: 1. **Click Compress & Run**: When you’re ready, click the **Compress & Run** button to start the compression process. 2. **Two Outputs**: * **Augmented Output**: This is the AI’s response, based on the compressed prompt. The output will summarize the sales transcript according to your query. * **Comparison Metrics**: The tool will also show comparison details like: * **Token Count**: The number of tokens used in both the original and compressed prompts. * **Cost**: The processing cost based on token count. * **Confidence**: The AI’s confidence in its response. * **Clarity**: How clear and easy to understand the AI’s response is. * **Output Similarity**: How similar the compressed and original outputs are. ## Step 5: Evaluate Results Once the compression is complete, evaluate the results by comparing the original and compressed outputs: * **Before Compression**: * Prompt: `"You are a helpful assistant. Use the given sales transcript below to summarize key pain points and solutions."` * Tokens: 1790 * Cost: \$0.0056 * **After Compression**: * Prompt: `"Summarize pain points and solutions from the transcript."` * Tokens: 635 * Cost: \$0.0003 * **Comparison**: * **Token Savings**: \~64.5% reduction in token usage. * **Output Similarity**: 98.17% similarity between the original and compressed output. * **Confidence and Clarity**: After compression, the AI's confidence and clarity score improved to above 80%. ## Step 6: Iterative Improvement If the results need refinement, you can adjust the prompt to ensure you maintain clarity while reducing token usage: * **Refine the Prompt**: Check the compressed prompt and modify it to ensure that no crucial details are omitted. * **Ensure Context is Preserved**: The key to effective prompt compression is maintaining essential context. Ensure the AI retains all relevant information in its output. ## Step 7: Applying Compression to Sales Transcripts Here’s how you can use prompt compression with a sales transcript: **Example Query**:\ `"Summarize how the sales representative addresses the prospect’s pain points and proposes solutions."` * **Before Compression**:\ Prompt: `"You are a helpful assistant. Use the following sales transcript to summarize the key pain points discussed and solutions offered."` * **Compressed Prompt**:\ `"Summarize pain points and solutions from the transcript."` **Augmented Output Example**:\ `"The prospect’s main pain point was the inability to track shipments in real-time, causing delays and customer dissatisfaction. The sales representative proposed a platform with GPS integration and automated alerts, addressing the concern by offering real-time tracking and ensuring timely delivery updates."` *** ## Frequently Asked Questions (FAQ) **Q: What is prompt compression?**\ A: Prompt compression is the process of reducing the length of the input while maintaining its essential meaning. This helps in reducing token usage, cutting down operational costs, and speeding up AI processing. **Q: Why should I use prompt compression?**\ A: By using prompt compression, you can significantly reduce the number of tokens required for processing, lowering costs and improving efficiency. It ensures that your tasks are processed faster without losing output quality. **Q: Does prompt compression affect the quality of the output?**\ A: No, the goal of prompt compression is to reduce token usage while maintaining the integrity and quality of the output. The compressed prompt still provides the model with enough context to produce accurate, high-quality responses. **Q: Can I use prompt compression for other types of data besides sales transcripts?**\ A: Yes, prompt compression can be used for various types of data, including legal documents, meeting notes, case studies, and more. It’s particularly useful when you need to process long-form text efficiently. **Q: How do I know if my prompt compression is effective?**\ A: After running the compression, LLUMO AI provides comparison metrics such as token count, output similarity, and confidence. You can assess how well the compression has worked by looking at these metrics and ensuring that output quality remains high. **Q: Is it possible to reverse or undo compression?**\ A: While the compression process is not reversible, you can always refine the compressed prompt to improve its clarity or make adjustments based on the AI’s output. This ensures the model retains important context without unnecessary verbosity. **Q: Can I apply compression to legal documents or case studies?**\ A: Absolutely. The prompt compression tool works well for various professional tasks, including legal tech use cases like summarizing legal cases, drafting contracts, and processing client queries. # Add LLUMO Compressor API to code and deploy Source: https://docs.llumo.ai/how-to-docs/compress-prompts/production Save cost in LLM calls with OpenAI using LLUMO compressor API # Setting up the environment ## Importing libraries: * os: This module provides a way to use operating system dependent functionality, like reading environment variables. * OpenAI: This is the official OpenAI Python client, used to interact with OpenAI's API. * requests: A popular library for making HTTP requests in Python. * json: Used for parsing JSON data, which is common in API responses. * logging: Provides a flexible framework for generating log messages in Python. * getpass: Allows secure password prompts where the input is not displayed on the screen. ## Setting up logging: * We use `logging.basicConfig()` to configure the logging system. The `level=logging.INFO` argument sets the threshold for logging messages to INFO level and above. * We create a logger object named logger that we'll use throughout our script to log important information and errors. This setup ensures we have all necessary tools to interact with APIs, handle data, and track any issues that might occur during execution. ```python theme={null} !pip install openai import os from openai import OpenAI import requests import json import logging from getpass import getpass # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) print("Libraries imported and logging set up successfully.") ``` # Secure API key handling ## Secure API key input: * We use `getpass()` to prompt the user for their API keys. This function hides the input, making it more secure than using regular input(). * This approach is safer than hardcoding API keys in your script, which could accidentally be shared or exposed. ## Setting environment variables: * We use `os.environ` to set environment variables for both API keys. * Environment variables are a secure way to store sensitive information, as they're not part of your code and are only accessible within the current process. ## Initializing the OpenAI client: * We create an instance of the OpenAI client using the API key we just set. * Using `os.getenv("OPENAI_API_KEY")` retrieves the API key from the environment variables. This method ensures that your API keys are handled securely and are readily available for use in your script. ```python theme={null} # Cell 2: Secure API key handling # Securely input API keys openai_api_key = getpass("Enter your OpenAI API key: ") llumo_api_key = getpass("Enter your Llumo API key: ") # Set environment variables os.environ['OPENAI_API_KEY'] = openai_api_key os.environ['LLUMO_API_KEY'] = llumo_api_key # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) print("API keys securely set and OpenAI client initialized.") ``` # Define Llumo compression function ## Function definition: * We define a function `compress_with_llumo` that takes a text input and an optional topic. ## API setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ## Payload preparation: * We create a payload dictionary with the input text. * If a topic is provided, we add it to the payload. ## API request: * We use `requests.post()` to send a POST request to the Llumo API. `response.raise_for_status()` will raise an exception for HTTP errors. ## Response parsing: * We parse the JSON response and extract the compressed text and token counts. * We calculate the compression percentage. ## Error handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * Unexpected response structure * If an error occurs, we log it and return the original text with failure indicators. ## Return values: * The function returns a tuple containing: * Compressed text (or original if compression failed) * Success boolean * Compression percentage * Initial token count * Final token count This function encapsulates the entire process of interacting with the Llumo API for text compression, including error handling and result processing. ```python theme={null} def compress_with_llumo(text, topic=None): # Retrieve the Llumo API key from environment variables LLUMO_API_KEY = os.getenv('LLUMO_API_KEY') # Define the Llumo API endpoint for text compression LLUMO_ENDPOINT = "https://app.llumo.ai/api/compress" # Set the headers for the API request headers = { "Content-Type": "application/json", # Specify the content type as JSON "Authorization": f"Bearer {LLUMO_API_KEY}" # Authorization header with the API key } # Create the payload for the API request with the provided text payload = {"prompt": text} # If a topic is provided, add it to the payload if topic: payload["topic"] = topic try: # Make a POST request to the Llumo API with the payload and headers response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) # Raise an exception if the request was unsuccessful response.raise_for_status() # Parse the JSON response from the API result = response.json() # Extract the 'data' field from the JSON response data = result['data']['data'] # Parse the JSON string in the 'data' field data_content = json.loads(data) # Get the compressed text from the parsed JSON compressed_text = data_content.get('compressedPrompt', text) # Get the initial and final token counts from the parsed JSON initial_tokens = data_content.get('initialTokens', 0) final_tokens = data_content.get('finalTokens', 0) # Calculate the compression percentage if initial_tokens and final_tokens: compression_percentage = ((initial_tokens - final_tokens) / initial_tokens) * 100 else: compression_percentage = 0 # Return the compressed text, success flag, compression percentage, and token counts return compressed_text, True, compression_percentage, initial_tokens, final_tokens except Exception as e: # Print an error message if an exception occurs print(f"Error compressing text: {str(e)}") # Return the original text, failure flag, and zeroed metrics return text, False, 0, 0, 0 ``` # Define example prompt and test without compression ## Defining the prompt: * We create a detailed prompt about photosynthesis. This serves as our example text for compression. ## Testing without compression: * We use the OpenAI client to send a request to the GPT-3.5-turbo model. * The messages parameter follows the chat format: * A system message sets the AI's role. * A user message contains our prompt. ## Displaying results: * We print the AI's response to the prompt. * We also print the total number of tokens used, which is important for understanding API usage and costs. This cell demonstrates how the API would typically be used without any compression, providing a baseline for comparison. ```python theme={null} # Cell 4: Define example prompt and test without compression # Example prompt prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ topic= "what is the moral of story" print("Without Llumo Compression:") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}\n") ``` # Test with Llumo compression ## Applying Llumo compression: * We call compress\_with\_llumo() with our example prompt. * The function returns multiple values, which we unpack into separate variables. ## Checking compression success: * We use an if statement to check if compression was successful. * If successful, we print compression statistics: percentage, initial and final token counts. ## Using the compressed prompt: * If compression succeeded, we use the compressed prompt in our API call to GPT-3.5-turbo. * We use the same message structure as before, but with the compressed prompt. ## Displaying results: * We print the AI's response to the compressed prompt. * We print the number of tokens used with the compressed prompt. ## Handling compression failure: * If compression fails, we print a message indicating this. * In a real application, you might want to fall back to using the original prompt in this case. This cell demonstrates the full process of compressing a prompt with Llumo and using it with the OpenAI API. By comparing the results and token usage with the previous cell, you can see the potential benefits of using Llumo compression in terms of token efficiency and cost savings. ```python theme={null} # Cell 5: Test with Llumo compression print("With Llumo Compression:") compressed_prompt, success, compression_percentage, initial_tokens, final_tokens = compress_with_llumo(prompt, topic) if success: print(f"Compression achieved: {compression_percentage:.2f}%") print(f"Initial tokens: {initial_tokens}, Final tokens: {final_tokens}") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": compressed_prompt} ] ) print(response.choices[0].message.content) print(f"Tokens used: {response.usage.total_tokens}") else: print("Compression failed. Using original prompt.") # Use the original prompt if compression fails ``` # Connect Your App to LLUMO AI in Minutes Source: https://docs.llumo.ai/how-to-docs/evaluate-llms/connect-python-sdk Get started with our SDK and ensure reliability for your app with intelligent observability and evaluation. Follow this quick guide to plug LLUMO AI into your workflow—fast, simple, and built for AI product teams. *** ## 1. Install the LLUMO AI SDK Please ensure that you have the **LLUMO AI SDK** installed before running evaluation. ```python theme={null} !pip install llumo ``` ## 2. Set your API key You will find your LLUMO AI API key on the top navbar next to your profile icon. ```python theme={null} LLUMO_AI_API_KEY = "key_NzE4NmU4*****************00d0cd" ``` ## 3. Select your framework Simply select your framework. For different frameworks, we have different callback handlers or wrappers. If you just want to evaluate the final log, select evaluate ```python theme={null} !pip install langchain_community !pip install langchain-openai ``` ```python theme={null} from langchain_openai import ChatOpenAI from langchain.agents import initialize_agent, Tool, AgentType from llumo import LlumoLogger ``` ```python theme={null} logger = LlumoLogger(apiKey=llumoKey, playground="playground-agent-logs") ``` ```python theme={null} sessionContext = LlumoSessionContext(logger=logger) sessionContext.start() sessionContext.startLlumoRun(runName="QUERY_EXECUTION") callbackHandler = LlumoCallbackHandler(session=sessionContext) try: # Execute query result = agent.run(q, callbacks=[callbackHandler]) except Exception as e: print(f"❌ Error: {str(e)}") # End Run sessionContext.endLlumoRun() # End Session sessionContext.end() ``` ```python theme={null} from llumo.openai import OpenAI from llumo.llumoLogger import LlumoLogger from llumo.llumoSessionContext import LlumoSessionContext logger = LlumoLogger(apiKey=llumoKey, playground="playground-openai-raw") # Initialize and start the Llumo Session session = LlumoSessionContext(logger = logger) ``` ```python theme={null} client = OpenAI( api_key="openaiKey", session=session, ) # Start Session session.start() session.startLlumoRun(runName="QUERY_EXECUTION") messages = [{"role": "user", "content": query}] # Output Generation response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, createExperiment=True, ) aiOutput = response.choices[0].message.content results.append({"query": query, "output": aiOutput}) # End Run session.endLlumoRun() # End Session session.end() ``` ```python theme={null} from llumo import LlumoLogger, LlumoSessionContext # Initialize logger logger = LlumoLogger( apiKey=llumoKey, playground="playground-batch-eval" ) # Initialize Llumo session session = LlumoSessionContext(logger=logger) # Run multiple evaluations resData = session.evaluateMultiple( data, evals=[ "Response Correctness", "Hallucination", "Response Completeness", "Input Bias", ], createExperiment=True, # Creates a named experiment in your dashboard ) # Print results print(resData) ``` ## 4. View Results on the LLUMO AI Dashboard Once you have integrated the SDK, we will handle all the heavy lifting, from logging, evaluating, creating run-reports, analysis issues across different runs and creating flow graph and insights for you. You can check out the whole debug reports on [app.llumo.ai/debugger](https://app.llumo.ai/debugger) # How to create a custom Eval from scratch? Source: https://docs.llumo.ai/how-to-docs/evaluate-llms/create-custom-evals Start getting insights in just 2 minutes LLUMO AI's Custom Evaluation Metrics feature lets you tailor the evaluation process to fit your unique needs, ensuring AI outputs align with your business goals. Whether you're analyzing customer service, academic content, or any other data, it helps you gain more precise and relevant insights. *** ## Aligns with Your Goals Custom metrics ensure your AI evaluation directly reflects your business objectives, whether it's improving customer service, content quality, or any other area. ## Accurate Assessments Tailored KPIs provide precise, relevant insights, avoiding the limitations of generic metrics that may not capture the nuances of your data. ## Actionable Insights for Better Decisions Custom metrics give you clear, actionable feedback, enabling quick improvements to AI performance based on what matters most to your business. ## Continuous Optimization Flexibility to adjust thresholds and criteria ensures ongoing improvement, keeping AI performance aligned with evolving business needs. ## Efficient Bulk Evaluation Evaluate large datasets quickly and accurately, saving time while maintaining high-quality assessments. ## Data-Driven Growth Granular feedback helps identify strengths and weaknesses, supporting informed decisions that drive AI and business growth. This guide will walk you through the steps of using Custom Eval Metrics to perform a detailed and personalized evaluation of your datasets. *** ## Step-by-Step Instructions: Evaluating using Custom Eval Metrics ### Step 1: Upload Your Dataset #### Option 1: Upload File 1. Log into the LLUMO AI Platform and go to the "Evaluate Dataset" section. 2. Click "Upload File" and select your dataset. The file can be in CSV, JSON, or Excel format. 3. **Review Your Data:** A preview of the uploaded data will be displayed. Ensure that the file is structured correctly and the data looks accurate before proceeding. #### Option 2: Upload via API 1. **Access the API Documentation:** Visit LLUMO’s API documentation for the exact endpoint and parameters. 2. **Upload Your Dataset:** Make an HTTP request to the API to upload your file. 3. **Confirm the Upload:** Once the upload is complete, you’ll receive a confirmation response, and the data will be ready for evaluation. *** ### Step 2: Go to Prompt Here, you can follow these steps: 1. **Write Prompt:** Enter your prompt by providing the desired query or instruction to guide the AI model in generating the results you expect. 2. **Create a Smart Prompt:** Refines your written prompt, making it more specific and detailed to generate more accurate and focused results. 3. **Select Your LLM Provider:** Choose your preferred provider from the drop-down list (LLUMO supports multiple LLM providers). 4. **Choose the Model:** Select the specific AI model you want to use for generating the results, based on your needs. 5. **Adjust Parameters:** Fine-tune the model’s parameters to match your requirements and improve output precision. 6. **Select Output Type:** Choose the type of output you want for the generated results. *** ### Step 3: Run the Prompts to Generate Outputs 1. Once the dataset is uploaded, initiate the process to run the prompts and generate outputs. 2. Allow the system to complete processing your prompts. 3. Once the outputs are ready, proceed to the evaluation step. Here, you can observe the prompt running to generate the output. Once the output is generated, the evaluation process will begin. *** ### Step 4: Custom Evaluation 1. Go to the "Create Column" section. 2. Select the "Custom Evaluation" option. 3. Here, you can create custom evaluation metrics by specifying a column name, defining the evaluation criteria, and selecting the prompt or output to assess. You can also create multiple custom evaluation metrics to evaluate different aspects of your data. 4. Once you've entered all the details, it will appear like this. In this example, I've created a custom metric called **Customer Intent Alignment (CIAS).** **Definition:** CIAS measures how well the company's response aligns with the customer's intended goal or request, based on AI-driven analysis of both the customer's inquiry and the company's response. 5. Select your evaluation model and choose the output column in your dataset that you want to assess. You can experiment with different models and run evaluations on the same prompt to compare their performance, using your custom evaluation metrics to analyze the results. *** ### Step 5: Evaluation Parameters **Set Rule for KPIs:** Each KPI allows you to set a specific threshold to define a "pass" or "fail." **Example:** For confidence, if the confidence score is more than 50, it passes. *** ### Step 6: Run the Evaluation 1. **Start the Evaluation:** After confirming your settings, click the "Create and Run All Columns" button to begin processing your evaluation. 2. **Review Evaluation Results:** The evaluation will return detailed results, including Pass/Fail status for each KPI along with percentage scores. Similarly, we can define multiple custom evaluations to evaluate the output. *** ## Frequently Asked Questions (FAQs) **How do I choose the right KPIs for my evaluation?** Select KPIs based on your evaluation goals. For example, for customer service data, KPIs like Sentiment Analysis and Response Time are essential. For academic writing, Grammar Quality and Clarity may be more relevant. **What happens if my outputs don’t meet the thresholds I set?** If an output fails to meet a threshold, it will be flagged as a failure. You can review the failed outputs and adjust the thresholds or improve the outputs to meet the required standards. **Can I export the evaluation results?** Yes, once the evaluation is complete, you can export the results in CSV, Excel, or PDF format for further analysis or reporting. **How long does the evaluation process take?** The time taken for the evaluation depends on the size of your dataset and the complexity of the model you’ve chosen. Typically, an evaluation of 100 prompts and outputs should take just a few minutes. If you need additional assistance, don’t hesitate to reach out to our support team! # How to customize Evals for your use case? Source: https://docs.llumo.ai/how-to-docs/evaluate-llms/customize-evaluations Start getting insights in just 2 minutes LLUMO AI's Custom Evaluation feature allows you to tailor the evaluation process to meet your unique requirements. Whether you're analyzing customer service data, academic content, or any other dataset, this powerful tool enables users to assess AI-generated outputs against tailored metrics and criteria that align with their specific needs and objectives. Unlike pre-defined evaluation methods, which may not fully capture the nuances of different use cases, Custom Evaluation allows users to define their own parameters, ensuring the evaluation process is both relevant and effective. This guide will walk you through the steps of using Custom Evaluation to perform a detailed and personalized evaluation of your datasets. *** ## Step-by-Step Instructions: Evaluating using Custom Evaluation ### Step 1: Upload Your Dataset #### Option 1: Upload File 1. Log into the LLUMO AI Platform and go to the "Evaluate Dataset" section. 2. Click "Upload File" and select your dataset. The file can be in CSV, JSON, or Excel format. 3. **Review Your Data**: A preview of the uploaded data will be displayed. Ensure that the file is structured correctly and the data looks accurate before proceeding. #### Option 2: Upload via API 1. **Access the API Documentation**: Visit LLUMO’s API documentation for the exact endpoint and parameters. 2. **Upload Your Dataset**: Make an HTTP request to the API to upload your file. 3. **Confirm the Upload**: Once the upload is complete, you’ll receive a confirmation response, and the data will be ready for evaluation. *** ### Step 2: Go to Prompt Here, you can follow these steps: 1. **Write Prompt**: Enter your prompt by providing the desired query or instruction to guide the AI model in generating the results you expect. 2. **Create a Smart Prompt**: Smart Prompt refines your written prompt, making it more specific and detailed to generate more accurate and focused results. 3. **Select Your LLM Provider**: Choose your preferred provider from the drop-down list (LLUMO supports multiple LLM providers). 4. **Choose the Model**: Select the specific AI model you want to use for generating the results, based on your needs. 5. **Adjust Parameters**: Fine-tune the model’s parameters to match your requirements and improve output precision. 6. **Select Output Type**: Choose the type of output you want for the generated results. *** ### Step 3: Run the Prompts to Generate Outputs 1. Once the dataset is uploaded, initiate the process to run the prompts and generate outputs. 2. Allow the system to complete processing your prompts. 3. Once the outputs are ready, proceed to the evaluation step. *** ### Step 3: Custom Evaluation 1. Go to the **"Create Column"** section. 2. Select the **“Evaluation”** option. Here, you can create your own Custom Evaluation by specifying a column name, defining your evaluation criteria instead of pre-defined criteria, and selecting the prompt or output you wish to assess using this custom evaluation. #### Example: Response Coherence In the screen below, we select Response Coherence as our evaluation metric from over 50+ available KPIs, which comes with predefined criteria. In custom evaluation, we replace the predefined criteria with our own custom definition to evaluate the output according to our specific niche. **Definition**:\ It refers to how logically consistent and well-structured the AI's response is, ensuring that the content flows smoothly, aligns with the prompt, and makes sense within its context. A coherent response should present information in a way that is clear, unified, and free from contradictions, with all parts of the response connecting logically to one another. **Key Aspects of Response Coherence**: * **Logical Flow**: The ideas in the response should be presented in a clear sequence. There should be a natural progression from one thought or statement to the next, without confusing jumps or gaps. * **Consistency**: The response should not contradict itself. All statements made within the response should be aligned and support the main point. Conflicting information reduces coherence. * **Contextual Relevance**: The response should remain relevant to the context and the prompt. It should avoid introducing irrelevant information or veering off-topic. * **Clarity and Understandability**: The ideas should be communicated in a way that is easy for the reader to follow and understand. Unclear or vague statements can make a response appear incoherent. 3. Select your evaluation model. You can choose different models to evaluate and compare their performance using the same prompt. 4. Choose the output column you wish to evaluate. *** ### Step 4: Evaluation Parameters 1. **Set Rule for KPIs**: Each KPI allows you to set a specific threshold to define a "pass" or "fail."\ Example for confidence: If the confidence score is more than 50, it passes. *** ### Step 5: Run the Evaluation 1. **Start the Evaluation**: After confirming your settings, click the **"Create and Run All Columns"** button to begin processing your evaluation. 2. **Review Evaluation Results**: The evaluation will return detailed results, including Pass/Fail status for each KPI along with percentage scores. *** ## Use Case: Response Coherence Imagine you’re evaluating customer service responses. A coherent response should: * Maintain logical flow, ensuring smooth progression from one point to the next. * Avoid contradictions and inconsistencies. * Stay relevant to the customer’s query. * Be clear and easy to understand. Using Custom Evaluation, you can: 1. Create a metric for "Response Coherence" with your own definition and scoring method. 2. Adjust parameters to ensure the evaluation focuses on what matters most to your business. 3. Compare different AI models or prompt structures to determine which yields the best results. *** ## Frequently Asked Questions (FAQs) **How do I choose the right KPIs for my evaluation?**\ Select KPIs based on your evaluation goals. For example, for customer service data, KPIs like Sentiment Analysis and Response Time are essential. For academic writing, Grammar Quality and Clarity may be more relevant. **Can I customize the KPIs for my evaluation?**\ While you can’t create completely custom KPIs, you can define KPIs specific to your niche by selecting and adjusting the existing ones. For example, you might adjust the Sentiment Analysis threshold to match customer service standards. **What happens if my outputs don’t meet the thresholds I set?**\ If an output fails to meet a threshold, it will be flagged as a failure. You can review the failed outputs and adjust the thresholds or improve the outputs to meet the required standards. **Can I export the evaluation results?**\ Yes, once the evaluation is complete, you can export the results in CSV, Excel, or PDF format for further analysis or reporting. **How long does the evaluation process take?**\ The time taken for the evaluation depends on the size of your dataset and the complexity of the model you’ve chosen. Typically, an evaluation of 100 prompts and outputs should take just a few minutes. If you need additional assistance, don’t hesitate to reach out to our support team! # null Source: https://docs.llumo.ai/how-to-docs/evaluate-llms/production # Save RAG cost using Prompt Compression Source: https://docs.llumo.ai/how-to-docs/save-rag-cost Start cutting AI cost in just 2 minutes Prompt compression helps reduce RAG costs by making shorter prompts while retaining their meaning. Using Llumo AI's simple API integration, you can easily compress your prompts and get the same output but at a much lower cost, with fewer hallucinations and faster inference speed.\ **RAG\_Context** and **Query** are pre-built variables that can be used to build your prompts. To create additional variables, use the "+Variable" format and reference them within your prompt using `{{ variable_name }}`. *** ## Key Concepts ### 1. What is RAG\_Context? Think of **RAG\_Context** as the "background information" that you give to the AI model to help it understand the situation better. #### Example: If you want to ask an AI, "What should I do to improve my health?" the AI could give a more specific answer if it knows the context: * Are you looking for exercise tips? * Do you have any specific health conditions? * Is your goal to lose weight, gain muscle, or stay healthy? So, the RAG\_Context provides that background information. **RAG\_Context Example:**\ `"I am asking for health improvement advice for someone who is looking to lose weight and is currently inactive."` *** ### 2. What is a Query? **Query** is the actual question or request you are asking the AI. It should be clear and direct. #### Example: Query: `"What are the best exercises to start with for weight loss?"` *** ### 3. What is a Prompt? A **prompt** is a combination of RAG\_Context and Query to form a complete input for the AI. * RAG\_Context provides the background or situation. * Query asks the actual question or makes the request. In LLUMO AI, both of these can be used together to form a complete and effective prompt. #### Example: Imagine you want to ask LLUMO AI for health advice. You would use **RAG\_Context** and **Query** in a combined format, like this: * **RAG\_Context:** `"I am asking for health improvement advice for someone who is looking to lose weight and is currently inactive."` * **Query:** `"What are the best exercises to start with for weight loss?"` **Full Prompt Example:**\ `"Give me an answer to the following query: {{ Query }} using the given context: {{ RAG_Context }}."` Here, the AI understands both the **RAG\_context** (the background information about losing weight and being inactive) and the **Query** (the specific question about exercises). This combination leads to a more accurate and relevant response. Why Use Pre-Built Variables? * **Save time**: You don’t need to repeat long context or details every time you create a prompt. * **Improve accuracy**: By defining specific variables, you ensure the AI takes into account all the details you want for a more accurate response. * **Make it easier to update**: If you need to change any part of the prompt, you can just update the value of the variable rather than rewriting the entire prompt. *** ### 4. Creating Additional Variables with "+Variable" You can add more specific details by creating custom variables using the format `+Variable`. #### Example: * **Custom Variable for Location:** `"I live in a hot, humid climate."` * **Custom Variable for Age:** `"I am 35 years old."` **Full Prompt Example:**\ `"Give me an answer to the following query: {{ Query }} using the given context: {{ RAG_Context }}, considering the location: {{ Location }}, and the age: {{ Age }}."` *** ## How to Perform Prompt Compression ### Step-by-Step Guide: 1. **Generate Sample Data:**\ Click on **Generate Sample** to create example data. This helps you test the system without inputting your own information. 2. **Verify Sample Data** When you click on **"Generate Sample"**, LLUMO AI will generate a set of random or example data that you can use to test how the system works. Here, take a moment to review the sample to get an idea of the format and structure. 3. **Compress and Run:**\ After generating the sample, click **Compress and Run** to reduce token size while retaining meaning. 4. **Example Results:** * **Output Similarity:** This shows how closely the generated response matches the original intent and context. For example, you might see that the AI’s response is about **89.89%** similar to what it should be based on the sample data. * **Token Reduction:** This shows how much the token count has been reduced after compression. A token is a unit of text used by the AI to process information. Compressing your prompt reduces the number of tokens, which makes processing faster and cheaper. For example, you might see that the token size is reduced from **1829 to 724** token size. If you already have your own data ready for testing or compressing, LLUMO AI makes it easy to work with your specific set of information. Here’s a detailed step-by-step guide to help you get started with your data on LLUMO AI: 1. **Define Pre-Built Variables and Prompt** LLUMO AI offers pre-built variables like **RAG\_Context** and **Query**, so you don’t have to set them up yourself. These are ready to use from the start, making it easier and faster to build your prompts. Simply write your **RAG\_Context** and **Query**, and add any extra variables if needed. By using these pre-built variables, you save time by not having to manually define certain details in your prompt. ### Example: Using RAG\_Context and Query Let’s say you want to ask the AI for health advice related to weight loss. Here's how it would look: * **RAG\_Context:** `"I need health advice for someone trying to lose weight."` * **Query:** `"What are the best practices for weight loss?"` So, your full prompt might look like this:\ `"Give me an answer to the following query: {{ Query }} using the given context: {{ RAG_Context }}."` When the AI processes this, it will: * Take the **RAG\_Context**: `"I need health advice for someone trying to lose weight."` * Combine it with the **Query**: `"What exercises are best for weight loss?"` This results in a well-informed and accurate response from the AI. When the AI processes this, it will take RAG\_Context ("I need health advice for someone trying to lose weight") and Query ("What exercises are best for weight loss?") and combine them to generate a response. 2. **Choose the Provider and Model** Once you've written your prompt, the next step is to select the **provider** and **model**. * **Pick a Provider:**\ Choose the service that will power the AI for your prompt. For example: * OpenAI (which provides models like GPT-4) * Other supported providers\ You can select the provider from a dropdown menu. * **Pick a Model:**\ After selecting the provider, choose a specific model. For instance: * **GPT-4** for advanced responses. Once both the provider and model are selected, you're all set to run your prompt and receive an answer! 3. **Compress and Run** Once your prompt is set and you've chosen the model, click the "Compress and Run" button. LLUMO AI will automatically compress the prompt by shortening it, making it more efficient. After the system processes your compressed prompt, LLUMO AI will show you the results. * **Output Similarity:**\ This shows how similar the AI’s response is to the expected result, helping you measure how well the prompt compression works. For example, you might see that the AI’s response is about **93.90%** similar to what it should be based on the sample data. * **Token Count Reduction:**\ This shows how many tokens have been saved by compressing the prompt. Fewer tokens usually mean a quicker and more cost-efficient response. For example, you might see that the token size is reduced from **525 to 143** token size. 4. **Previous RAG\_Context and Query** You’ll see a symbol next to `+variable`. When you click on it, you can see the RAG\_Context and queries you’ve used before. This makes it easy to check your past inputs without having to enter them again. 5. **Connect API** * Navigate to the Connect API section within your LLUMO AI interface. * Once in the Connect API tab, you’ll find simple, step-by-step instructions on how to integrate the API with your system. * Follow the guidelines carefully to integrate the API. This may involve copying a key or adding a few lines of code to link LLUMO AI with your project. By following these 3 simple steps, you'll be set up to use prompt compression and enhance your workflow within just 5 minutes! *** ## Benefits of Prompt Compression * **Save Time:** Avoid repeating long details by using pre-built or custom variables. * **Improve Accuracy:** Ensure the AI considers all necessary information for better responses. * **Reduce Costs:** Shorter prompts reduce token counts, making processing faster and cheaper. *** ## FAQ 1. **What is prompt compression, and how does it help with AI?**\ Prompt compression is when you shorten the text you give to AI but still keep the same meaning. This helps save money because the AI doesn't need to process as much information. It also speeds up the AI's response time, making everything run faster and more efficiently. 2. **How do I use RAG\_Context and Query in LLUMO AI?**\ LLUMO AI gives you two pre-made variables called RAG\_Context and Query. RAG\_Context is the background information, and Query is the question you want answered. Instead of typing everything out, you just use these variables, which makes creating prompts much quicker and easier. 3. **Can I create my own variables in LLUMO AI?**\ Yes! If you need extra information in your prompts, you can create your own custom variables by adding "+Variable." For example, if you need a variable for someone's location, you can call it "+location." Then, just refer to it in your prompt, just like the pre-built variables. 4. **How does prompt compression make things cheaper and faster?**\ By shortening your prompts, you reduce the number of tokens, which lowers the cost for using AI. Plus, smaller prompts mean the AI can process them faster, so you get quicker answers. It's a simple way to save money and time. 5. **Can I view my old RAG\_Context and Query values?**\ If you want to see the RAG\_Context and Query you've used before, you can do that easily. Just click on the symbol next to "+variable," and it will show you all your past inputs. This way, you don’t have to re-enter them every time. *** # Create Eval Analytics API Source: https://docs.llumo.ai/llm-evaluation/api-reference/create-eval-analytics-api post /api/create-eval-analytics Creates evaluation analytics # Evaluating a Bulk Dataset using 3-4 metrics Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/evaluate-dataset-multiple-metric If you're working with large datasets, whether it's customer support conversations, academic papers, or chatbot dialogues, here's the hard truth: Evaluating your AI models with just one metric is a **huge mistake**. If you only measure one thing – let’s say "accuracy" – you might be missing the forest for the trees. Sure, your AI could be spitting out correct answers, but what if it's doing so in a way that’s confusing, irrelevant, or even hallucinating? You need a range of metrics to get the full story. LLUMO AI lets you assess performance across 50+ Evaluation metrics such as clarity, confidence, context, and even hallucinations. You’ll get a much clearer picture of where your model stands and where it needs work. This guide will walk you through the process of evaluating a bulk dataset with multiple prompts and models, from uploading your data to interpreting the results. *** ## Step-by-Step Instructions: Evaluating a Bulk Dataset of chatbot using 3-4 Evaluation metrics ### Step 1: Upload Your Dataset **Option 1: Upload File** 1. Log into the LLUMO AI Platform and go to the "Evaluate Dataset" section. 2. Click "Upload File" and select your dataset. The file can be in CSV, JSON, or Excel format. 3. Review Your Data: A preview of the uploaded data will be displayed. Ensure that the file is structured correctly and the data looks accurate before proceeding. **Option 2: Upload via API** 1. Access the API Documentation: Visit LLUMO’s API documentation for the exact endpoint and parameters. 2. Upload Your Dataset: Make an HTTP request to the API to upload your file. 3. Confirm the Upload: Once the upload is complete, you’ll receive a confirmation response, and the data will be ready for evaluation. ### Step 2: Go to Prompt Here, you can follow these steps: 1. Write Prompt: Here, enter your prompt by providing the desired query or instruction to guide the AI model in generating the results you expect. 2. Create a Smart Prompt: Smart Prompt refines your written prompt, making it more specific and detailed to generate more accurate and focused results. 3. Select Your LLM Provider: Choose your preferred provider from the drop-down list (LLUMO supports multiple LLM providers). 4. Choose the Model: Select the specific AI model you want to use for generating the results, based on your needs. * You can choose different models to evaluate and run experiments to compare their performance on the same prompt. 5. Adjust Parameters: Fine-tune the model’s parameters to match your requirements and improve output precision. 6. Select Output Type: Choose the type of output you want for the generated results. ### Step 3: Run the Prompts to Generate Outputs 1. Once the dataset is uploaded, initiate the process to run the prompts and generate outputs. 2. Allow the system to complete processing your prompts. 3. Once the outputs are ready, proceed to the evaluation step. * Here, you can observe the prompt running to generate the output. Once the output is generated, the evaluation process will begin. ### Step 3: Select Key Performance Indicators (KPIs) 1. Go to the "Create Column" section and select the “Evaluation” option. 2. From the dropdown menu, choose the KPIs you want to evaluate. 3. Name the column where the evaluation results will be displayed. 4. Select the output column in your dataset that you want to evaluate. Here we are selecting our 1st metrics confidence. * You can choose from more than 50 KPIs covering various areas of analysis, such as: Context, clarity, confidence and even many more. ### Step 3: Evaluation Parameters 1. Set Rule for KPIs: * Each KPI allows you to set a specific threshold to define a "pass" or "fail." * Example for confidence : if the confidence score is more than 50, it passes. ### Step 4: Choose Your Evaluation Model 1. Select the model that best fits your evaluation needs. ### Step 5: Run the Evaluation 1. Start the Evaluation: After confirming your settings, click the "Create and Run All Columns" button to begin processing your evaluation. ### Step 6: Review Results 1. Once the evaluation is complete, you'll receive detailed results, including: * Pass/Fail status for each KPI * Percentage scores for each metric * These results will help you identify areas of improvement for your AI model and refine it based on the feedback. ### Step 7: Export Evaluation Results 1. You can export the evaluation results for further analysis or reporting in CSV, Excel, or PDF format. Similarly, we can select multiple KPIs to evaluate the output, and the final result will appear as follows: LLUMO AI isn’t just about evaluating – it’s about transforming how you work with your data. The platform makes it incredibly easy to run comprehensive evaluations with multiple KPIs. ## Use Case 1: How can you perform a bulk evaluation using multiple evaluation metrics across different models at once instead of processing them individually. ### Step 1: Navigate to the box on the right side of the "Knowledge Base" section and click Select All. * Selecting "All" ensures that the entire dataset, including all evaluation metrics and prompts, is selected. You will see an indicator confirming that 55 rows (or data entries) have been selected for evaluation. ### Step 2: After selecting all rows, a new menu will appear. Click on Run All in the menu. * This action initiates the evaluation process for the entire dataset using multiple evaluation metrics across different models, all in a single click. ### Step 3: Once you click Run All, the system executes the evaluation process for the selected rows. * This includes running prompts, generating outputs, and evaluating them against your custom metrics. The evaluation results are displayed in the window, providing a detailed view of the outputs and metrics. Here, in the above screen perform the following * **Selected Checkbox:** * Indicates that 100 rows (or data entries) are currently selected for batch processing, such as cloning or evaluation. * **Clone Button:** * Creates a duplicate of the selected rows or data entries. Useful for experimenting with slight modifications while retaining the original data. * **Delete Button:** * Deletes the selected rows or data entries from the evaluation table. This action is typically irreversible, so users need to confirm before proceeding. * **Run Button:** * Executes the evaluation process for the selected rows. This triggers the prompt and output generation along with custom metric evaluations. * **Close Button:** * Exits the current evaluation session or clears the current selection of rows, returning users to the previous state or dashboard. Additionally, for a comprehensive overview of available tools, actions, and customization options within the LLUMO platform, check out the Comprehensive Menu and Features Overview. This page will help you navigate the various features and capabilities to enhance your evaluation process, including how to access, configure, and utilize custom metrics efficiently. ## Key Terminology ### Key Performance Indicators (KPIs) * KPIs are measurable metrics used to assess the performance of your prompts and outputs. ### Set Rule * Using Set Rule, you can set minimum or maximum values that determine whether the results meet the evaluation criteria. For example, you might set a threshold of 80% accuracy for grammar quality, meaning that any output with less than 80% accuracy would fail that KPI. ### Pass/Fail Criteria * These are the conditions that must be met for an output to pass the evaluation. If an output meets or exceeds the set percentage, it passes; otherwise, it fails. ### AI Models * AI models are the underlying algorithms used to process and evaluate the outputs. LLUMO AI supports several models optimized for different evaluation tasks, such as sentiment analysis, grammar checking, or response relevance. ## Frequently Asked Questions (FAQs) ### What happens if my output doesn’t meet the thresholds I set? * If an output doesn’t meet the set criteria, it will be marked as a Fail. You can review the failed outputs and adjust your model or dataset accordingly to improve performance. ### Can I export my evaluation results? * Yes, you can export the results in CSV, Excel, or PDF formats for detailed analysis or reporting purposes. ### How long does the evaluation process take? * The evaluation time depends on the size of your dataset and the complexity of the selected evaluation model. A typical evaluation of 100 prompts and outputs may take only a few minutes. ### How do I handle large volumes of data efficiently during the evaluation? * To manage large volumes of data, it’s recommended to upload files in manageable chunks or utilize the API for bulk processing. ## Glossary ### Knowledge Base: * This column displays the source or baseline data (e.g., a company's description or service information). ### User Question: * The user’s query or the input to be addressed by the AI. ### Prompt: * The prompt used to guide the AI’s response generation, likely adjusted or created by the user for optimal results. ### Output Columns: * These represent various custom evaluation metrics created for assessing the AI’s responses, such as: * **Test Confidence:** Evaluates the confidence level in the AI’s response. * **Test Context:** Measures the relevance of the AI’s output to the provided context. * **Test Clarity:** Assesses how clear the AI-generated response is. * **Test Vocabulary:** Evaluates vocabulary usage and alignment with domain-specific language or requirements. # Setup prompt evaluation API Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/evaluate-first-prompt Use LLUMO AI's proprietary technology to evaluate LLM output and gain insights. ## Integrating Llumo evaluation API in LLM Pipeline This guide will explain how to integrate Llumo's evaluation API into a LLM pipeline build on top of OpenAI APIs. LLUMO can help you gain complete insights on you LLM outputs and customer success using proprietary framework- EvalLM. We'll go through the process step-by-step to make it easy for developers of all levels. \##Setting up the environment \###Importing libraries: * os: This module provides a way to use operating system dependent functionality, like reading environment variables. * OpenAI: This is the official OpenAI Python client, used to interact with OpenAI's API. * requests: A popular library for making HTTP requests in Python. * json: Used for parsing JSON data, which is common in API responses. * logging: Provides a flexible framework for generating log messages in Python. * getpass: Allows secure password prompts where the input is not displayed on the screen. \###Setting up logging: * We use `logging.basicConfig()` to configure the logging system. The `level=logging.INFO` argument sets the threshold for logging messages to INFO level and above. * We create a logger object named logger that we'll use throughout our script to log important information and errors. This setup ensures we have all necessary tools to interact with APIs, handle data, and track any issues that might occur during execution. ```python theme={null} !pip install openai import os from openai import OpenAI import requests import json import logging from getpass import getpass # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) print("Libraries imported and logging set up successfully.") ``` \##Secure API key handling \###Secure API key input: * We use `getpass()` to prompt the user for their API keys. This function hides the input, making it more secure than using regular input(). * This approach is safer than hardcoding API keys in your script, which could accidentally be shared or exposed. \###Setting environment variables: * We use `os.environ` to set environment variables for both API keys. * Environment variables are a secure way to store sensitive information, as they're not part of your code and are only accessible within the current process. \###Initializing the OpenAI client: * We create an instance of the OpenAI client using the API key we just set. * Using `os.getenv("OPENAI_API_KEY")` retrieves the API key from the environment variables. This method ensures that your API keys are handled securely and are readily available for use in your script. ```python theme={null} # Cell 2: Secure API key handling # Securely input API keys openai_api_key = getpass("Enter your OpenAI API key: ") llumo_api_key = getpass("Enter your Llumo API key: ") # Set environment variables os.environ['OPENAI_API_KEY'] = openai_api_key os.environ['LLUMO_API_KEY'] = llumo_api_key del openai_api_key del llumo_api_key # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) print("API keys securely set and OpenAI client initialized.") ``` # Llumo Evaluation Function Documentation ## Define Llumo Evaluation Function ### Function Definition: * We define a function `evaluate_with_llumo` that takes a `prompt` and `output` as inputs. ### API Setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ### Payload Preparation: * We create a payload dictionary with the `prompt`, `output`, and predefined analytics type ("Clarity"). ### API Request: * We use `requests.post()` to send a POST request to the Llumo API. * `response.raise_for_status()` will raise an exception for HTTP errors. ### Response Parsing: * We parse the JSON response and extract the evaluation data. * We print the API response for debugging purposes. ### Error Handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * If an error occurs, we log it and return an empty dictionary with a failure indicator. ### Return Values: * The function returns a tuple containing: * Evaluation data (or empty dictionary if evaluation failed) * Success boolean This function encapsulates the entire process of interacting with the Llumo API for text evaluation, including error handling and result processing. ```python theme={null} def evaluate_with_llumo(prompt, output): LLUMO_API_KEY = os.getenv("LLUMO_API_KEY") LLUMO_ENDPOINT = "https://app.llumo.ai/api/create-eval-analytics" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } payload = { "prompt": prompt, "input": {}, "output": output, "analytics": ["Clarity"] } try: response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) try: result = response.json() print("API Response:", result) return result.get('data', {}), True except json.JSONDecodeError as json_error: logger.error(f"Error decoding JSON: {str(json_error)}") return {}, False except requests.RequestException as e: logger.error(f"Error evaluating with Llumo: {str(e)}") return {}, False ``` # Getting Respone from OpenAI ### Define Example Prompt: * We define an example prompt to be used for testing without compression. ### Example Prompt: ```python theme={null} prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognized a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ ``` This segment of code demonstrates how to define an example prompt and test the response generation without applying any compression, using the OpenAI API. It includes the prompt definition, API request, and response extraction steps. ```python theme={null} # Cell 4: Define example prompt and test without compression # Example prompt prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) openai_output=response.choices[0].message.content print(openai_output) print(f"Tokens used: {response.usage.total_tokens}\n") ``` # Evaluating Responses with Llumo ### Evaluate the OpenAI Response: * We evaluate the response generated by the OpenAI API using the Llumo evaluation function. * We call the evaluate\_with\_llumo function with the example prompt and the openai\_output. * We check if the evaluation was successful: * If successful, we print the Llumo evaluation results. * If the evaluation fails, we print an error message and indicate that the original prompt can be used if evaluation fails. ```python theme={null} print("Evaluating Responses:") llumo_result, success = evaluate_with_llumo(prompt, openai_output) if success: print("Llumo Evaluation Results:") for analytic, score in llumo_result.items(): print(f"{analytic}: {score}") else: print("Evaluation with Llumo failed.") # Use the original prompt if compression fails ``` # Setup Prompt Evaluation API with OpenAI output Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/evaluate-openAI Use LLUMO AI’s proprietary technology to evaluate output from OpenAI GPT models. \##Setting up the environment \###Importing libraries: * os: This module provides a way to use operating system dependent functionality, like reading environment variables. * OpenAI: This is the official OpenAI Python client, used to interact with OpenAI's API. * requests: A popular library for making HTTP requests in Python. * json: Used for parsing JSON data, which is common in API responses. * logging: Provides a flexible framework for generating log messages in Python. * getpass: Allows secure password prompts where the input is not displayed on the screen. \###Setting up logging: * We use `logging.basicConfig()` to configure the logging system. The `level=logging.INFO` argument sets the threshold for logging messages to INFO level and above. * We create a logger object named logger that we'll use throughout our script to log important information and errors. This setup ensures we have all necessary tools to interact with APIs, handle data, and track any issues that might occur during execution. ```python theme={null} !pip install openai import os from openai import OpenAI import requests import json import logging from getpass import getpass # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) print("Libraries imported and logging set up successfully.") ``` \##Secure API key handling \###Secure API key input: * We use `getpass()` to prompt the user for their API keys. This function hides the input, making it more secure than using regular input(). * This approach is safer than hardcoding API keys in your script, which could accidentally be shared or exposed. \###Setting environment variables: * We use `os.environ` to set environment variables for both API keys. * Environment variables are a secure way to store sensitive information, as they're not part of your code and are only accessible within the current process. \###Initializing the OpenAI client: * We create an instance of the OpenAI client using the API key we just set. * Using `os.getenv("OPENAI_API_KEY")` retrieves the API key from the environment variables. This method ensures that your API keys are handled securely and are readily available for use in your script. ```python theme={null} # Cell 2: Secure API key handling # Securely input API keys openai_api_key = getpass("Enter your OpenAI API key: ") llumo_api_key = getpass("Enter your Llumo API key: ") # Set environment variables os.environ['OPENAI_API_KEY'] = openai_api_key os.environ['LLUMO_API_KEY'] = llumo_api_key del openai_api_key del llumo_api_key # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) print("API keys securely set and OpenAI client initialized.") ``` # Llumo Evaluation Function Documentation ## Define Llumo Evaluation Function ### Function Definition: * We define a function `evaluate_with_llumo` that takes a `prompt` and `output` as inputs. ### API Setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ### Payload Preparation: * We create a payload dictionary with the `prompt`, `output`, and predefined analytics type ("Clarity"). ### API Request: * We use `requests.post()` to send a POST request to the Llumo API. * `response.raise_for_status()` will raise an exception for HTTP errors. ### Response Parsing: * We parse the JSON response and extract the evaluation data. * We print the API response for debugging purposes. ### Error Handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * If an error occurs, we log it and return an empty dictionary with a failure indicator. ### Return Values: * The function returns a tuple containing: * Evaluation data (or empty dictionary if evaluation failed) * Success boolean This function encapsulates the entire process of interacting with the Llumo API for text evaluation, including error handling and result processing. ```python theme={null} def evaluate_with_llumo(prompt, output): LLUMO_API_KEY = os.getenv("LLUMO_API_KEY") LLUMO_ENDPOINT = "https://app.llumo.ai/api/create-eval-analytics" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } payload = { "prompt": prompt, "input": {}, "output": output, "analytics": ["Clarity"] } try: response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) try: result = response.json() print("API Response:", result) return result.get('data', {}), True except json.JSONDecodeError as json_error: logger.error(f"Error decoding JSON: {str(json_error)}") return {}, False except requests.RequestException as e: logger.error(f"Error evaluating with Llumo: {str(e)}") return {}, False ``` # Getting Respone from OpenAI ### Define Example Prompt: * We define an example prompt to be used for testing without compression. ### Example Prompt: ```python theme={null} prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognized a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ ``` This segment of code demonstrates how to define an example prompt and test the response generation without applying any compression, using the OpenAI API. It includes the prompt definition, API request, and response extraction steps. ```python theme={null} # Cell 4: Define example prompt and test without compression # Example prompt prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. """ response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt} ] ) openai_output=response.choices[0].message.content print(openai_output) print(f"Tokens used: {response.usage.total_tokens}\n") ``` # Evaluating Responses with Llumo ### Evaluate the OpenAI Response: * We evaluate the response generated by the OpenAI API using the Llumo evaluation function. * We call the evaluate\_with\_llumo function with the example prompt and the openai\_output. * We check if the evaluation was successful: * If successful, we print the Llumo evaluation results. * If the evaluation fails, we print an error message and indicate that the original prompt can be used if evaluation fails. ```python theme={null} print("Evaluating Responses:") llumo_result, success = evaluate_with_llumo(prompt, openai_output) if success: print("Llumo Evaluation Results:") for analytic, score in llumo_result.items(): print(f"{analytic}: {score}") else: print("Evaluation with Llumo failed.") # Use the original prompt if compression fails ``` # Setup Prompt Evaluation API with Vertex output Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/evaluate-vertex Use LLUMO AI’s proprietary technology to evaluate output from Google Gemini models. \##Installing Necessary Libraries This cell installs or upgrades the necessary Python packages for the project: * google-cloud-aiplatform: The Google Cloud AI Platform SDK, used for interacting with Vertex AI. * requests: A popular HTTP library for making API calls (will be used for the Llumo API). * nltk: Natural Language Toolkit, a leading platform for building Python programs to work with human language data. * beautifulsoup4: A library for pulling data out of HTML and XML files, useful for web scraping. The ! at the beginning allows running shell commands in Jupyter notebooks or Google Colab. ```python theme={null} !pip install --upgrade google-cloud-aiplatform requests ``` \##Setting Up VertexAI This cell mounts your Google Drive to the Colab environment: * It imports the `os` module for operating system operations and the drive module from `google.colab`. * `drive.mount()` attaches your Google Drive to the '/content/drive' directory in the Colab environment. * `force_remount=True` ensures that the drive is remounted even if it was previously mounted, which can help resolve connection issues ```python theme={null} import os from google.colab import drive drive.mount('/content/drive',force_remount=True) ``` Then set up the Google Cloud credentials: * It sets the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to your Google Cloud service account key file. * The file path suggests that your credentials JSON file is stored in your Google Drive under the 'MyDrive/vertex/' directory. * This step is crucial for authenticating your script with Google Cloud services. ```python theme={null} os.environ['GOOGLE_APPLICATION_CREDENTIALS']='/content/drive/MyDrive/vertex/googleCred.json' ``` \##Importing Libraries This cell imports all necessary Python modules: * `os`: For operating system operations and environment variables. * `requests`: For making HTTP requests (will be used for Llumo API calls). * `json`: For JSON parsing and manipulation. * `logging`: For setting up logging in the script. * `getpass`: For securely inputting passwords or API keys. * `aiplatform`: The main module for interacting with Vertex AI. * `TextGenerationModel`: Specific class for text generation tasks in Vertex AI. ```python theme={null} import os import requests import json import logging from getpass import getpass from google.cloud import aiplatform from vertexai.language_models import TextGenerationModel ``` \##Setting up Basic Logging This cell sets up logging for the script: * `logging.basicConfig()` configures the logging system with INFO level, meaning it will capture all info, warning, and error messages. * `logger = logging.getLogger(__name__)` creates a logger object.` __name__` is a special Python variable that gets set to the module's name when the module is executed. ```python theme={null} logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ``` \##Setting up Llumo API This cell securely handles the Llumo API key: * It uses `getpass()` to prompt for the Llumo API key without displaying it on the screen as it's typed. * The API key is then stored as an environment variable named 'LLUMO\_API\_KEY'. * This approach keeps the API key secure by not hardcoding it in the script. ```python theme={null} llumo_api_key = getpass("Enter your Llumo API key: ") os.environ['LLUMO_API_KEY'] = llumo_api_key del llumo_api_key ``` # Llumo Evaluation Function Documentation ## Define Llumo Evaluation Function ### Function Definition: * We define a function `evaluate_with_llumo` that takes a `prompt` and `output` as inputs. ### API Setup: * We retrieve the Llumo API key from environment variables. * We set the API endpoint and prepare headers for the HTTP request. ### Payload Preparation: * We create a payload dictionary with the `prompt`, `output`, and predefined analytics type ("Clarity"). ### API Request: * We use `requests.post()` to send a POST request to the Llumo API. * `response.raise_for_status()` will raise an exception for HTTP errors. ### Response Parsing: * We parse the JSON response and extract the evaluation data. * We print the API response for debugging purposes. ### Error Handling: * We use a try-except block to catch potential errors: * JSON decoding errors * Request exceptions * If an error occurs, we log it and return an empty dictionary with a failure indicator. ### Return Values: * The function returns a tuple containing: * Evaluation data (or empty dictionary if evaluation failed) * Success boolean This function encapsulates the entire process of interacting with the Llumo API for text evaluation, including error handling and result processing. ```python theme={null} def evaluate_with_llumo(prompt, output): LLUMO_API_KEY = os.getenv("LLUMO_API_KEY") LLUMO_ENDPOINT = "https://app.llumo.ai/api/create-eval-analytics" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {LLUMO_API_KEY}" } payload = { "prompt": prompt, "input": {}, "output": output, "analytics": ["Clarity"] } try: response = requests.post(LLUMO_ENDPOINT, json=payload, headers=headers) try: result = response.json() print("API Response:", result) return result.get('data', {}), True except json.JSONDecodeError as json_error: logger.error(f"Error decoding JSON: {str(json_error)}") return {}, False except requests.RequestException as e: logger.error(f"Error evaluating with Llumo: {str(e)}") return {}, False ``` \##Getting Respone from VertexAI. \###Defining the prompt: * We create a detailed prompt about photosynthesis. This serves as our example text for compression. \###Sending request: * We use the VertexAI client to send a request to the text-bison model. * The messages parameter follows the chat format: * A system message sets the AI's role. * A user message contains our prompt. \###Displaying results: * We print the AI's response to the prompt. * Vertex AI doesn't provide any token usage. So, it's not possible to print token usage for checking. ```python theme={null} prompt = """ Quite a long time ago, there lived two talking birds with their parents. One day when their parents were away, a villager who generally had an eye on those special birds caught them and took them away. One of the birds got away from the trap and looked for his parents. The bird, at last, arrived at a hermitage where it was welcomed and had some food. He lived joyfully. An explorer once ran over the other bird that the villager caught. He talked very rudely to him. He was shocked to see a talking bird but at the same time was angry with his way of behaving. The explorer visited the hermitage and recognised a similar talking bird, yet this bird talked respectfully and welcomed him to remain there. Moral of the Story Staying in a good company gives us a good way of behaving. Bad company influences our way of behaving negatively. What is Moral of the story """ model = TextGenerationModel.from_pretrained("text-bison") parameters = { "max_output_tokens": 1024, "temperature": 0.2, "top_p": 0.8, "top_k": 40 } response = model.predict(prompt, **parameters) print(response.text) ``` # Evaluating Responses with Llumo ### Evaluate the OpenAI Response: * We evaluate the response generated by the OpenAI API using the Llumo evaluation function. * We call the evaluate\_with\_llumo function with the example prompt and the openai\_output. * We check if the evaluation was successful: * If successful, we print the Llumo evaluation results. * If the evaluation fails, we print an error message and indicate that the original prompt can be used if evaluation fails. ```python theme={null} print("Evaluating Responses:") prompt = "Describe the process of photosynthesis." response = "Photosynthesis is a process used by plants and other organisms to convert light energy, usually from the sun, into chemical energy that can later be released to fuel the organisms' activities. This process is essential for the growth of plants. Photosynthesis occurs in the chloroplasts of cells, where chlorophyll absorbs light energy and converts it into chemical energy through a series of reactions. The overall equation for photosynthesis can be written as: 6CO2 + 6H2O + light energy -> C6H12O6 + 6O2. This process is vital for the production of oxygen, which is necessary for the survival of most living organisms." eval_result, success = evaluate_with_llumo(prompt, response) if success: print("Llumo Evaluation Results:") for analytic, score in eval_result.items(): print(f"{analytic}: {score}") else: print("Evaluation with Llumo failed.") ``` # How to integrate LLUMO API and learn evaluation in your codebase? Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/integrate-api-code This document will guide you through integrating LLUMO AI API into your codebase and performing evaluations with both default and custom analytics. Follow the steps below to start using LLUMO AI's evaluation capabilities within your application. *** ## Overview LLUMO AI provides a powerful API that helps you evaluate and analyze text inputs. By sending a request to the LLUMO API, you can obtain evaluation metrics such as confidence, clarity, and context. You can also customize these evaluations by defining your own analytics criteria in your workspace. The following sections cover integration details, including how to integrate the LLUMO API into your code and customize the evaluation process. ## Integration Steps ### Step 1: Log In to LLUMO AI 1. Sign in to your LLUMO AI account [https://app.llumo.ai](https://app.llumo.ai) using your credentials. 2. Navigate to the "Eval LM" section and Go to “Connect API” where you can start the evaluation process for your AI model. 3. Now, copy the code and Setup prompt evaluation API in your codebase. ### Step 2: Install Required Libraries Before integrating LLUMO AI's API, ensure you have the `requests` library installed. You can install it using pip: ```bash theme={null} pip install requests ``` ### Step 3: Basic Setup To integrate LLUMO API into your code, you'll need to send a POST request to the endpoint provided by LLUMO AI. #### API Endpoint & Authorization * **API URL:** `https://app.llumo.ai/api/create-eval-analytics` * **Authorization:** Use your unique API token in the Authorization header. Replace `Bearer ` with your actual Bearer key. Example Header: ```python theme={null} headers = { "Authorization": "Bearer ", "Content-Type": "application/json" } ``` #### Request Body Format The request body is a JSON object where you provide essential parameters like your `workspaceID`, the `prompt`, `input`, and `output`. Example of default evaluation request: ```python theme={null} data = { "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "Germany" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain." } ``` **Explanation of fields:** * `prompt`: Text or question you want to analyze. * `input`: Language or other settings (currently only language is supported). * `output`: The result or analysis based on your input prompt. ### Step 4: Making the API Call Use the `requests.post()` method to send your data to the API. Below is a sample code that demonstrates how to make the request. Example Code: ```python theme={null} import requests # URL and headers url = "https://app.llumo.ai/api/create-eval-analytics" headers = { "Authorization": "Bearer ", "Content-Type": "application/json" } # Request body data = { "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "Germany" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain.", } # Make the POST request response = requests.post(url, headers=headers, json=data) # Output the response print("Status Code:", response.status_code) print("Response:", response.json()) ``` ### Default Evaluation Metrics Upon making a request to the LLUMO AI API, the response will include the following default evaluation metrics: * **Confidence:** Measures the confidence level of the generated output. * **Clarity:** Assesses the clarity of the generated text. * **Context:** Analyzes whether the output aligns with the context provided in the prompt. * **Overall Score:** A combined score based on the above metrics. Example Response: ```json theme={null} { "status": "success", "metrics": { "confidence": 0.92, "clarity": 0.85, "context": 0.88, "overallScore": 0.87 } } ``` ### Custom Evaluation Metrics If you want to evaluate your data based on custom-defined analytics in your workspace, you can add a custom analytics name to the request body. #### Adding Custom Analytics To specify custom analytics, include the `"analytics"` field in the request body with an array of your custom analytics names. Example: ```python theme={null} data = { "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "Germany" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain.", "analytics": ["Perplexity"] # Custom analytics } ``` In this case, `"Perplexity"` is a custom analytics name that you have set up in your workspace. #### Custom Analytics Configuration Before using custom analytics, ensure they are set up within your workspace on the LLUMO platform. If the analytics name is valid and configured, the API will return metrics for your custom analysis. You can refer to the guide on setting up custom analytics in the Custom Eval Playground [here](#). Example of Full API Call with Custom Analytics: ```python theme={null} import requests # URL and headers url = "https://app.llumo.ai/api/create-eval-analytics" headers = { "Authorization": "Bearer ", "Content-Type": "application/json" } # Request body with custom analytics data = { "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "Germany" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain.", "analytics": ["Perplexity"] # Custom analytics } # Make the POST request response = requests.post(url, headers=headers, json=data) # Output the response print("Status Code:", response.status_code) print("Response:", response.json()) ``` #### Sample Response for Custom Analytics ```json theme={null} { "status": "success", "analyticsScore": { "Perplexity": 0.89, "confidence": 0.91, "clarity": 0.87, "context": 0.84, "overallScore": 0.89 } } ``` ## Conclusion By following this documentation, you should be able to easily integrate LLUMO AI API into your codebase for evaluating text outputs. You can choose to use the default evaluation metrics or customize your evaluation by adding analytics configurations in your workspace. For any issues or further questions, consult the LLUMO AI API documentation or contact support for assistance. ## FAQ **Q. How can I use custom evaluation metrics with the LLUMO API?** A. To use custom evaluation metrics, you need to add the `analytics` field in the request body when making an API call. For example, you can specify custom metrics like `"Perplexity"` by including the following in the request body: ```json theme={null} "analytics": ["Perplexity"] ``` You can check our custom analytics support doc for more details. ``` ``` # How to Run Evaluation in Production? Source: https://docs.llumo.ai/llm-evaluation/how-to-docs/run-eval-prod "Running evaluation in production" refers to the process of continuously monitoring and assessing the performance of your AI models while they are being used in a real-world, operational environment (also known as "production"). In production, an AI model is actively being used to handle tasks like answering customer queries, making predictions, or processing data. Over time, the model’s performance may change due to various factors such as shifts in input data, changes in user behavior, or model drift. *** ## Prerequisites Before you begin, make sure that: * You have an active LLUMO AI account and access to the platform. * You have the necessary datasets and evaluation metrics defined for your AI models. * Make sure you have a working understanding of API integration or access to the user interface (UI) on your platform—check out our LLUMO AI guide on API to get started. ## Step 1: Log In to LLUMO AI 1. Sign in to your LLUMO AI account [here](https://app.llumo.ai) using your credentials. 2. Navigate to the "Eval LM" section and go to “Connect API” where you can start the evaluation process for your AI model. 3. Now, copy the code and set up prompt evaluation API in your codebase. ## Step 2: Hit the API for Evaluation In a production environment, you need to send requests to the evaluation API. This is where the evaluation of your text, image, or other data happens. * **API Call:** You'll be sending a request to the API endpoint with the required data (e.g., prompts, outputs). * **Request Type:** This is done via a POST request with a JSON payload. * **Endpoint:** [https://app.llumo.ai/create-eval-api](https://app.llumo.ai/create-eval-api) ## Step 3: Production Code Execution Once the API receives the request, it processes the input data and returns metrics like confidence, clarity, and context. These metrics will be used to analyze the output. * **API Output:** Metrics such as confidence, clarity, context, and overall score are generated by the API. * These responses from the API can be used in your own production code as well. Further, these are logged at LLUMO's end, which you can access in the "Logs" section. ## Step 4: View Logs in Real-Time In a production environment, all the API responses and metrics can be logged in real-time to keep track of performance and behavior. ## Step 5: Real-Time Analysis Using a Dashboard A dashboard interface for LLUMO AI's evaluation and monitoring system. Below is a detailed explanation of both screens: ### Screen 1: Evaluation Dashboard Overview #### Key Metrics Displayed * **Average Queries per User (Top Left)** * Indicates the average number of queries submitted by individual users over the selected timeframe (e.g., December 2024). * **Current Value:** 3 (with a 3% decline compared to the previous period). * **Use Case:** Helps track user engagement levels. * **Tokens per Query (Top Center)** * Displays the average token usage for each query. * **Current Value:** 764 (8% reduction compared to the prior period). * **Use Case:** Useful for managing token efficiency and optimizing costs. * **Returning Users Rate (Top Right)** * Shows the percentage of users who return to use the platform. * **Current Value:** 25% (4% improvement). * **Use Case:** A higher rate indicates better user retention and satisfaction. * **Overall Quality Score (Right Center)** * Represents the aggregate quality score for the model's performance. * **Current Value:** 85% (2% increase). * **Graph:** Provides a trend analysis of quality over time, enabling performance monitoring. #### Detailed Metrics * **Error Rate** * Measures error rates to assess AI performance. * **Current Value:** 7% (reduced by 3%). * **Use Case:** Lower score indicates better AI output and robust LLM pipeline. * **Refusal Rate** * Measures refusal rates to understand rejection trends. * **Current Value:** 6% (reduced by 12%). * **Use Case:** Lower score indicates better AI output and fewer declines to generate a response. * **Repeat Query** * Measures the frequency of repeated queries. * **Current Value:** 32% (increased by 8%). * **Use Case:** Lower score indicates a more effective response. * **Feedback Score** * Measures the quality of your interactions. * **Current Value:** Positive (73%) vs. Negative (27%). * **Use Case:** Provides qualitative insight into user satisfaction. #### Additional Metrics * **Model-Wise Error & Refusal Rates** * Breaks down performance metrics across different models (e.g., GPT-4, Gemini-Pro). * **Use Case:** Measure performance by analyzing error and refusal rates per model. * **Completion Rate Per Task** * Visualizes how well the system performs across distinct task categories (e.g., "Can", "Do"). * **Use Case:** Measure completion rate per task to gauge efficiency. ### Screen 2: Evaluation and Insights #### Evaluation Section * **Error and Refusal Rate Comparisons Across Models** * Models include GPT-3.5 Turbo, GPT-4, Gemini-Pro, and custom solutions. * Graphs compare error rates (e.g., some errors that don't lead to any response) and refusal rates (e.g., queries declined by models). * **Use Case:** Model benchmarking to identify the most effective system. * **Insights and Recommendations** * The insights highlight areas of concern in the generated responses and compare them to industry benchmarks. * **Metrics:** A percentage of responses falling below the respective benchmark for correctness (70%), relevancy (72%), and coherence (62%). * **Time Period:** Data is drawn from 1st to 30th September, providing a specific evaluation period. * **"See in Playground" Buttons:** These buttons suggest the ability to test or refine model outputs interactively, providing an actionable follow-up for users. ### Log Section #### Logged Queries Table **Fields:** * **Prompt:** User-submitted input or request. * **Output:** Model's response to the prompt. * **Model:** Name of the model used to generate the output. * **Provider:** Indicates the service provider (e.g., OpenAI, VertexAI). * **Input/Output Tokens:** Number of tokens in the query and response. * **Total Tokens:** Combined tokens used (input + output). * **Response Time:** Time taken to generate a response. **Use Case:** This section provides traceability for analyzing system responses and optimizing token usage and latency. Running evaluation in production is an essential step to ensure your AI models perform well in real-world situations. Over time, models can lose accuracy due to changes in data or user behavior, but with LLUMO AI, you can easily monitor and improve your model’s performance. By following the steps outlined in this guide, you can identify issues quickly, make improvements, and keep your AI systems running effectively. LLUMO AI makes this process simple with its user-friendly tools, detailed metrics, and automation options, helping you maintain reliable and high-quality AI models. # Setup Prompt Evaluation API Source: https://docs.llumo.ai/llm-evaluation/setup/api Use LLUMO AI's proprietary technology to evaluate LLM output and gain insights. ## Getting Started with Prompt Evaluation API This guide provides step-by-step instructions on setting up prompt evaluation API, that helps your evaluate your prompt output and gives you insights. ### 1. Open evaluation setup modal The "Evaluation setup modal" provides your essential connection details: API endpoint, key, and sample request bodies. This ensures a smooth setup for compressing your prompts. After login to LLUMO for the first time, you will see a modal asking you to select the journey - Cost saving and Evaluation. You need to select the Evaluation option. If you have already selected the Compressor option, no worries. If you see the left navigation bar, you will see the Evaluation option. Then you can see a banner on the top of the page, asking you to set up. Click on “Setup Now” Now, you can see the setup modal for the evaluation. If you are not able to see the below modal, [contact our support team](mailto:product@llumo.ai). If you close the modal window, you can access it again by clicking “Setup Now” CTA on the banner at the top of the page. ### 2. Access your API keys The API keys equips you with the credentials needed to connect with Prompt Compression API. This unlocks the power to evaluate your prompts output and gives you hidden insight without any need of ground truth. We suggest you to keep your API keys very safely. If you experience any misuse, [contact our support team](mailto:product@llumo.ai). The setup modal provides an overview of Evaluation and a "Connect Now" CTA. Click on "Connect Now" and it will open the API connection detail modal * API endpoint: The URL you will use to send requests to the Evaluation API. * API key: Your unique API key, which is required for authentication. You will be given one API key by default. But, if you want to create multiple API keys, refer to [managing your keys](https://docs.llumo.ai). Examples of codes containing request bodies in different languages is provided, that you can use to send a request to the Evaluation API. Copy the sample code block and paste into editor of your choice. Below is an example of sample code block in python. ```python compressPrompt.py theme={null} import requests url = "https://app.llumo.ai/api/create-eval-analytics" payload = { "prompt": "", "prompt": "", "input": "", output: "", analytics: "", } headers = { "Content-Type": "application/json" "Authorization": "Bearer " } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) ``` The request body includes the following important parameters: * prompt: (Mandatory) The text prompt you want to compress. * input: List of placeholders used inside prompt. When there are more than one placeholder then this will be list. * output: The output of the prompt. * analytics: List of analytics you want to evaluate your prompt output on. Here is an example of these parameters. ```json theme={null} "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "India" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain. Day 4-6: Munich Day 4: Travel to Munich, the capital of Bavaria. Upon arrival, visit the Marienplatz and watch the famous Glockenspiel chime at the New Town Hall. Explore the nearby Viktualienmarkt for some Bavarian delicacies. Day 5: Immerse yourself in Bavarian culture with a visit to the Nymphenburg Palace and the Munich Residenz. In the afternoon, head to the Englischer Garten, one of the world's largest urban parks, for a leisurely stroll. Day 6: Take a day trip to Neuschwanstein Castle, one of the most picturesque castles in the world. It's about a two-hour drive from Munich, but the stunning views of the Bavarian countryside and the fairy-tale castle are well worth it. Day 7-9: Heidelberg and the Rhine Valley Day 7: Travel to Heidelberg, a charming university town known for its romantic castle overlooking the Neckar River. Explore the old town, visit the Heidelberg Castle, and stroll along the Philosopher's Walk for panoramic views of the city. Day 8: Embark on a scenic cruise along the Rhine River, passing by medieval castles, vineyards, and quaint villages. Stop by the town of Rüdesheim to sample some local wines. Day 9: Explore more of the Rhine Valley region or head back to Frankfurt for departure, depending on your schedule. Tips: Transportation: Consider purchasing a German Rail Pass if you plan to travel extensively by train. It offers unlimited travel on Germany's extensive rail network. Language: While many Germans speak English, learning a few basic phrases in German can enhance your experience and show respect for the local culture. Weather: Check the weather forecast before your trip and pack accordingly, especially if you're visiting during the colder months. This itinerary offers a mix of history, culture, and natural beauty, giving you a well-rounded experience of Germany. Safe travels!", "analytics": ["clarity", "confidence"] ``` For fine-grained control over analytics and no ground truth, explore the optional parameters within the request body. These parameters allow you to tailor metrics to your specific needs and visualize cost breakdowns on the dashboard. For a detailed breakdown on the API request and response, please refer to the [API reference page](https://docs.llumo.ai/cost-saving/api-reference/compress-prompt-api). ### 3. Send first request to Evaluation API Once you have your request setup for a sample body, you can send a request to the Evaluation API to evaluate your own prompts output based on selected metrics. 1. Open your directory where LLM project reside in editor of your choice. 2. Edit the sample code snippet you copied from LLUMO setup modal. 3. Replace the placeholder values for prompt and topic with your specific prompt and topic. 4. Include your API key in the header of the request. 5. Run the code snippet. You can find detailed instructions on setting up the API in your code on the dedicated [guide page](https://docs.llumo.ai/cost-saving/how-to-docs/compress-first-prompt). For a more interactive experience, we recommend using API testing tools like Postman or Thunder Client. Below is the step-by-step detailed video explaining the complete process. API testing tools After sending the request, you can view the logs and metrics generated on the dashboard to see how the evaluation process performed. This information can help you optimize your requests for better results. ### All Done! Congrats! You've set up your LLUMO's Prompt Evaluation API and it has started evaluating your prompt outputs with each inference! If you encounter any difficulties while setting up, please refer to the troubleshooting section of the guide or, contact our support team at [connect@llumo.ai](mailto:connect@llumo.ai). ``` ``` # Observe Source: https://docs.llumo.ai/observe LLUMO AI Observe is a dashboard designed to monitor 360° LLM performance in real time. By providing an in-depth view of each and every point across your LLM workflow, Observe helps businesses to visualize the performance of AI workflows and helps to pin point the exact issues. *** ## Why You Need LLUMO AI Observe If you often struggle with: * **Lack of Visibility** – No clear insights on how your LLM workflows * **Inconsistency** – Unpredictable responses due to unmonitored model drifts. * **Scalability** – Performance degrades as queries increase. * **High AI costs** – Inefficient prompts and excessive API calls drive up expenses. * **Output Quality** – No structured way to track biases, hallucinations, or security issues. *** ## Core Features ### 360° LLM Monitoring Dashboard Track LLM responses in real time with a unified dashboard that visualizes performance trends, failure points, and cost breakdowns. ### End-to-End LLM Pipeline Visibility Observe how inputs are processed at each stage, ensuring transparent and predictable AI behavior. ### Cost Optimization & Resource Efficiency Reduce AI operational expenses by tracking token usage, identifying redundant API calls, and optimizing prompt efficiency. *** ## Exploring the LLUMO AI Observe Dashboard The LLUMO AI Observe dashboard provides a real-time snapshot of LLM performance. Key widgets include: * **Response Accuracy** → Tracks the correctness and reliability of AI-generated responses. A higher accuracy indicates fewer hallucinations and better AI performance. * **Response Time** → Measures the latency of AI responses. Faster response times enhance user experience, especially for real-time applications like chatbots and AI assistants. * **User Satisfaction** → Displays positive vs. negative feedback from users interacting with the AI. A high satisfaction rate suggests effective and useful AI responses. * **User Engagement** → Measures how actively users interact with the AI, reflecting adoption and usability. A percentage increase shows growing engagement. * **Escalation Rate** → Indicates how often AI fails to resolve queries, leading to human intervention. A lower percentage is desirable. The percentage increase suggests potential performance issues. * **Fallback Rate** → Tracks how often the AI fails to generate a meaningful response and falls back to predefined responses. High fallback rates may indicate incomplete training or ineffective prompt engineering. * **Query Volume** → Monitors AI usage trends. An increased percentage suggests growing adoption or increased demand for AI interactions. * **User Recognition Rate** → Measures how well the AI identifies returning users or understands user queries. An improvement percentage signals better personalization and recognition. * **First Contact Resolution** → Measures how effectively AI resolves queries in the first interaction without requiring follow-ups. A higher FCR boosts efficiency. * **Intent Recognition Rate** → Evaluates how well AI understands user intent. A high rate suggests strong NLP capabilities and effective intent classification. * **Conversation Completion Rate** → Shows how many AI-driven conversations reach a natural resolution. A declining rate may indicate users dropping off due to poor responses. * **Sentiment Analysis** → Analyzes the sentiment of AI-generated responses and user feedback. Helps in identifying areas of improvement. * **Hallucination Rate** → Tracks how often the AI generates inaccurate or misleading responses. Lower rates indicate higher reliability. A positive trend suggests ongoing improvements. *** ## How to Start with LLUMO AI Observe ### Step 1: Log Your Observations Integrate LLUMO AI Observe into your system to track live model interactions. Define critical monitoring metrics such as latency, accuracy, and hallucination rates. ### Step 2: Analyze Performance Trends Click on the LLUMO Observe button to see real-time visualization, pinpoint failures, identify efficiency gaps, and analyze model drift over time. SETUP OBSERVE *** ## FAQ **Q. What is LLUMO AI Observe?**\ LLUMO AI Observe is a real-time monitoring platform that helps teams track, analyze, and optimize their LLM applications across an entire pipeline. **Q. How does LLUMO AI Observe improve LLM performance?**\ It provides: * Live dashboards for tracking performance trends. * Anomaly detection to prevent model drift. * Cost optimization insights to improve efficiency. **Q. What monitoring metrics are available in LLUMO AI Observe?** * **Prebuilt Metrics:** Latency, accuracy, hallucination rate, API cost. * **Custom Metrics:** Define KPIs based on specific use cases. **Q. Can LLUMO AI Observe help reduce AI costs?**\ Yes! It tracks token usage, API expenses, and inefficient prompts to lower operational costs. **Q. How can I track model performance over time?**\ LLUMO AI Observe logs all monitoring data, allowing users to compare trends and fine-tune their AI models continuously. API DOCUMENTATION # Optimize Source: https://docs.llumo.ai/optimise LLUMO AI Optimize recommends Next Step for targeted corrective actions based on insights from LLUMO AI Observe. By providing detailed performance analysis and actionable recommendations, Optimize ensures LLMs remain efficient, accurate, and cost-effective. *** ## Why You Need LLUMO AI Optimize If your LLM struggles with: * **Low Accuracy** – Responses frequently deviate from expected outputs. * **High Token usage** – Inefficient responses increasing operational costs. * **Poor Coherence** – Answers lack logical flow and semantic consistency. * **Excessive Refusals** – Overly cautious models rejecting valid queries. * **Delayed Response** – High latency impacting user experience. *** ## Core Features * **Insight-Driven Performance Recommendations**\ Optimize analyzes error patterns, feedback trends, and token usage to provide precise recommendations for improvement. * **Targeted Model Adjustments**\ Receive specific tuning suggestions for prompt engineering, model fine-tuning, and system-level optimizations. * **Automated Cost Efficiency Insights**\ Identify redundant API calls, unnecessary token consumption, and alternative approaches to reduce expenses. * **Enhanced LLM Output Alignment**\ Improve accuracy, coherence, and completeness through structured insights and data-driven refinement techniques. *** ## Insights & Recommendations: Optimizing LLM Performance LLUMO AI’s Optimize helps pin point performance gaps, and provides actionable next steps. * **Answer Correctness Insights**\ Detects factual inconsistencies and suggests refining training data or incorporating retrieval-augmented generation. * **Conciseness Optimization**\ Highlights excessive verbosity and recommends optimizing responses for clarity and efficiency. * **Coherence Analysis**\ Identifies logical gaps and advises on prompt alignment and scoring mechanisms. * **Cost Efficiency Breakdown**\ Tracks token usage and suggests cost-reducing strategies like shorter prompts or alternative API usage. * **Model Comparison Analysis**\ Evaluates multiple LLMs side by side, pinpointing which models perform best for specific tasks. *** ## Using LLUMO AI Optimize to Improve LLMs ### Step 1: Setup API calls to connect with LLUMO AI Once connected, LLUMO AI Optimize will automatically detect failure points in your LLM workflows such as frequent errors, low-confidence responses, and other inefficiencies.\ Then LLUMO AI Optimize will automatically provide recommendations to solve the issues that are found in the LLM workflows. ### Step 2: Apply Recommendations Adjust prompts, fine-tune models, or modify API configurations based on Optimize’s recommendations.\ Implement cost-saving techniques and prompt refinements to reduce token usage. ### Step 3: Validate Improvements Deploy optimized models and track performance changes using LLUMO AI Observe.\ Iterate based on real-time data to ensure continued improvements. *** ### Final Takeaway: LLUMO AI Optimize = Smarter AI Result Turn performance insights into actionable improvements with LLUMO AI Optimize. Ensure your AI models are accurate, efficient, and cost-effective. *** SETUP LLUMO AI OPTIMIZE *** ## FAQ **1. What is LLUMO AI Optimize?**\ LLUMO AI Optimize is a performance enhancement module that provides targeted recommendations to improve LLM efficiency, accuracy, and cost-effectiveness. It analyzes insights from LLUMO AI Observe and suggests actionable next steps to refine AI models. **2. Why do I need LLUMO AI Optimize?**\ If your LLM is experiencing low accuracy, high token usage, poor coherence, excessive refusals, or delayed responses, LLUMO AI Optimize helps: * Improve accuracy by detecting factual inconsistencies. * Reduce costs by optimizing token consumption. * Enhance coherence for logical and structured responses. * Lower response time by refining API interactions. **3. How does LLUMO AI Optimize work?**\ LLUMO AI Optimize analyzes error patterns, token usage, and feedback trends to provide: * Insight-driven performance recommendations for better prompt engineering and model fine-tuning. * Targeted model adjustments to enhance AI response accuracy. * Automated cost-efficiency insights to reduce redundant API calls and unnecessary token use. **4. Does LLUMO AI Optimize support all LLM providers?**\ Yes! LLUMO AI Optimize is compatible with all major LLMs, including OpenAI, Gemini, and custom-trained models. **5. How much does LLUMO AI Optimize reduce costs?**\ Optimize can help reduce token usage by up to 80%, cutting down on unnecessary expenses while maintaining output quality. **6. How often should I use LLUMO AI Optimize?**\ For best results, continuous optimization is recommended. Run it regularly to adapt to model updates, changing datasets, and evolving business needs. **7. How do I get started?**\ Simply connect your API to LLUMO AI Optimize, and it will automatically start analyzing and providing recommendations. # OptiSave Source: https://docs.llumo.ai/optisave OptiSave is an advanced AI-driven tool meticulously designed by LLUMO AI’s in-house AI engineers to optimize and streamline the performance of Large Language Models (LLMs). It acts as a powerful intermediary between AI users and LLMs, ensuring that interactions with the model are more efficient, cost-effective, and precise. At LLUMO AI, we are committed to helping businesses to build trustworthy, high-performance, and cost-effective AI solutions. Our research team works tirelessly to assist organizations in overcoming their biggest hurdles related to generative AI evaluation, experimentation, monitoring, and optimization. We understand the challenges involved in deploying AI at scale, and OptiSave was designed specifically to alleviate these complexities by making AI interactions more seamless and resource-efficient. ## Days of Struggle, Moments of Triumph: The Birth of OptiSave OptiSave is the answer to the inefficiencies you’ve been battling. The skyrocketing token usage. The frustrating delays. The costs that just wouldn’t quit. We fixed it. Modern AI applications demand high efficiency, but interacting with LLMs can often lead to excessive token usage, increased latency, and higher operational costs. OptiSave addresses these challenges by compressing input prompts, optimizing token usage, and improving latency, overall model responsiveness by reducing hallucination — without sacrificing one ounce of accuracy. And we did it all without breaking a sweat. See what's possible when perseverance meets innovation—when the impossible becomes achievable—look no further than OptiSave. *** ## Core Objectives of OptiSave: OptiSave is designed to address several key challenges faced by businesses when interacting with Large Language Models (LLMs). Its core objectives focus on optimizing AI model interactions by improving efficiency, reducing costs, and enhancing the overall quality of generated outputs. Below is a detailed breakdown of each core objective: ### 1. Upto 80% Cost Reduction: One of the primary objectives of OptiSave is to compress input prompt usage while retaining the full meaning of the original input prompt. In the context of LLMs, a "token" represents a unit of text, and the more tokens an input contains, the greater the computational resources required to process it. Tokenization can increase the cost of API usage and may lead to slower processing times if the inputs are too large. API costs for using LLMs are often directly tied to the number of tokens sent to and generated by the model. Since large inputs and long outputs can quickly add up in terms of cost, minimizing token usage is a significant concern for businesses operating on a budget. #### How Cost Reduction Works: OptiSave employs advanced techniques like Token reduction, cache management and quality management to compress the input prompt. This involves identifying and eliminating redundant words, phrases, or parts of the input that do not contribute significantly to the model’s understanding. #### How LLUMO AI Optimizes Tokens & Saves Costs at Scale **What is a Token & How is it Calculated?** A token is a unit of text processed by a language model. It can be a word, a part of a word, or even a punctuation mark. LLMs charge based on the number of tokens used per query, meaning longer prompts = higher costs. Optimizing token usage can drastically reduce your expenses. #### Example **Without OptiSave** ``` Query: "Provide a comprehensive report on the impact of artificial intelligence across industries, including automation trends, economic changes, workforce adaptation, regulatory challenges, and ethical considerations. Also, include case studies, expert opinions, and predictions for the next decade." Context: “Knowledgebase” Input Tokens = Tokens in “Query” + “Context” Assuming Input Tokens = 2,000 ``` **With OptiSave** ``` Precise Query: "Summarize AI’s impact on industries, including automation, economy, workforce, regulations, and ethics." Precise Context: “Knowledgebase” Input Tokens = Tokens in “Precise Query” + “Precise Context” Input Tokens using OptiSave = 873 tokens ``` #### Token Reduction & Cost Savings ``` - 2,000 tokens → 873 tokens (56.35% reduction) - Assumed cost per token: $0.0001 ``` **Without Optisave:** ``` 2,000 tokens × $0.0001 = $0.20 per query ``` **With Optisave:** ``` 873×0.0001=$0.0873 per query ``` **Total Cost Savings Per Query:** ``` 0.20−0.0873=$0.1127 per query (56.35% reduction) ``` **Impact at scale** ``` If running 500,000 queries per month: - Without Optisave: 500,000×0.20=$100,000 per month - With OptiSave: 500,000×0.0873=$43,650 per month ``` **Total Monthly Savings:** ``` 100,000−43,650=$56,350 saved per month ``` **Annual Savings:** ``` 56,350×12=$676,200 saved per year ``` LLUMO AI helps teams experiment, observe, and optimize LLM usage—so you get high-quality outputs at a fraction of the cost.\ See how real teams are cutting costs with LLUMO AI: LLUMO Case Study \#AI #LLMOps #CostOptimization #GenerativeAI #TokenEfficiency #AIOptimization #### Benefits: * **Lower Operational Costs:** By cutting down on token usage, OptiSave directly lowers the API costs associated with each interaction. * **Reduced Token Usage:** By compressing inputs without losing meaning, OptiSave ensures that fewer tokens are sent to the model. * **More Predictable Budgeting:** With reduced token consumption, businesses can more accurately forecast and manage AI-related expenses. *** ### 2. Improved Latency: Response time is a critical factor for many real-time AI applications. High latency can be frustrating for users and can impact the overall user experience, especially in interactive environments like chatbots or customer support systems. Reducing the time it takes for an AI model to generate a response is crucial for improving performance. #### How Latency Optimization Works: OptiSave addresses latency by reducing computational overhead. By compressing inputs and eliminating unnecessary complexity, OptiSave allows the model to process requests faster. Furthermore, the tool intelligently refines input prompts to ensure that the model’s response generation process is as streamlined as possible, minimizing the time required to generate a high-quality output. #### Example: Improve Latency with Optisave **Without Optisave:** ``` Query: "Provide a detailed technical breakdown of quantum computing, including superposition, entanglement, and qubits, along with its potential applications in cryptography, medicine, logistics, artificial intelligence, and other industries. Additionally, discuss the challenges, future research areas, and expert predictions for the next two decades." Context: “Knowledgebase” Input Tokens = Tokens in “Query” + “Context” Assuming Input Tokens = 2,000 Processing Time: 10 seconds Tokens Generated: 2,000 tokens ``` **With Optisave:** ``` Query: "Summarize how quantum computing works and its key industrial applications." Context: “Knowledgebase” Input Tokens = Tokens in “Query” + “Context” Assuming Input Tokens = 873 Processing Time: 5 seconds Tokens Generated: 500 tokens ``` #### Latency & Efficiency Gains * **Processing Time Reduced by 50%** ``` 10 seconds → 5 seconds ``` * **Tokens Reduced by 56.33%** ``` 2,000 tokens → 873 tokens ``` **Latency Improvement:** ``` Response time reduced by 50%, from 10 seconds to 5 seconds. ``` **Cost of Delay:** ``` In real-time applications like customer support chatbots, reducing response time by 5 seconds can improve engagement and reduce user frustration. For 100,000 interactions per day, faster response times lead to increased user satisfaction and better engagement. ``` #### Benefits: * **Faster Response Times:** Reducing the number of tokens to process and streamlining the input prompts results in quicker response times, providing a smoother and more efficient user experience. * **Improved User Experience:** In environments where real-time interactions are essential, reducing latency can significantly improve customer satisfaction and engagement. *** ### 3. Reduce Hallucinations: Hallucinations refer to instances when AI models generate responses that are misleading, inaccurate, or completely false. These errors can be particularly problematic in domains where precision and reliability are critical. Minimizing hallucinations is essential to ensure the trustworthiness and quality of the generated outputs. #### How to reduce Hallucinations: OptiSave tackles hallucinations by improving the clarity and precision of input prompts. Through advanced prompt engineering, it ensures that the model receives clear, concise, and well-structured input. This clarity reduces the likelihood of misinterpretation by the model, which is one of the common causes of hallucinations. Additionally, OptiSave may incorporate mechanisms to provide models with more specific context or grounding information, thereby reducing ambiguity and improving the accuracy of responses. #### Example: **Without Optimization:** ``` Query: "Tell me about the economic impacts of the Mars rover." Output: "The Mars rover has significantly impacted global economies by leading to technological advancements in several industries." **Hallucination:** The economic impact of the Mars rover on global economies is not a verified fact. ``` **With OptiSave Optimization:** ``` Query: "Describe the technological impacts of the Mars rover on various industries." Output: "The Mars rover led to innovations in robotics and materials science, which have applications in industries such as aerospace and healthcare." **Accurate Output:** This response is factually grounded and accurate. ``` **Cost of Hallucinations:** ``` By reducing hallucinations by just 5%, you can significantly improve the reliability of your AI outputs, saving businesses potentially millions of dollars in miscommunication costs. ``` #### Benefits: * **Enhanced Accuracy:** Clearer and more specific inputs reduce the likelihood of the model generating inaccurate or misleading outputs. * **Increased Trust:** By minimizing hallucinations, OptiSave helps ensure that AI outputs are more reliable, which is particularly important in professional settings where accuracy is paramount. *** ## How to Use OptiSave ### Prerequisites: Make sure you are in the Experiment section of the product and have some data ready for testing (either your own data or sample data). ### Step 1: Access OptiSave Click on OptiSave on the right-hand side (RHS) of the Experiment section.\ A new side menu will appear. ### Step 2: Configure Your Column Enter a Column Name to label your experiment. ### Step 3: Choose Your Prompting Method You have two options: * **Write Prompt** – You can manually enter a prompt to generate responses. * **Smart Prompt** – This option enables automatic prompt optimization.\ You can select both checkboxes if you want to generate two separate columns using both methods. ### Step 4: Select Provider & Model Under Select Provider, choose the AI provider (e.g., OpenAI).\ Under Select Model, pick the AI model you want to use. ### Step 5: Run the Experiment Click on **Create And Run All Column** to execute the experiment. ### Step 6: Review the Results **Add Image related to this 4 column** After running the experiment, four new columns will be generated in the experiment table: * **Compressed Input** – An optimized version of the original input prompt. * **Output** – The response generated via OptiSave. * **Cost** – The cost incurred for generating this output. * **Saving** – A percentage comparison of cost savings with and without OptiSave. Now, you’re all set to optimize and analyze your AI-generated responses efficiently with OptiSave!\ By following these steps, you can seamlessly integrate and measure the impact of OptiSave in optimizing your AI models for performance, cost-efficiency, and response quality. *** ## FAQs 1. **What is OptiSave used for?**\ OptiSave is designed to optimize prompts, reduce costs, and improve AI efficiency through automated compression techniques. 2. **Can I use OptiSave with any model?**\ Yes, OptiSave supports various LLMs and can be applied across different AI models. 3. **How does OptiSave help in cost reduction?**\ By compressing input prompts, OptiSave minimizes token usage, leading to lower processing costs without sacrificing performance. 4. **Will OptiSave affect output quality?**\ No, OptiSave is designed to maintain or even enhance output quality while optimizing efficiency. With reduced input tokens, content becomes more precise, which helps in reducing hallucinations. 5. **How does OptiSave help in reducing hallucinations?**\ OptiSave refines input prompts and compresses content, ensuring more precise instructions for the model. This reduces ambiguity and minimizes the chances of generating hallucinated or irrelevant responses. 6. **How does OptiSave improve latency?**\ By reducing input token size and optimizing outputs, OptiSave decreases data processing time. This leads to faster response generation and improved real-time performance. 7. **How do I track my optimizations?**\ OptiSave provides real-time tracking and logs all improvements in the Experiment section for easy comparison. By following these steps, users can effectively leverage OptiSave to refine their AI models, enhance performance, and achieve cost efficiency seamlessly. # Quickstart Source: https://docs.llumo.ai/quickstart Reduce LLM cost and gain 360° insights of your LLM outputs. ## Reduce Cost LLUMO compresses your tokens to build production ready AI at 50% cost and 10x speed. Compress your prompt by 70% before passing to LLMs. Connect to LLUMO API and reduce cost by 50%. Save cost in OpenAI API calls using LLUMO compressor API. Save cost in Google Vertex pipeline using LLUMO compressor API. Save cost in Langchain pipeline using LLUMO compressor API. Save cost in Llama Index pipeline using LLUMO compressor API. ## Evaluate LLMs The only customizable LLMs evaluation tool to gain 360° insights into your AI output quality. Evaluate & compare all universal language models at one place. Use LLUMO AI’s proprietary technology to evaluate output from OpenAI GPT models. Use LLUMO AI's proprietary technology to evaluate LLM output and gain insights. Use LLUMO AI’s proprietary technology to evaluate output from Google Gemini models. # Setup prompt compression API Source: https://docs.llumo.ai/setup-llumo/setup-cost-saving/api Start cutting AI cost in just 2 minutes ## Getting Started with Prompt Compression API This guide provides step-by-step instructions on setting up prompt compression API, that compresses input prompts before passing it to LLMs, helping you save cost and reduce inference speed. ### 1. Open compressor setup modal The "Compressor setup modal" provides your essential connection details: API endpoint, key, and sample request bodies. This ensures a smooth setup for compressing your prompts. If you've already done demo call and got the access to the LLUMO app, this step is complete. If you are a new user for [LLUMO AI](https://www.llumo.ai), please refer to [Create Account](https://docs.llumo.ai/setup-llumo/create-account) and [Activate your account](https://docs.llumo.ai/setup-llumo/activate-account) After you have access and you login to LLUMO for the first time, you will see a modal asking you to select the journey - Cost saving and Evaluation. You need to select the Cost Saving option. If you have already selected the Evaluation option, no worries. If you see the left navigation bar, you will see the compressor option. Then you can see a banner on the top of the page, asking you to set up. Click on “Setup Now” Now, you can see the setup modal for the compressor. If you are not able to see the below modal, [contact our support team](mailto:product@llumo.ai). If you close the modal window, you can access it again by clicking “Setup Now” CTA on the banner at the top of the page. ### 2. Access your API keys The API keys equips you with the credentials needed to connect with Prompt Compression API. This unlocks the power to compress your prompts and experience cost savings. We suggest you to keep your API keys very safely. If you experience any misuse, [contact our support team](mailto:product@llumo.ai). The setup modal provides an overview of Compressor and a "Connect Now" CTA. Click on "Connect Now" and it will open the API connection detail modal * API endpoint: The URL you will use to send requests to the Compressor API. * API key: Your unique API key, which is required for authentication. You will be given one API key by default. But, if you want to create multiple API keys, refer to [managing your keys](https://docs.llumo.ai). Examples of codes containing request bodies in different languages is provided, that you can use to send a request to the Compressor API. Copy the sample code block and paste into editor of your choice. Below is an example of sample code block in python. ```python compressPrompt.py theme={null} import requests url = "https://app.llumo.ai/api/compress" payload = {"prompt": ""} headers = { "Content-Type": "application/json" "Authorization": "Bearer " } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) ``` The request body includes the following important parameters: * prompt: (Mandatory) The text prompt you want to compress. * topic: (Optional) The topic of the prompt. We highly recommend providing a topic for better compression results. Here is an example of these two parameters. ```json theme={null} "prompt": "In a forgotten corner of the universe, a nomadic tribe journeys across a desolate wasteland on colossal, bio-engineered sandworms. These colossal creatures, revered as both gods and transportation, are on the verge of extinction due to a mysterious blight. A young rider, ostracized for their curiosity about the world beyond the sand, discovers a hidden cache of ancient technology. This technology offers a glimmer of hope for saving the sandworms, but it also unlocks forbidden knowledge that threatens to shatter the tribe's long-held beliefs. Torn between tradition and the promise of progress, the young rider must embark on a perilous quest to uncover the truth about the blight and the tribe's origins. Their journey will lead them to face colossal sand creatures, navigate treacherous landscapes, and confront a powerful ruling class determined to maintain the status quo. Will they succeed in saving the sandworms and their people, or will they succumb to the dangers that lie hidden beneath the sands? Write a story about their fight for survival and the burden of knowledge." "topic": "What are the potential consequences of the young rider's choice between tradition and progress in saving the sandworms?" ``` For fine-grained control over logging and cost visualization, explore the optional parameters within the request body. These parameters allow you to tailor metrics to your specific needs and visualize cost breakdowns on the dashboard. For a detailed breakdown on the API request and response, please refer to the [API reference page](https://docs.llumo.ai/cost-saving/api-reference/compress-prompt-api). ### 3. Send first request to Prompt Compression API Once you have your request setup for a sample body, you can send a request to the Compressor API to compress your own prompts. 1. Open your directory where LLM project reside in editor of your choice. 2. Edit the sample code snippet you copied from LLUMO setup modal. 3. Replace the placeholder values for prompt and topic with your specific prompt and topic. 4. Include your API key in the header of the request. 5. Run the code snippet. You can find detailed instructions on setting up the API in your code on the dedicated [guide page](https://docs.llumo.ai/cost-saving/how-to-docs/compress-first-prompt). For a more interactive experience, we recommend using API testing tools like Postman or Thunder Client. Below is the step-by-step detailed video explaing the complete process. API testing tools After sending the request, you can view the logs and metrics generated on the dashboard to see how the compression process performed. This information can help you optimize your requests for better results. ### All Done! Congrats! You've set up your LLUMO's Prompt Compression API and it has started saving your cost with each inference! If you encounter any difficulties while setting up, please refer to the troubleshooting section of the guide or, contact our support team at [connect@llumo.ai](mailto:connect@llumo.ai). ``` ``` # Setup Prompt Evaluation API Source: https://docs.llumo.ai/setup-llumo/setup-evaluation/api Use LLUMO AI's proprietary technology to evaluate LLM output and gain insights. ## Getting Started with Prompt Evaluation API This guide provides step-by-step instructions on setting up prompt evaluation API, that helps your evaluate your prompt output and gives you insights. ### 1. Open evaluation setup modal The "Evaluation setup modal" provides your essential connection details: API endpoint, key, and sample request bodies. This ensures a smooth setup for compressing your prompts. After login to LLUMO for the first time, you will see a modal asking you to select the journey - Cost saving and Evaluation. You need to select the Evaluation option. If you have already selected the Compressor option, no worries. If you see the left navigation bar, you will see the Evaluation option. Then you can see a banner on the top of the page, asking you to set up. Click on “Setup Now” Now, you can see the setup modal for the evaluation. If you are not able to see the below modal, [contact our support team](mailto:product@llumo.ai). If you close the modal window, you can access it again by clicking “Setup Now” CTA on the banner at the top of the page. ### 2. Access your API keys The API keys equips you with the credentials needed to connect with Prompt Compression API. This unlocks the power to evaluate your prompts output and gives you hidden insight without any need of ground truth. We suggest you to keep your API keys very safely. If you experience any misuse, [contact our support team](mailto:product@llumo.ai). The setup modal provides an overview of Evaluation and a "Connect Now" CTA. Click on "Connect Now" and it will open the API connection detail modal * API endpoint: The URL you will use to send requests to the Evaluation API. * API key: Your unique API key, which is required for authentication. You will be given one API key by default. But, if you want to create multiple API keys, refer to [managing your keys](https://docs.llumo.ai). Examples of codes containing request bodies in different languages is provided, that you can use to send a request to the Evaluation API. Copy the sample code block and paste into editor of your choice. Below is an example of sample code block in python. ```python compressPrompt.py theme={null} import requests url = "https://app.llumo.ai/api/create-eval-analytics" payload = { "prompt": "", "prompt": "", "input": "", output: "", analytics: "", } headers = { "Content-Type": "application/json" "Authorization": "Bearer " } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) ``` The request body includes the following important parameters: * prompt: (Mandatory) The text prompt you want to compress. * input: List of placeholders used inside prompt. When there are more than one placeholder then this will be list. * output: The output of the prompt. * analytics: List of analytics you want to evaluate your prompt output on. Here is an example of these parameters. ```json theme={null} "prompt": "I am planning a trip to {{location}}, give me a travel plan", "input": { "location": "India" }, "output": "Absolutely, Germany is a wonderful destination with a rich history, diverse culture, and beautiful landscapes. Here's a suggested travel plan for a memorable trip: Day 1-3: Berlin Day 1: Arrive in Berlin, check into your accommodation, and get acquainted with the city. Visit iconic landmarks such as the Brandenburg Gate, the Reichstag Building, and Checkpoint Charlie. Day 2: Explore Berlin's cultural scene. Visit Museum Island, home to several world-renowned museums including the Pergamon Museum and the Altes Museum. Take a stroll along the East Side Gallery to see remnants of the Berlin Wall adorned with street art. Day 3: Dive deeper into Berlin's history with a visit to the Holocaust Memorial and the Topography of Terror museum. Spend the evening exploring the vibrant nightlife of neighborhoods like Kreuzberg or Friedrichshain. Day 4-6: Munich Day 4: Travel to Munich, the capital of Bavaria. Upon arrival, visit the Marienplatz and watch the famous Glockenspiel chime at the New Town Hall. Explore the nearby Viktualienmarkt for some Bavarian delicacies. Day 5: Immerse yourself in Bavarian culture with a visit to the Nymphenburg Palace and the Munich Residenz. In the afternoon, head to the Englischer Garten, one of the world's largest urban parks, for a leisurely stroll. Day 6: Take a day trip to Neuschwanstein Castle, one of the most picturesque castles in the world. It's about a two-hour drive from Munich, but the stunning views of the Bavarian countryside and the fairy-tale castle are well worth it. Day 7-9: Heidelberg and the Rhine Valley Day 7: Travel to Heidelberg, a charming university town known for its romantic castle overlooking the Neckar River. Explore the old town, visit the Heidelberg Castle, and stroll along the Philosopher's Walk for panoramic views of the city. Day 8: Embark on a scenic cruise along the Rhine River, passing by medieval castles, vineyards, and quaint villages. Stop by the town of Rüdesheim to sample some local wines. Day 9: Explore more of the Rhine Valley region or head back to Frankfurt for departure, depending on your schedule. Tips: Transportation: Consider purchasing a German Rail Pass if you plan to travel extensively by train. It offers unlimited travel on Germany's extensive rail network. Language: While many Germans speak English, learning a few basic phrases in German can enhance your experience and show respect for the local culture. Weather: Check the weather forecast before your trip and pack accordingly, especially if you're visiting during the colder months. This itinerary offers a mix of history, culture, and natural beauty, giving you a well-rounded experience of Germany. Safe travels!", "analytics": ["clarity", "confidence"] ``` For fine-grained control over analytics and no ground truth, explore the optional parameters within the request body. These parameters allow you to tailor metrics to your specific needs and visualize cost breakdowns on the dashboard. For a detailed breakdown on the API request and response, please refer to the [API reference page](https://docs.llumo.ai/cost-saving/api-reference/compress-prompt-api). ### 3. Send first request to Evaluation API Once you have your request setup for a sample body, you can send a request to the Evaluation API to evaluate your own prompts output based on selected metrics. 1. Open your directory where LLM project reside in editor of your choice. 2. Edit the sample code snippet you copied from LLUMO setup modal. 3. Replace the placeholder values for prompt and topic with your specific prompt and topic. 4. Include your API key in the header of the request. 5. Run the code snippet. You can find detailed instructions on setting up the API in your code on the dedicated [guide page](https://docs.llumo.ai/cost-saving/how-to-docs/compress-first-prompt). For a more interactive experience, we recommend using API testing tools like Postman or Thunder Client. Below is the step-by-step detailed video explaining the complete process. API testing tools After sending the request, you can view the logs and metrics generated on the dashboard to see how the evaluation process performed. This information can help you optimize your requests for better results. ### All Done! Congrats! You've set up your LLUMO's Prompt Evaluation API and it has started evaluating your prompt outputs with each inference! If you encounter any difficulties while setting up, please refer to the troubleshooting section of the guide or, contact our support team at [connect@llumo.ai](mailto:connect@llumo.ai). ``` ``` # Welcome to LLumo AI’s Support Page Source: https://docs.llumo.ai/support Whether you're seeking assistance with using LLUMO AI, have a technical query, or need more information about our platform, we are here to help. Here are the different ways you can get support from our team. ## Book a Call For detailed inquiries or personalized guidance, we recommend booking a one-on-one call with one of our specialists. They will assist you with specific project requirements and help you get the most out of LLUMO AI. **Schedule Here:** [Book Your Session](https://www.llumo.ai/book-demo) ## Support Contact If you have any queries or need assistance, feel free to contact us directly. Our team is ready to help with any questions you might have. * **Email:** [connect@llumo.ai](mailto:connect@llumo.ai) * **Phone:** +91 8527507925 We’re here to ensure you have the best experience with LLUMO AI. Don’t hesitate to reach out!