# API Scope Source: https://developer.mindlytics.ai/api-reference/api-definitions Mindlytics APIs are designed for the applications developers to meet the following objectives, 1. **Manage user identities:** Identify users, enrich user identity with user traits, manage user's unidentified and identified states using aliasing. 2. **User Session Tracking:** Track user sessions. 3. **Conversation Tracking:** Track beginning and end of a conversation with granular turn by turn tracking. 4. **Custom Tracking:** Track user's explicit in-app actions or AI's responses through custom, developer defined event names. # Introduction Source: https://developer.mindlytics.ai/api-reference/introduction Mindlytics offers a powerful RESTful APIs designed for applications to record human–AI interactions and user actions to analyse and visualize from the Mindlytics portal. It enables developers to seamlessly integrate their application with mindlytics analytics platform to track and monitor user intent, engagement, and AI performance. Depending on the application structure and customer's unique tracking needs, the APIs may be instrumented along with the SDKs. Not all the APIs may be required for a given implementation. For instance, a customer may choose to use *track* API to track custom events while relying on the mindlytics SDKs to track sessions, conversations and user intents. In an another implementation, a customer may choose to use the mindlytics APIs to send custom events, conversation turns, session starts/ends etc. and not use the mindlytics SDK at all. # How Mindlytics works? Source: https://developer.mindlytics.ai/how-mindlytics-works Mindlytics leverages a proprietary AI engine designed to interpret user interactions with AI agents and translate them into analytics events. It seamlessly analyzes how users prompt the AI and how the AI responds, automatically generating real-time analytics events that capture explicit and implicit user actions, intents, traits, and emotional reactions. These insights are visualized in the Mindlytics portal—helping you understand user expectations, track AI performance, measure conversational friction, and assess customer satisfaction. How Mindlytics Work Pn Traditional analytics tools like Google Analytics or Adobe Analytics require developers to manually define event schemas and instrument applications to trigger those events at specific points in the user journey. This approach works well for conventional web and mobile applications where the user experience is structured and predictable. However, AI applications present a new challenge. Human–AI interactions are unstructured, dynamic, and often non-linear—making it nearly impossible to predefine event schemas in advance. Maintaining such schemas as the AI evolves not only becomes unmanageable but also drains valuable time from your product managers, architects, and data analysts. **Mindlytics solves this problem with its built-in AI-powered analytics engine.** It automatically interprets human–AI interactions and generates meaningful analytics events in real time, using intuitive and consistent naming conventions. This eliminates the need for manual instrumentation and schema maintenance—freeing your teams to focus on innovation, not plumbing. For hybrid applications, Mindlytics also supports custom events with user-defined schemas. This allows developers to combine insights from AI-driven conversations with traditional UI-based user journeys—creating a unified view of engagement across both structured and unstructured experiences. 1. **Integrate** Mindlytics via SDK or API into your AI app or agent. 2. **Capture** raw conversations or \[Human-AI] interactions in real time. Instrument the SDK to pipe user prompts and AI responses to mindlytics analytics engine. 3. **Process** interactions using AI-powered mindlytics analytics engine to decode user intent and agent performance. Let mindlytics process interactions to auto generate *analytics events.* (optionally add custom events as required.) 4. **Visualize & Analyze** \[Human-AI] engagement metrics through interactive dashboards that highlight intent fulfillment, friction hotspots, sentiment, funnels, and more. # What is Mindlytics? Source: https://developer.mindlytics.ai/index Mindlytics.ai is the first AI-native product analytics platform designed specifically for AI-driven applications—ranging from LLM-powered apps and chatbots to autonomous agents. Think of Mindlytics as the equivalent of Google Analytics, but purpose-built for LLM-based conversational and interactive experiences. Hero Light Hero Dark If you’re building an AI-first product and want to truly **understand how users interact with your AI**, Mindlytics provides the tools to quantitatively measure user's intent and behavior, optimize \[Human-AI] engagement, and maximize conversion. **Why It Matters:** AI interactions are nonlinear and unpredictable—traditional analytics fall short. [Mindlytics.ai](http://Mindlytics.ai) offers a purpose-built solution to **capture, process, and analyze** conversational data, giving teams the actionable fidelity needed to **improve user experience, AI performance, and business outcomes**. # Chart Configuration Pattern Source: https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1 All **Mindlytics Analysis Charts** follow a common configuration and interaction model. This pattern allows users to quickly create, modify, save, and reuse charts across different analytical use cases. Each chart is configured using **left-side controls**, a **central visualization area**, and **top-right visualization options**. ## 1. Left-side configuration controls The left panel defines **what data is included** in the chart and **how it is filtered**. While the exact controls may vary by chart type, they follow a consistent structure. ### Events Defines which events are included in the analysis. * Default: **Any Event** (includes all tracked events) * One or more specific events can be selected * Selected events can be filtered using **event properties** **Example** > Event = `Intent Informed`\ > Event Property = `source = mobile` *** ### For users Restricts analysis to a specific set of users. * Default: **All users** * Filter users by: * User traits and values * Users who performed a specific event * Preconfigured user cohorts **Example** > Users where `plan = enterprise` *** ### Shown Intent Adds intent-level context to the analysis. * Filters events to those generated when a specific intent was expressed **Example** > Shown Intent = `ResetPassword` *** ### Measured as Defines how the selected data is aggregated. * **Uniques** – Number of unique users who generated the events * **Totals** – Total number of events generated * **Average** – Average number of events per user **Example** > Measured as = **Totals** → “How many Reset password dialog happened?” *** ## 2. Time range and bucketing Time controls appear in the top-right of the chart display area and apply across all chart types. * Bucket data **daily**, **weekly**, or **monthly** * Choose a custom start and end date * Or select predefined ranges such as **7d**, **30d**, or **60d** **Example** > Daily buckets over the last 7 days *** ## 3. Visualization options Users can control how the data is rendered. * Select **Line** or **Bar** or \*\*Pie \*\*chart (where applicable) * Visualization updates instantly as configuration changes *** ## 4. Chart metadata and saving At the top of the chart display area, users can configure metadata for reuse and sharing. * **Chart name** (required to save) * **Optional description** for context Saved charts: * Appear under the **Charts** section in the left navigation * Can be added to one or more dashboards * Can be deleted using the **“…”** menu *** ## 5. Summary metrics and underlying data Below the chart title, Mindlytics displays **pre-calculated summary values** for the selected dataset. At the bottom of the chart display area, the **underlying data table** used to render the chart is shown. * Enables export or copy/paste * Ensures transparency between visualization and raw data # Conversation KPI Chart Source: https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-2 The **Conversation KPI** chart in Mindlytics provides a comprehensive view of conversational performance by combining multiple KPIs into a single, powerful dashboard. Mindlytics extracts insights from natural language interactions between your users and AI into actionable metrics. With this chart, you can analyse: **1. Intent Conversion Rate (ICR)**\ *Measures the effectiveness of your AI agent in resolving user intents.*\ A high ICR indicates that your agent is successfully understanding and fulfilling user goals within a conversation, signaling strong intent recognition and response quality. **2. First Intent Friction (FIF)**\ *Quantifies the responsiveness of your AI agent at the start of a conversation.*\ FIF measures the time taken to resolve the user's first expressed intent. Lower friction suggests a smoother, faster onboarding experience and early user satisfaction. **3. New Intents**\ *Tracks the emergence of user intents outside the expected scope.*\ This metric highlights the frequency and nature of unexpected or unhandled intents expressed by users, helping teams identify coverage gaps and new demand signals. **4. Sentiment**\ *Assesses user sentiment during interactions with the AI agent.*\ Derived from user language and behavior, this metric reflects how positively or negatively users feel while engaging with the agent—providing insight into user satisfaction and emotional tone. **5. AI-Human Engagement Duration**\ *Analyzes how long users actively engage with the AI agent per session.*\ This KPI captures the duration of conversations, offering a view into session depth and sustained user interest or complexity of task resolution. **6. Prompts per Engagement**\ *Indicates the average number of messages exchanged between the user and AI agent per session.*\ This helps evaluate interaction density—whether conversations are concise and effective or prolonged and potentially inefficient. # Funnel Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/funnel Description of your new file. The **Funnel Analysis Chart** visualizes how users progress through a defined sequence of steps and where they drop off. It is used to measure conversion, completion, and friction in AI-driven workflows. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1) with ordered steps. ## What this chart answers * Where do users drop off in a conversational flow? * How many users complete a task after expressing an intent? * Which steps introduce the most friction? ## How it works You define an ordered list of events that represent steps in a flow. Mindlytics computes conversion rates and drop-offs between each step. ## Examples * **Booking flow conversion** * Step 1: `conversation_started` * Step 2: `intent_detected (BookAppointment)` * Step 3: `slot_selected` * Step 4: `booking_confirmed` * **Support resolution flow** * Step 1: `intent_detected` * Step 2: `ai_response_sent` * Step 3: `issue_resolved` Use this chart to optimize task success and reduce abandonment. # Intent KPI Chart Source: https://developer.mindlytics.ai/insights/charts/intent-analysis The **Intent KPI** chart offers a focused lens into your AI agent's performance at the intent level— revealing how effectively it understands, recommends, and fulfills user needs. Drawing from best practices in conversational analytics, this dashboard compiles multiple intent-focused metrics into a single view, helping you to measure quality and optimize outcomes. **1. Intent Fulfillment Friction (IFF) :** Measures the level of friction encountered by the AI agent when resolving user intents. Higher friction may indicate prolonged dialogues or delays in achieving intent resolution. **2. Intent Fulfillment Rate (IFR):** Represents the percentage of user intents successfully fulfilled by the AI agent. A higher rate signifies better agent performance in meeting user needs. **3. Intent Fulfillment Sentiment:** Evaluates the sentiment expressed by users during the process of intent fulfillment. This metric provides insights into user satisfaction and emotional tone while fulfilling user need. **4. Intent Acceptance Rate (IAR) :** Assesses the frequency at which users accept intent recommendations proposed by the AI agent. This metric reflects the relevance and accuracy of the agent's suggestions. **5. Attribute Acceptance Rate (AAR) :** Measures the rate at which users accept attribute recommendations (e.g., missing information) provided by the AI agent during intent fulfillment. A higher rate indicates effective guidance by the agent. **6. Intent Fulfillment Efficiency:** Evaluates the efficiency of the AI agent in resolving user intents, considering factors like the number of interactions and time taken. This metric is inversely related to Intent Fulfillment Friction. # Intent Distribution Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/intent-distribution Description of your new file. The **Intent Distribution Analysis Chart** visualizes how frequently different intents are expressed by users. It highlights demand patterns and intent concentration. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1), centered on intent metrics. ## What this chart answers * What users are trying to do most often? * Which intents dominate overall usage? * How intent mix changes over time? ## How it works Mindlytics aggregates intent occurrences and displays their relative or absolute frequency. ## Examples * **Top intents in last 30 days** * Bucket = Monthly * Measured as = **Totals** * **Unique users per intent** * Measured as = **Uniques** Use this chart to guide intent optimization and roadmap decisions. # Retention Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/retention Description of your new file. The **Retention Analysis Chart** measures how often users return to interact with the AI over time. It highlights stickiness and long-term engagement patterns. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1) with cohort-based time tracking. ## What this chart answers * Do users return after their first interaction? * How retention changes across cohorts? * Which intents drive repeat usage? ## How it works Users are grouped into cohorts based on their first interaction date, and repeat engagement is tracked over subsequent time buckets. ## Examples * **7-day retention** * Cohort = First interaction date * Bucket = Daily * **Retention by intent** * Shown Intent = `AccountManagement` Use this chart to assess adoption and long-term value. # Segmentation Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/segmentation Description of your new file. The **Segmentation Analysis Chart** allows you to break down events by users, intents, and time to understand *who is doing what* in your AI application. It is the most flexible analysis chart in Mindlytics and is commonly used for exploratory analysis, validation, and trend monitoring. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1). ## What this chart answers * How many users performed a specific action? * How event volume changes over time for a given cohort? * How engagement differs by intent, user attribute, or time window? ## How it works You select one or more events, optionally filter them by user traits and intent context, choose how results are measured, and visualize trends over time. ## Examples * **Unique users sending messages per day** * Event = `message_sent` * Measured as = **Uniques** * Bucket = Daily, Last 7 days * **Total API calls for a specific intent** * Event = `api_call` * Shown Intent = `TrackOrder` * Measured as = **Totals** * **Average number of prompts per user** * Event = `prompt_sent` * Measured as = **Average** # Sentiment Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/sentiment-analysis Description of your new file. The **Sentiment Analysis Chart** shows the emotional tone of user interactions with the AI, helping teams monitor satisfaction, frustration, and risk signals. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1), with sentiment-based aggregation. ## What this chart answers * Are users generally satisfied or frustrated? * How sentiment trends change over time? * Which intents correlate with negative sentiment? ## How it works Sentiment is automatically inferred by Mindlytics and aggregated across events, sessions, or intents. ## Examples * **Sentiment distribution** * Pie chart * Last 30 days * **Negative sentiment for a specific intent** * Shown Intent = `CancelSubscription` This chart is especially useful for quality monitoring and customer experience analysis. # Session Analysis Chart Source: https://developer.mindlytics.ai/insights/charts/session Description of your new file. The **Session Analysis Chart** focuses on conversational sessions rather than individual events. It helps analyze engagement depth, session structure, and conversational complexity. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1), with session-level metrics. ## What this chart answers * How long do users typically converse with the AI? * How many turns or events occur per session? * How does session behavior vary by intent? ## How it works Events are grouped by session, and metrics are computed across sessions within the selected time range. ## Examples * **Average session duration** * Session duration * Bucket = Weekly * **Sessions with high turn count** * Filter users by intent = `Troubleshooting` This chart is useful for evaluating AI conversational quality and workload. # User Composition Chart Source: https://developer.mindlytics.ai/insights/charts/user-composition Description of your new file. The **User Composition Analysis Chart** shows how your user base is distributed across attributes, cohorts, or behaviors. It provides a structural view of *who your users are*. This chart follows the standard [**Chart Configuration Pattern**](https://developer.mindlytics.ai/insights/charts/conversation-analysis-copied-1), focused on user attributes. ## What this chart answers * What percentage of users belong to each cohort? * How users are distributed across regions, plans, or behaviors? * How user makeup changes over time? ## Examples * **User distribution by country** * User trait = `country` * **New vs returning users** * User cohort = lifecycle stage This chart is ideal for audience analysis and segmentation strategy. # Chart Configuration Pattern Source: https://developer.mindlytics.ai/insights/cohorts Description of your new file. # Events Explorer Source: https://developer.mindlytics.ai/insights/events View most recently generated events and the associated user Id **Events Explorer** provides a real-time, chronological view of all events generated by your application and tracked through the Mindlytics SDK. Events explorer is accessed from **Live Events** option from the leftside navigation panel. It enables developers and product teams to monitor live event streams, validate instrumentation, and inspect individual user behavior. ### How it works The Events Explorer displays events sorted by **timestamp**, with the most recent events appearing first. Each event entry includes: * **User ID** – the unique identifier of the user who generated the event * **Event Name** – the name of the event as sent by the SDK * **Timestamp** – the exact time the event was recorded by Mindlytics The view updates automatically as new events are ingested, allowing near real-time visibility into application activity. ### Filtering events Use the **Filter by Events** control to narrow the event stream to one or more specific event types. * Select one or multiple event names from the dropdown to filter the view * The dropdown is **dynamically populated** based on event names received for your application * Filtering helps isolate specific interactions, flows, or SDK events for focused inspection ### Inspecting user activity Clicking an event opens the corresponding **User Profile**, where you can: * View associated **user traits** and metadata * See a complete, time-ordered list of **all events generated by that user** * Analyze how an individual user interacts with your application across sessions This makes Events Explorer especially useful for debugging, instrumentation validation, and investigating specific user journeys. ### Refreshing events The Events Explorer page is **auto-updated** to reflect newly ingested events.\ You can also manually refresh the view at any time by clicking the **Reload** icon, which retrieves the most recent events. ### Common use cases * Verifying SDK setup and event instrumentation * Debugging missing, delayed, or malformed events * Monitoring real-time user activity * Drilling down from raw events to individual user behavior # Introduction Source: https://developer.mindlytics.ai/insights/getting-started The **Mindlytics Portal** allows you to create, organize, and analyze charts that help you understand how users engage with your AI application. The portal supports both **precomputed human–AI engagement KPIs** and flexible **analysis charts**, enabling teams to monitor performance, explore behavior patterns, and debug interaction flows. Charts can be created, configured, saved, and organized into dashboards for ongoing analysis. Navigation is available from the left pane, which includes **Home**, **Dashboards**, **Charts**, and **Live Events**, along with a global **Create** button. # Default Dashboard Source: https://developer.mindlytics.ai/insights/getting-started-copied-1 **Home** is the default dashboard automatically created by Mindlytics for each application. It provides a high-level snapshot of overall AI engagement using four preconfigured charts. ### Engagement Chart Displays a 7-day overview of: * Active users * New users * Total conversations * Number of unique intents served by the AI ### Top Intents Chart Shows the **top 10 most frequently used intents** over the last 30 days, based on intent count. ### Conversations Chart Highlights conversational quality metrics for the last 30 days, including: * Average conversation duration * Average number of prompts per conversation * Average number of intents served per conversation ### User Sentiment Chart Displays a pie-chart distribution of **positive**, **negative**, and **neutral** sentiment detected in user interactions over the last 30 days. The Home dashboard is read-only and serves as a quick, at-a-glance view of application health and engagement trends. # Dashboards Source: https://developer.mindlytics.ai/insights/getting-started-copied-2 The **Dashboards** section allows you to create custom dashboards tailored to specific use cases such as product monitoring, experimentation, customer support, or executive reporting. ### Creating dashboards * Navigate to **Dashboards** and click **Create Dashboard** * Provide a name and optional description * Add one or more **saved charts** to the dashboard ### Using dashboards * All configured dashboards are listed under the Dashboards section * Clicking a dashboard opens a consolidated view of all associated charts * A chart can be added to multiple dashboards Dashboards enable teams to group related insights and reuse charts across different analytical views. # Charts Source: https://developer.mindlytics.ai/insights/getting-started-copied-3 The **Charts** section is where you create, configure, save, and manage all analytical visualizations in Mindlytics. ### Creating charts Click the blue **Create** button and select a chart type to begin configuration. Once created, charts can be saved and reused across dashboards. ### Chart types Mindlytics supports two broad categories of charts: #### KPI Charts KPI charts display **precomputed human–AI engagement metrics** that are automatically collected and calculated by Mindlytics. * **Conversation KPI Charts** – Metrics related to conversations, sessions, and overall interaction quality * **Intent KPI Charts** – Metrics related to intent usage, intent success, and intent-level engagement These KPIs require no manual configuration beyond chart selection. #### Analysis Charts Analysis charts allow deeper exploration of user behavior and interaction patterns: * **Segmentation Analysis Chart** – Compare behavior across user, session, or intent segments * **Funnel Analysis Chart** – Analyze step-by-step progression and drop-offs in interaction flows * **Session Analysis Chart** – Understand session duration, volume, and conversational structure * **Retention Analysis Chart** – Measure how often users return to interact with the AI * **User Composition Analysis Chart** – Analyze the makeup of your user base across attributes and cohorts * **Intent Distribution Analysis Chart** – Visualize how frequently different intents are expressed * **Sentiment Analysis Chart** – Track sentiment distribution and trends over time ### Saving and accessing charts * Any configured chart can be **saved** for reuse * Saved charts appear under the **Charts** section in the left navigation pane * Click a chart name to view it * Use the **“…”** menu to delete a saved chart ### Adding charts to dashboards * Open a saved chart * Click **Add to** (top right) * Select one or more dashboards This allows charts to be reused across multiple dashboards without duplication. # Users Explorer Source: https://developer.mindlytics.ai/insights/users View active users by user id **Users Explorer** provides a real-time, searchable view of users interacting with your AI application. It helps developers and product teams understand user-level engagement, inspect recent interactions, and analyze how individual users experience the AI agent. ### Default view The Users Explorer displays a list of users with key engagement and interaction attributes, including: * **User ID** – the unique identifier of the user * **Last Seen** – the timestamp of the user’s most recent interaction * **Last Intent** – the intent detected in the user’s most recent interaction with the AI * **Last Sentiment** – the sentiment associated with the user’s most recent interaction * **Conversation Count** – the total number of conversations the user has had with the AI agent The list is updated automatically as new interactions occur, ensuring up-to-date visibility into user activity. ### Customizing displayed attributes You can tailor the Users Explorer table to show only the user attributes relevant to your analysis. * Click **Configure Display** (top right) to select or deselect user traits * Add or remove any tracked **user traits** from the table columns * Changes apply instantly, allowing flexible exploration without modifying tracking configuration This enables teams to adapt the view for debugging, customer support, or deeper behavioral analysis. ### Searching users Use the **Search** field to quickly find specific users based on any tracked user trait. * Search by **User ID**, **name**, or any other user attribute being tracked * Search operates across all available user traits, not just visible columns * Useful for locating individual users, validating identity mapping, or investigating specific cases ### Drilling into user profiles Clicking a user opens the **User Profile**, where you can: * View the complete set of user traits and metadata * See a chronological list of all events and interactions generated by the user * Analyze the user’s full interaction history across sessions and conversations ### Common use cases * Monitoring user engagement and activity at the individual level * Investigating user-specific issues or anomalies * Validating user traits and identity resolution * Supporting customer success and debugging workflows # User Profile Source: https://developer.mindlytics.ai/insights/users-copied-1 View all the user properties of the selected user and the exhaustive list of events generated by the user. The **User Profile** page provides a detailed, user-centric view of how an individual user is identified and how they engage with your AI application. The page is organized to answer two core questions: **who the user is** and **how the user interacts with the AI**. ### User details The left side of the page displays all known **user traits** (attributes) for the selected user. These traits are automatically populated based on how the Mindlytics SDK is instrumented in your application. By default, the following attributes are shown: * **User ID** – the unique identifier for the user * **First Seen** – the timestamp of the user’s first recorded interaction * **Last Seen** – the timestamp of the most recent interaction * **Last Intent** – the most recent intent expressed by the user * **Last Known Sentiment** – the sentiment detected in the user’s latest interaction * **Intent Count** – the total number of intents expressed by the user over their lifetime If your application tracks additional user attributes (such as **email**, **name**, **gender**, **location**, or other domain-specific traits), they are displayed automatically in this section. #### Avatar support To display a user avatar, pass the reserved user trait `avatar` with a URL pointing to the image location (for example, an image hosted in an S3 bucket or your application’s backend).\ When present, the avatar is rendered automatically in the user profile. ### Activity timeline The **Activity** section shows a chronological history of the user’s interactions with the AI, organized by **session**. * Events are grouped by **Session ID**, making it easy to follow individual conversations * Each event includes the **event name** and **timestamp** * Use the **Next** and **Previous** controls at the bottom of the page to navigate through all sessions and events associated with the user This timeline provides a clear, session-level view of how the user engages with the AI over time. ### Event details Clicking on an event in the Activity timeline opens the **Event Details** panel on the right side of the page. This panel displays: * **Event Name** * **Timestamp** * **Event Properties** associated with the event For **custom events**, event properties are defined and sent by your application during SDK instrumentation.\ For **Mindlytics default events**, all relevant attributes are automatically captured and attached by the SDK. ### Use cases The User Profile page can function as a lightweight, application-specific **CRM view**, enabling teams to: * Understand individual user behavior and engagement patterns * Debug issues by inspecting raw events and sessions * Support customer success and investigate user-reported problems * Validate SDK instrumentation and user trait mapping # Mindlytics SDKs Source: https://developer.mindlytics.ai/overview-sdks-apis The Mindlytics SDKs are available, at this time, for the Python and Javascript/Typescript platforms. ## SDK Repositories * Python : [https://github.com/Mindlytics/mlsdk-python](https://github.com/Mindlytics/mlsdk-python) * Javascript / Typescript : [https://github.com/Mindlytics/mlsdk-js](https://github.com/Mindlytics/mlsdk-js) ## SDK User Guides Integrate Mindlytics into a Python project. Integrate Mindlytics into a JavaScript project. # Examples Source: https://developer.mindlytics.ai/python-sdk/examples Python SDK Examples # Python SDK Usage Source: https://developer.mindlytics.ai/python-sdk/python-usage This is the [Mindlytics](https://mindlytics.ai) client-side SDK for Python clients. It is used to authenticate and send telemetry events to the Mindlytics analytics backend server. This SDK uses `asyncio` and the `asyncio.Queue` to decouple your existing client code from the communication overhead of sending data to Mindlytics. When you send events with this SDK you are simply pushing data into a queue. A background coroutine in the SDK will pop the queue and handle the actual communication with Mindlytics, handling errors, timeouts, rate limits, etc with zero impact to your main application. ```python theme={null} # A simple chatbot server that integrates with the Mindlytics service from fastapi import FastAPI, Request from pydantic import BaseModel from fastapi.responses import StreamingResponse import asyncio import os from openai import OpenAI from dotenv import load_dotenv from mlsdk import Client as MLClient load_dotenv() app = FastAPI() openai = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) @app.middleware("http") async def add_session_to_request(request: Request, call_next): # Get client-side ids from headers session_id = request.headers.get("x-session-id") conversation_id = request.headers.get("x-conversation-id") user_id = request.headers.get("x-user-id") device_id = request.headers.get("x-device-id") # Instanciate a client object with your organization api key and project id ml = MLClient( api_key=os.environ.get("MLSDK_API_KEY", project_id=os.environ.get("MLSDK_PROJECT_ID", ) # session_id is required. It should be a unique uuid representing a unique user session. # conversation_id is optional, but required if sending conversation-related events. # One of user_id or device_id is required. request.mlsession = ml.create_session( session_id=session_id, conversation_id=conversation_id, id=user_id, device_id=device_id, ) try: response = await call_next(request) finally: # Flush the mindlytics event queue to ensure all messages are sent await request.mlsession.flush() return response # Simple streamer function to stream tokens back to the client. async def openai_streamer(mlsession, question: str): assistant = "" stream = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": question}], stream=True, ) for chunk in stream: content = chunk.choices[0].delta.content or "" assistant.append(content) # Capture the entire response ... yield content # Send the complete "turn" to the Mindlytics service await mlsession.track_conversation_turn( user: question, assistant: assistant ) class AskRequest(BaseModel): question: str # Endpoint for asking a question of the assistant @app.post("/ask-assistant") async def ask_assistant(ask_request: AskRequest): return StreamingResponse(openai_streamer(ask_request.mlsession, ask_request.question), media_type="text/event-stream") # Call this when the session/conversation is finished. @app.post("end-session") async def end-session(request: Request): await request.mlsession.end_session() return {"status": "ok"} ``` The SDK is stateless as long as you are consistent with session\_ids and conversation\_ids. You must explicitly call `end_conversation()` when a conversation is finished, or an `end_session()` which will automatically end all open conversations associated with the session. This is required so that Mindlytics can perform post-conversation analysis. ## Concepts Except for client-level user identify and alias, all other communication with Mindlytics is contained within a "session". In a session you may send your own "user defined" events; that is, events that are not specific to Mindlytics but are meaningful to you. In a session you may also send special Mindlytics events related to conversations. Events happen at a point in time, but sessions and conversations they belong to have a start and an end and thus a specific duration. ### User ID and Device ID User IDs are something you can decide to use or not use. If you decide to use them, user ids should be unique for a organization/project pair. You can use anything you like as long as it is a string, and is unique for each user in a project. Device IDs should represent unique devices, like a browser instance or a mobile device uuid. Device IDs are considered globally unique. If you do not use user ids, then you must use device ids. You can use both. For example, when a session begins you may not know the id of the user who starts it. If this is the case, you must supply a "device\_id" that is globally unique and represents the device the user is communicating on. This might be a mobile device uuid. This is harder on a browser, but you might use a uuid stored in a local cookie. Sometime during the session/conversation you might discover who the user is and then you can issue a "session\_user\_identify" event with the user id, who will then be associated with the device\_id and the session. ## Architecture The Mindlytics SDK is designed to have a minimal impact on your application. The SDK requires `asyncio` and uses an asynchronous queue to decouple your application from the actual communication with Mindlytics. When you interact with the SDK your data gets pushed into an asynchronous FIFO and the SDK returns control to your application immediately. In the background the SDK removes data from the queue and tries to send it to the Mindlytics service. The SDK handles errors, and any timeouts, retries or rate limits as it tries to get the data to the server. When your application exits there is a way to wait on the SDK to completely drain the queue so no data is lost. ## Errors Because your application code is completely decoupled from the SDK sending data, it is not possible to get Mindlytics errors as they happen, if they happen. At any time you may query the Mindlytics session to see if it has any errors, and get a list of these errors. ```python theme={null} if session.has_errors(): for err in session.get_errors(): print(f"{err.status}: {err.message}") ``` You may also register a function as a error callback if you'd like notification of errors as they occur: ```python theme={null} from mlsdk import Client, APIResponse def ml_error_reporter(err: Exception): print(str(err)) client = Client(...) session = client.create_session(on_error=ml_error_reporter) ``` Since your application is decoupled from the Mindlytics backend, you can only get communication errors this way. Deeper errors that might happen on the Mindlytics backend while processing queued messages are not possible to get this way. However, this SDK supports an optional websockets mechanism which you might choose to employ to receive these processing errors, and to receive Mindlytics generated events as they are generated. See [Websocket Support](#websocket-support) below. ## Client API ```python theme={null} from mlsdk import Client client = Client(api_key="KEY", project_id="ID") ``` **Arguments:** * api\_key - Your Mindlytics workspace api key. * project\_id - The ID of a project in your workspace. Used to create sessions. * debug (optional, False) - Enable to turn on logging. * server\_endpoint (optional) - Use a different endpoint for the Mindlytics server. You can set environment variables for `MLSDK_API_KEY` and `MLSDK_PROJECT_ID` which will be used unless you supply the value to the constructor. **Returns:** An instance of the Mindlytics client object. This is used primarily to create sessions, but has two other methods for identifying users and managing aliasing outside of normal sessions. ```python theme={null} from mlsdk import Client try: await client.user_identify( id="JJ@mail.com", traits={ "name": "Jacob Jones", "email": "jj@mail.com", "country": "United States" } ) except Exception as (e): print(e.message) ``` Used to identify new users or devices and to merge traits on existing users or devices. **Arguments:** * id - A unique user id for a new user or an existing user for the workspace/project specified in `client`. If this id already exists, the given traits are merged with any existing traits. Any existing matching traits are over written. Mindlytics supports strings, booleans, and numbers as trait values. * device\_id - (optional, None) A unique device id. One of id or device\_id is required. * traits - (optional, None) - A dict of user or device traits. ```python theme={null} from mlsdk import Client try: await client.user_alias( id="jjacob", previous_id="JJ@mail.com", ) except Exception as (e): print(e.message) ``` Used to create an alias for an existing user. **Arguments:** * id - The new id for this user. * previous\_id - The previous id value for this user. The previous\_id is used for the lookup. ```python theme={null} session = client.create_session( session_id=str(uuid.uuid4()), conversation_id=str(uuid.uuid4()), id='jjacob' ) await session.track_event(event="Start Chat", properties={"from": "shopping cart"}) await session.track_conversation_turn( user="I need help choosing the right lipstick for my skin color.", assistant="I can help you with that. What color would you use to describe your skin tone?", await session.end_session() await session.flush() ``` In the example above, the session consists of one conversation and all events are associated with that conversation. But you can have multiple ongoing conversations within a single session, as long as those conversations belong to the same user or device. You can do this by passing a conversation\_id in a more granular way and by calling `end_conversation()`. You can still call `end_session()` and that will automatically end all open conversations. Here is an example: ```python theme={null} conversation_id_1 = str(uuid.uuid4()) conversation_id_2 = str(uuid.uuid4()) session = client.create_session( session_id=str(uuid.uuid4()), id='jjacob' ) # custom events do not have to be associated with a conversation. await session.track_event(event="Start Chat", properties={"from": "shopping cart"}) await session.track_conversation_turn( conversation_id=conversation_id_1, user="I need help choosing the right lipstick for my skin color.", assistant="I can help you with that. What color would you use to describe your skin tone?", await session.track_conversation_turn( conversation_id=conversation_id_2, user="Do we sell lipstick?", assistant="Yes", ) await session.end_conversation(conversation_id=conversation_id_2) await session.end_conversation(conversation_id=conversation_id_1) await session.flush() ``` **Arguments:** * session\_id - (required, str) A globally unique session id for this session. * conversation\_id - (optional, None) A globally unique conversation\_id to associated with all events in the session. * id - (optional, None) If the user id for this session is known, you can pass it here. * device\_id - (optional, None) A device id. If user id is not passed, then device\_id is required. * on\_error - (optional, None) A function that will be called whenever SDK detects an error with the Mindlytics service. * on\_event - (optional, None) If specified, will start a websocket client session and report events as they are generated my Mindlytics If an `id` is not passed, the session will be associated with a temporary anonymous user until the actual user is identified. ## Session API ```python theme={null} await session.flush() ``` This method will block and wait until all pending events are send off to the Mindlytics server. If you do **not** call this method, there is a chance you can lose data if it has not been transferred yet. Once this method is called you can no longer send any events to the Mindlytics service using this session instance. ```python theme={null} await session.flush_and_continue() ``` This method will block and wait until all pending events are send off to the Mindlytics server. Calling this version of "flush" lets you continue to send messages to the Mindlyitcs service using this session instance. You should eventually call `session.flush()` before destroying the session instance to make sure all asyncio tasks are cleaned up. ```python theme={null} await session.end_session() ``` You must call this method to end a session. If there are open conversations associated with the session they are automatically closed. **Arguments:** * timestamp - (optional, None) If importing past data you can specify a timestamp for the end of this session. * attributes - (optional, None) A dictionary of arbitrary attributes you may want to associated with this session. ```python theme={null} if session.has_errors(): errors = session.get_errors() ``` The `has_errors()` method can be used to check if there have been any errors communicating with the Mindlytics service. The `get_errors()` method can be used to retrieve any errors. It returns a list of `APIResponse` objects (pydantic data models): ```python theme={null} class APIResponse(BaseModel): """Base class for API responses. Attributes: errored (bool): Indicates if the API response contains an error. status (str): The status of the API response. message (str): A message associated with the API response. """ errored: bool status: int message: str ``` ```python theme={null} await session.user_identify( id="JJ@mail.com", traits={ "name": "Jacob Jones", "email": "jj@mail.com", "country": "United States" } ) ``` If the user involved in a session becomes know during the session, or if the user should have some new traits added, you can call this method. **Attributes:** * timestamp - (optional, None) If specified, the timestamp associated with this event. For new users, this becomes their start date. * id - (optional, None) A unique user id for a new user or an existing user for the workspace/project specified in `client`. If this id already exists, the given traits are merged with any existing traits. Any existing matching traits are over written. Mindlytics supports strings, booleans, and numbers as trait values. * device\_id - (optional, None) A unique device id. If user id is not passed then device\_id is requiredd. * traits - (optional, None) - A dict of user traits. ```python theme={null} await session.user_alias( id="jjacob", previous_id="JJ@mail.com", ) ``` Used to create an alias for an existing user within a session. **Arguments:** * timestamp - (optional, None) If specified, the timestamp associated with this event. * id - The new id for this user. * previous\_id - The previous id value for this user. The previous\_id is used for the lookup. ```python theme={null} await session.track_event(event="My Custom Event") await session.track_event( event="Another Event", properties={ "email": "test@test.com", # str "age": 30, # int "is_subscribed": True, # bool "height": 1.75, # float } ) ``` Use this method to send your own custom events to the Mindlytics service. **Arguments:** * timestamp - (optional, None) If importing past data you can specify a timestamp for the occurrence of this event. * event - (str, required) The name of the event. * conversation\_id - (optional, None) The conversation\_id if this event is to be associated with an open conversation. * properties (optional, dict) A dictionary of arbitrary properties you may want to associate with this event. Supported value types are str, int, bool and float. ```python theme={null} await session.end_conversation() ``` This method is used to close a conversation. Conversations have a duration, and this method is needed to identify the end. When `session.end_session()` is called, any open conversations are also closed. **Arguments:** * timestamp - (optional, None) If importing past data you can specify a timestamp for this event. This would be the end date of the conversation. * conversation\_id - (optional, None) To close a specific conversation if there are more than one open, the conversation id if the one you want to close. * properties (optional, dict) A dictionary of arbitrary properties you may want to associate with this conversation. These values will be merged with any you might have specified when the conversation was created. ```python theme={null} await session.track_conversation_turn( user="I am feeling hungry so I would like to find a place to eat.", assistant="Do you have a specific which you want the eating place to be located at?" ) ``` Send a single "turn" of a conversation to the Mindlytics service for analysis. **Arguments:** * timestamp - (optional, None) The timestamp of the conversation turn. Defaults to the current time. Use this to import past data. * conversation\_id - (optional, None) The conversation id for this turn. Defaults to current conversation. Required if there are multiple opened conversations in this session. * user - (required, str) The user utterance. * assistant - (required, str) The assistant utterance. * assistant\_id - (optional, None) An assistant id for the assistant, used to identify agents. * properties - (optional, dict) A dictionary of arbitrary properties you may want to associate with this conversation turn. * usage - (optional, None) Use this to track your conversational LLM costs. You can optionally track your own conversational LLM costs in Mindlytics. You can do this on a turn-by-turn basis using this method, or on a less granular basis using the method described below. You can specify costs in one of two ways; if your LLM is a popular, known LLM you may send your model's name and the prompt and completion token counts, and Mindlytics will use an online database to look up the per-token costs for this model and do the math. Or you may pass in an actual cost as a float, if you know it or are using a less popular LLM. The "usage" property can be one of: ```python theme={null} class TokenBasedCost(BaseModel): """Common models have costs that are provided by a service on the web. If you are using one of these models, you can provide the model name and the number of tokens in the prompt and completion, and the cost will be calculated for you. """ model: str = Field(..., min_length=1, max_length=100) prompt_tokens: int completion_tokens: int class Cost(BaseModel): """If you know the cost of a conversation turn, you can provide it directly. This will be accumulated in the conversation analysis. """ cost: float ``` ```python theme={null} await session.track_conversation_usage( cost: TokenBasedCost(model="gpt-4o", prompt_tokens=134, completion_tokens=237) ) ``` Use this method to track your own LLM costs. **Arguments:** * timestamp - (optional, None) If importing past data you can specify a timestamp for this event. * conversation\_id - (optional, None) The conversation id for this usage. Defaults to current conversation. * cost: (required, Union\[TokenBasedCost, Cost]) - A cost to be added to the conversation cost so far. ```python theme={null} await session.track_function_call( name="my_function_name", args='{"input1": 5, "input2": 6}', result="17", runtime=4093 ) ``` Use this to track tool calls during a conversation. **Arguments:** * timestamp - (optional, None) If importing past data you can specify a timestamp for this event. * conversation\_id - (optional, None) The conversation id for this usage. Defaults to current conversation. * name - (required, str) The function name. * args - (optional, str) The arguments to the function (usually a JSON string). * result - (optional, str) The function result as a string. * runtime - (optional, int) Number of milliseconds the function took to run. * properties - (optional, dict) A dictionary of arbitrary properties you may want to associate with this function call. ## HTTPClient There is a class you can use to communicate with the raw Mindlytics backend service endpoints. ```python theme={null} from mlsdk import HTTPClient client = HTTPClient( api_key="YOUR_WORKSPACE_API_KEY", project_id="YOUR_PROJECT_ID", ) response = await send_request( url="/bc/v1/events/queue", method="POST", data={ # your data } ) ``` The response is a dictionary that looks like: ```python theme={null} { "errored": True, # or False "status": 500, # http status code "message": "..." # Error message } ``` ## Websocket Support While your application code is decoupled from the Mindlytics service in terms of sending events, it is possible to receive the events you send as well as the analytics events that Mindlytics generates over a websocket connection. You can do this by registering callback handlers when you create a new session. ```python theme={null} from mlsdk import Client, MLEvent async def main(): client = Client( api_key="YOUR_WORKSPACE_API_KEY", project_id="YOUR_PROJECT_ID", ) async def on_event(event: MLEvent) -> None: print(f"Received event: {event}") async def on_error(error: Exception) -> None: print(f"Error: {error}") session_context = client.create_session( device_id="test_device_id", on_event=on_event, on_error=on_error, ) async with session_context as session: await session.track_conversation_turn( user="I would like book an airline flight to New York.", assistant="No problem! When would you like to arrive?", ) # leaving the context will automatically flush any pending data in the queue and wait until # everything has been sent. Because you registered callbacks for websockets, the websocket connection # will wait until a "Session Ended" event arrives, and then close down the websocket connection. asyncio.run(main()) ``` ## Helpers The Mindlytics SDK comes with some built in "helpers" to make integrating the SDK easier with some popular AI frameworks. See the "examples" directory for ideas of how to take advantage of these helpers. ## Examples ```sh theme={null} poetry run python -m ipykernel install --user --name=mindlytics --display-name "Mindlytics Python SDK" ``` On a mac, this command reported: `Installed kernelspec mindlytics in $HOME/Library/Jupyter/kernels/mindlytics`. You should create a file named `.env.examples` with some key environment variables that are required by the demos, something like this (with your real values of course): ```sh theme={null} OPENAI_API_KEY="yours" MLSDK_API_KEY="yours" MLSDK_PROJECT_ID="yours" ``` And if you are using a non-standard Mindlytics backend, add ```sh theme={null} MLSDK_SERVER_BASE="http://localhost:3000" ``` Then execute: ```sh theme={null} eval `cat .env.examples` poetry run jupyter lab examples ``` # End a conversation Source: https://developer.mindlytics.ai/rest/events/conversation-end POST /bc/v1/events/event/end-conversation End a conversation for a user. # Start a new conversation Source: https://developer.mindlytics.ai/rest/events/conversation-start POST /bc/v1/events/event/start-conversation Start a conversation for a user. # Track a conversation turn Source: https://developer.mindlytics.ai/rest/events/conversation-turn POST /bc/v1/events/event/conversation-turn A turn in a conversation. # Track conversation usage Source: https://developer.mindlytics.ai/rest/events/conversation-usage POST /bc/v1/events/event/conversation-usage Usage of a conversation. # Alias a user during a session Source: https://developer.mindlytics.ai/rest/events/session-alias POST /bc/v1/events/event/alias Alias a user by their unique ID. # End a session Source: https://developer.mindlytics.ai/rest/events/session-end POST /bc/v1/events/event/end-session End a session for a user. # Identify a user during a session Source: https://developer.mindlytics.ai/rest/events/session-identify POST /bc/v1/events/event/identify Identify a user by their unique ID. # Start a new session Source: https://developer.mindlytics.ai/rest/events/session-start POST /bc/v1/events/event/start-session Start a session for a user. # Track an arbitrary event Source: https://developer.mindlytics.ai/rest/events/track POST /bc/v1/events/event/track Track an event for a user. # Obtain an Authorization Token Source: https://developer.mindlytics.ai/rest/live-events/live-events-auth GET /bc/v1/live-events/realtime Get authorization key for WebSocket connection. Specify a session_id to scope events to a specific session. # Overview Source: https://developer.mindlytics.ai/rest/live-events/overview When you send track events to the Mindlytics service using a REST endpoint, the incoming event is sent to a processing queue and the REST endpoint returns immediately. This queuing architecture means there will be very little impact to your application when using the Mindlytics service. Depending on the type of event you are sending to Mindlytics, the processing of that event may take a little time and may generate several new events as a result. In some use cases it may be desirable to see these events as and when they are generated. You can accomplish this with a websocket connection to the Mindlytics service to receive these generated events. The way this works is that you must first use an authenticated REST call to obtain an "authorization token" and then use this authorization token in a custom header when creating the websocket client. Here are some usage examples: ```javascript javascript icon="node" theme={null} import Websocket from 'ws' const MLWSEndpoint = "wss://wss.mindlytics.ai" const wsAuthorizationToken = await getAuthorizationToken() const wsClient = new WebSocket(MLWSEndpoint, { headers: { Authorization: `Bearer ${wsAuthorizationToken}`, }, }) wsClient.on('error', (error) => { console.log(error.message) }) wsClient.on('message', (message) => { const event = JSON.parse(message) console.log(event) }) ``` ```python python icon="python" theme={null} import websockets from websockets.asyncio.client import connect ws_url = "wss://wss.mindlytics.ai" ws_authorization_token = await get_authorization_token() headers = [("Authorization", f"Bearer {ws_authorization_token}")] async with connect(ws_url, additional_headers=headers) as websocket: async for message in websocket: event = json.loads(message) print(event) ``` # Get Started Source: https://developer.mindlytics.ai/rest/overview ## Authentication To call REST endpoints, you must pass your workspace's api key as the bearer token in the `Authorization` request header, and one of your project ids in a custom header named `X-App-Id`. You can obtain these values from the Mindlytics SaaS portal. ## Errors Errors are returned as standard HTTP errors. You will get a status code like 400, 403, 500, etc. and the response body will contain the error message text. # Overview Source: https://developer.mindlytics.ai/rest/user/overview These endpoints are used to manage your application users *outside* of Mindlytics sessions. # Alias a user Source: https://developer.mindlytics.ai/rest/user/user-alias POST /bc/v1/user/alias Alias user Use this endpoint to associate another id with a particular user. The new id becomes the primary id. All previous ids are kept in the user's "aliases" field. # Identify a user Source: https://developer.mindlytics.ai/rest/user/user-identify POST /bc/v1/user/identify Identify user. The user id, or the user's device id, or both must be provided You can associate traits with a user id or a device id. If the user or device id already exists, the given traits are merged with the existing traits. # Terminology Source: https://developer.mindlytics.ai/terminology # Examples Source: https://developer.mindlytics.ai/typescript-sdk/examples Typescript SDK examples # Typescript SDK Usage Source: https://developer.mindlytics.ai/typescript-sdk/typescript-usage This is the [Mindlytics](https://mindlytics.ai) client-side SDK for Javascript clients. It is used to authenticate and send telemetry events to the Mindlytics analytics backend server. This SDK uses an async queue to decouple your existing client code from the communication overhead of sending data to Mindlytics. When you send events with this SDK you are simply pushing data into a queue. In the background, the SDK will pop the queue and handle the actual communication with Mindlytics, handling errors, timeouts, rate limits, etc with zero impact to your main application. ## Installation ```bash theme={null} npm install @mindlytics/node-sdk ``` ## Simple Usage ```ts theme={null} import { Client } from '@mindlytics/node-sdk' const client = new Client({ projectId: 'your-project-id', apiKey: 'your-api-key', deviceId: 'your-device-id', }) const session = client.createSession({ sessionId: crypto.randomUUID(), // or an existing session id userId: '123', }) await session.track({ event: 'File Uploaded', }) await session.end() const errors = await session.flush() ``` ## Context The SDK provides a context system using `AsyncLocalStorage` that allows you to access the session throughout your application code. This is particularly useful for tracking LLM interactions and tool calls. ```ts theme={null} import { openai } from '@ai-sdk/openai' import { serve } from '@hono/node-server' import { streamText, createTool } from 'ai' import { z } from 'zod' import { Hono } from 'hono' import { stream } from 'hono/streaming' import { Client, useSession } from '@mindlytics/node-sdk' import { authMiddleware } from './auth.middleware.ts' const app = new Hono() app.use(authMiddleware) app.post('/chat', async (c) => { const client = new Client({ projectId: 'your-project-id', apiKey: 'your-api-key', userId: c.get('userId'), }) const session = client.createSession({ sessionId: req.headers['x-session-id'] conversationId: req.headers['x-conversation-id'] userId = req.user.id }) return client.withContext(async () => { const result = streamText({ model: openai('gpt-4o'), prompt: 'How is the weather in Tokyo?', tools: [weatherTool], }) return stream(c, (stream) => stream.pipe(result.toDataStream())) }) }) const weatherTool = createTool({ name: 'weather', description: 'A tool that returns the weather for a given city', parameters: z.object({ city: z.string(), }), execute: async ({ city }) => { const session = useSession() const start = new Date() const result = await getTheWeatherFor(city) await session.trackConversationFunction({ properties: { name: 'CheckWeather', args: JSON.stringify([city]), result, runtime: new Date() - start, } }) return result }, }) ``` ## Serverless On serverless platforms like Vercel or Cloudflare, you can use the `session.flush()` method to ensure all events are sent to the Mindlytics platform before the function execution ends. ## Receiving Events and Errors from Mindlytics While your application code is decoupled from the Mindlytics service in terms of sending events, it is possible to receive the events you send as well as the analytics events that Mindlytics generates over a web socket connection. You can do this by registering callback handlers when you create a new session. ```js theme={null} import {MLEvent} from '@mindlytics/core' session.startListening( onError: { callback: (error: Error, data: any) => {...}, data: yourData }, onEvent: { callback: (event: MLEvent, data: any) => {...}, data: yourData } ) ``` Any `yourData` that you supply will be sent to your handlers as a second argument. You can use this to gain access to contextual information if needed. ## Concepts Except for client-level user identify and alias, all other communication with Mindlytics is contained within a "session". In a session you may send your own "user defined" events; that is, events that are not specific to Mindlytics but are meaningful to you. In a session you may also send special Mindlytics events related to conversations. Events happen at a point in time, but sessions and conversations they belong to have a start and an end and thus a specific duration. While you can explicitly start and end sessions and conversations, some of this work can be done implicitly. This is particularly useful if you are using the SDK in a stateless, serverless context and handling an ongoing conversation. ### User ID and Device ID User IDs are something you can decide to use or not use. If you decide to use them, user ids should be unique for a organization/project pair. You can use anything you like as long as it is a string, and is unique for each user in a project. Device IDs should represent unique devices, like a browser instance or a mobile device uuid. Device IDs are considered globally unique. If you do not use user ids, then you must use device ids. You can use both. For example, when a session begins you may not know the id of the user who starts it. If this is the case, you must supply a "device\_id" that is globally unique and represents the device the user is communicating on. This might be a mobile device uuid. This is harder on a browser, but you might use a uuid stored in a local cookie. Sometime during the session/conversation you might discover who the user is and then you can issue a "session\_user\_identify" event with the user id, who will then be associated with the device\_id and the session. ## Client API ```ts theme={null} import { Client } from '@mindlytics/node-sdk' const client = new Client({}) ``` Create a client instance. An api key and a project id are required. If not specified then the environment variables `MLSDK_API_KEY` and `MLSDK_PROJECT_ID` are checked. You can obtain these values from your account on the Mindlytics SaaS portal. The full set of options for the `Client` constructor are: ```ts theme={null} { apiKey?: string projectId?: string baseUrl?: string debug?: boolean queue?: QueueOptions } ``` The `baseUrl` points to the Mindlytics production server address. This can be changed by specifying `baseUrl` or by setting the environment variable `MLSDK_SERVER_BASE`. **Returns:** An instance of the Mindlytics client object. This is used primarily to create sessions, but has two other methods for identifying users and managing aliasing outside of normal sessions. ```ts theme={null} const user = await client.identifyUser({ id: 'customer-123', traits: { email: 'c123@mail.com', } }) ``` Used to identify a new user. If called on an existing id, will merge the traits. Traits are optional. A trait can be a string, a number or a boolean. More complex data types are not supported. You may also supply a `deviceId` if you know it. If the device id has been used to create sessions (see below) then all sessions and associated events with this device id now belong to this user. **Returns:** A Mindlytics user object. ```ts theme={null} const user = await client.aliasUser({ id: 'c123@mail.com', previous_id: 'customer-123' }) ``` Used to change the id of a user. Both `id` and all previous ids become aliases for this user and can be used to refer to this user in the future. **Returns:** A Mindlytics user object. ```ts theme={null} const session = client.createSession({ sessionId: crypto.randomUUID(), userId: 'c123@mail.com' }) ``` **Returns:** A new `Session` object. The `sessionId` is required and can be a new session id or an existing session id. Session ids should be globally unique with respect to your api key and project id. You need a session to send events. To create a session you must supply either a `userId` or a `deviceId`. If you do not know the user id at the time a session is started, then you must at least supply a device id which should represent the unique device (eg. mobile phone, browser, etc) the user is coming from. You may also supply a `conversationId` which will be attached to events sent using this session instance. This is optional, since you can attach it to individual events. ## Session API ```ts theme={null} await session.start({ attributes: { origin: "shopping cart" } }) ``` Start the session. You do not need to call this directly, as all other event-related methods will auto-create a session if they need to, but you can call it if you'd like. The `attributes` is optional and if specified, the user-defined attributes are associated with the session. ```ts theme={null} await session.end({ attributes: { origin: "shopping cart" } }) ``` End the session. You must call this method to end a session. This gives the Mindlytics service the opportunity to perform session-wide analysis. This method will also automatically end any associated conversations. The optional attributes if specified will be merged into any existing session attributes. ```ts theme={null} await session.flush() ``` This method will return only after all queued messages are sent to the Mindlytics service. ```ts theme={null} await session.identify({ id: 'customer-123', traits: { email: 'c123@mail.com', } }) ``` Used to identify a user within a session. Immediately binds this user to the current session. ```ts theme={null} await session.alias({ id: 'c123@mail.com', previous_id: 'customer-123' }) ``` Create a new primary id for a user, turning the previous id into an alias. ```ts theme={null} await session.track({ event: 'MyCustomEventName', properties: { stringProp: "a string", numProp: 123, boolProp: true, } }) ``` Track a custom event. `properties` are optional. Supported property types are string, number and boolean. Complex data types are not supported. ```ts theme={null} await session.startConversation({ conversation_id: 'conv-id-1', attributes: { startingPoint: 'support' } }) ``` Start a new conversation. You do not need to call this directly, as all other conversation-event-related methods will auto-create a conversation if they need to, but you can call it if you like. The `attributes` is optional and if specified, the user-defined attributes are associated with the conversation. ```ts theme={null} await session.endConversation({ conversation_id: 'conv-id-1', attributes: { startingPoint: 'support' } }) ``` End a conversation. You do not need to call this directly, as an `session.end()` will automatically close any open conversations, but you can call it if you like. The `attributes` is optional and if specified, the user-defined attributes are merged with any existing conversation attributes. > A note on conversation ids. When you call `client.createSession()` you can pass an optional `conversationId` and if you do, this value will be automatically applied as the "conversation\_id" to all methods that accept a "conversation\_id". If you do not supply a `conversationId` to `client.createSession()` then you must supply it to the events that are related to conversations. Supplying to individual events could allow you to support multiple conversations within a single session. ```ts theme={null} await session.trackConversationTurn({ conversation_id: 'conv-id-1', properties: { user: 'Why is the sky blue?', assistant: 'You know, I get asked this a lot!' } }) ``` This sends a conversation turn to the Mindlytics service for analysis. There are some additional, optional properties you can add to this: ```ts theme={null} await session.trackConversationTurn({ properties: { user: 'Why is the sky blue?', assistant: 'You know, I get asked this a lot!', assistant_id: 'agent-123', model: 'gpt-4o-mini', prompt_tokens: 6, completion_tokens: 15, cost: 0.0000351, my_own_custom_prop: 'custom', } }) ``` `assistant_id` might be useful in a multi-agent system to keep track agent participation. `model`/`prompt_tokens`/`completion_tokens` if specified will cause the Mindlytics service to calculate the cost of this turn, and accumulate the total cost of a conversation. It uses an online database of popular models to retrieve the most current cost data. Alternatively you can specify `cost` directly if you know it or the model you are using is not a common LLM. And you can add your own custom properties. ```ts theme={null} await session.trackConversationUsage({ properties: { model: 'gpt-4o-mini', prompt_tokens: 6, completion_tokens: 15, cost: 0.0000351, } }) ``` You can track costs independently of individual turns. ```ts theme={null} await session.trackConversationFunction({ properties: { name: 'getWeather', args: '["New York, New York"]', result: "Probably either really cold or really hot.", runtime: 340, } }) ``` Track a tool call. # Use Cases Source: https://developer.mindlytics.ai/use-cases Mindlytics enable stakeholders gather insights about how users and AI engage. > Mindlytics is designed for LLM-powered chatbots and virtual assistants, Autonomous agents and task-focused AI apps, AI-driven customer support, sales agents, and personalization engines. ### **Intent-Driven User Insights** Mindlytics decodes unstructured human–AI interactions to surface real user intent—tracking fulfillment rates, friction points, sentiment, and engagement patterns—insights that traditional analytics miss. ### **Conversational Effectiveness** Measure how well your AI responds during live dialogue, including: * Identifying where users stumble or drop off (friction) * Tracking successful intent resolutions and conversational flow ### **AI Agent Performance** Get granular insights into your LLM agents: * Task completion rates * Average response times * Effectiveness of AI-recommended intents and attributes ### **User Segmentation & Cohorts** Understand who your users are, how they engage, and how their behavior evolves: * Segment users based on intent types and sentiment trends * Compare cohorts (e.g. high conversion vs low conversion) to uncover winning strategies ### **Tailored Funnel & Journey Analysis** Build custom funnels for AI-first flows, such as onboarding, intent pathing, upsell sequences, or autonomous agent workflows: * Track progression, drop-offs, and conversion efficiency through every conversational step ### **Continuous Optimization & Feedback Loop** Use Mindlytics’ real-time dashboards to: * Identify areas of conversational friction * Tune AI prompts and model behavior * Increase user satisfaction and conversion with iterative, data-driven adjustments