Complete OpenLIT Tutorial: Open-Source Observability for LLM Applications

# Tutorial Lengkap OpenLIT: Observability Open-Source untuk Aplikasi LLM ## Pendahuluan Membangun aplikasi berbasis Large Language Model (LLM) memang menarik, tetapi menjalankannya di production ada...

By Ruby Abdullah · · tutorial
OpenLITLLM ObservabilityOpenTelemetryAI MonitoringMLOps

Complete OpenLIT Tutorial: Open-Source Observability for LLM Applications

Introduction

Building applications powered by Large Language Models (LLMs) is exciting, but running them in production is an entirely different challenge. How do you know how much each request costs? How long does the model take to respond? Are there prompts failing silently? This is where OpenLIT comes in.

OpenLIT is an open-source observability platform designed specifically for AI and LLM applications. Built on top of the OpenTelemetry standard, OpenLIT provides auto-instrumentation for over 30 LLM providers, GPU monitoring, prompt evaluation, and secret management vault. What sets OpenLIT apart from other observability tools is its ease of integration — just two lines of code to start tracking all your LLM interactions.

In this tutorial, we will learn how to install, configure, and use OpenLIT to comprehensively monitor LLM applications.

Why OpenLIT?

Before diving into implementation, let's understand why OpenLIT is worth considering:

  • Auto-Instrumentation: No need to write manual tracing code. OpenLIT automatically captures traces, metrics, and logs from popular LLM libraries.
  • OpenTelemetry Native: Observability data in standard OTel format, exportable to any backend (Grafana, Datadog, Jaeger, etc.).
  • Multi-Provider Support: Supports OpenAI, Anthropic, Cohere, Mistral, Google Gemini, AWS Bedrock, Azure OpenAI, and many more.
  • GPU Monitoring: Track GPU usage in real-time for local inference workloads.
  • Built-in Dashboard: Provides a ready-to-use UI dashboard without additional configuration.
  • Prompt Management: Integrated vault for managing and versioning prompt templates.
  • Installation

    Prerequisites

    Make sure you have:

    • Python 3.8 or newer
    • pip package manager
    • Docker and Docker Compose (for running OpenLIT server)

    Installing OpenLIT SDK

    Install the OpenLIT Python SDK using pip:

    pip install openlit
    

    To install with support for specific features, use extras:

    # With GPU monitoring support
    

    pip install openlit[gpu]

    With evaluation support

    pip install openlit[eval]

    Running OpenLIT Server

    OpenLIT provides a dashboard server that can be run using Docker Compose:

    git clone https://github.com/openlit/openlit.git
    

    cd openlit

    docker compose up -d

    Once running, open the dashboard at http://localhost:3000. Default credentials are:

    • Email: user@openlit.io
    • Password: openlituser

    Alternatively, if you only want to send data to an existing OTel backend (e.g., Grafana Tempo or Jaeger), you don't need to run the OpenLIT server.

    Basic Configuration

    Initializing OpenLIT

    To start tracing LLM calls, simply add two lines of code at the beginning of your application:

    import openlit
    
    

    openlit.init()

    By default, OpenLIT sends data to the OTLP endpoint at http://127.0.0.1:4318. You can configure a custom endpoint:

    import openlit
    
    

    openlit.init(

    otlpendpoint="http://your-otel-collector:4318",

    applicationname="my-llm-app",

    environment="production"

    )

    Full Configuration

    Here are the available configuration parameters:

    import openlit
    
    

    openlit.init(

    otlpendpoint="http://localhost:4318",

    applicationname="chatbot-service",

    environment="staging",

    tracecontent=True, # Log prompt and response content

    disabledinstrumentors=None, # List of disabled instrumentors

    collectgpustats=False, # Enable GPU monitoring

    pricingjson=None, # Path to custom pricing file

    )

    The tracecontent=True parameter records prompt and response content. In production, you may want to disable this for privacy reasons:

    openlit.init(
    

    tracecontent=False, # Don't log prompt/response content

    environment="production"

    )

    Basic Usage: Monitoring OpenAI Calls

    Let's start with a simple example — monitoring calls to OpenAI:

    import openlit
    

    from openai import OpenAI

    Initialize OpenLIT

    openlit.init(

    applicationname="openai-demo",

    environment="development"

    )

    Create OpenAI client as usual

    client = OpenAI()

    This call is automatically traced by OpenLIT

    response = client.chat.completions.create(

    model="gpt-4",

    messages=[

    {"role": "system", "content": "You are a helpful assistant."},

    {"role": "user", "content": "Explain what observability is in 3 sentences."}

    ],

    temperature=0.7,

    maxtokens=200

    )

    print(response.choices[0].message.content)

    Without any additional code, OpenLIT will record:

    • Model used
    • Input and output token counts
    • Latency (request duration)
    • Estimated cost
    • Prompt and response content (if tracecontent=True)
    • Request status (success/failure)

    Multi-Provider Monitoring

    One of OpenLIT's key strengths is its ability to monitor multiple LLM providers simultaneously:

    import openlit
    

    from openai import OpenAI

    from anthropic import Anthropic

    from cohere import Client as CohereClient

    Single initialization for all providers

    openlit.init(

    applicationname="multi-provider-app",

    environment="development"

    )

    OpenAI

    openaiclient = OpenAI()

    openairesponse = openaiclient.chat.completions.create(

    model="gpt-4",

    messages=[{"role": "user", "content": "Hello from OpenAI"}]

    )

    Anthropic

    anthropicclient = Anthropic()

    anthropicresponse = anthropicclient.messages.create(

    model="claude-sonnet-4-20250514",

    maxtokens=100,

    messages=[{"role": "user", "content": "Hello from Anthropic"}]

    )

    Cohere

    cohereclient = CohereClient()

    cohereresponse = cohereclient.chat(

    model="command-r-plus",

    message="Hello from Cohere"

    )

    print("All calls are automatically traced!")

    Each call to any provider is recorded in the OpenLIT dashboard with complete metadata, allowing you to compare performance and costs across providers.

    Vector Database Monitoring

    OpenLIT also supports tracing vector database operations, which is crucial for RAG applications:

    import openlit
    

    from chromadb import Client as ChromaClient

    from openai import OpenAI

    openlit.init(applicationname="rag-pipeline")

    ChromaDB operations are also traced

    chroma = ChromaClient()

    collection = chroma.getorcreatecollection("documents")

    Add documents

    collection.add(

    documents=["OpenLIT is an observability platform for AI"],

    ids=["doc1"],

    metadatas=[{"source": "tutorial"}]

    )

    Query

    results = collection.query(

    querytexts=["what is observability?"],

    nresults=3

    )

    LLM call with RAG context

    client = OpenAI()

    context = "\n".join(results["documents"][0])

    response = client.chat.completions.create(

    model="gpt-4",

    messages=[

    {"role": "system", "content": f"Context: {context}"},

    {"role": "user", "content": "Explain AI observability"}

    ]

    )

    With this setup, you can see the entire RAG pipeline in the dashboard — from vector DB queries to LLM calls — in a single trace.

    Advanced Usage

    Custom Spans and Attributes

    To add additional context to traces, use decorators or context managers:

    import openlit
    

    from openai import OpenAI

    from opentelemetry import trace

    openlit.init(applicationname="advanced-demo")

    tracer = trace.gettracer("my-app")

    client = OpenAI()

    @tracer.startascurrentspan("processcustomerquery")

    def processquery(customerid: str, query: str):

    span = trace.getcurrentspan()

    span.setattribute("customer.id", customerid)

    span.setattribute("query.category", "support")

    response = client.chat.completions.create(

    model="gpt-4",

    messages=[

    {"role": "system", "content": "You are a customer support agent."},

    {"role": "user", "content": query}

    ]

    )

    result = response.choices[0].message.content

    span.setattribute("response.length", len(result))

    return result

    answer = processquery("CUST-001", "How do I reset my password?")

    print(answer)

    GPU Monitoring

    To monitor GPU usage when running local models:

    import openlit
    
    

    openlit.init(

    applicationname="local-inference",

    collectgpustats=True # Enable GPU monitoring

    )

    Run inference with a local model

    from transformers import pipeline

    generator = pipeline("text-generation", model="microsoft/DialoGPT-medium")

    output = generator("Hello, how are you?", maxlength=50)

    GPU stats (utilization, memory, temperature) are automatically recorded

    OpenLIT will collect GPU metrics including:

    • GPU utilization (%)
    • Memory usage (used/total)
    • Temperature
    • Power consumption

    Quality Evaluation with OpenLIT Guard

    OpenLIT provides built-in evaluation features to check LLM output quality:

    import openlit
    
    

    openlit.init(applicationname="eval-demo")

    Evaluate hallucination

    result = openlit.guard.hallucination(

    prompt="Who was the first president of the United States?",

    response="The first president of the United States was George Washington, who served from 1789 to 1797.",

    contexts=["George Washington was the first president of the United States, serving from 1789 to 1797."]

    )

    print(f"Hallucination score: {result.score}")

    print(f"Verdict: {result.verdict}")

    Evaluate toxicity

    result = openlit.guard.toxicity(

    text="Thank you for your help, that was very useful!"

    )

    print(f"Toxicity score: {result.score}")

    Evaluate bias

    result = openlit.guard.bias(

    text="Everyone deserves access to quality education."

    )

    print(f"Bias score: {result.score}")

    Integration with LangChain

    OpenLIT integrates directly with popular frameworks like LangChain:

    import openlit
    

    from langchainopenai import ChatOpenAI

    from langchaincore.prompts import ChatPromptTemplate

    from langchaincore.outputparsers import StrOutputParser

    openlit.init(applicationname="langchain-app")

    Build chain as usual

    prompt = ChatPromptTemplate.frommessages([

    ("system", "You are a professional translator."),

    ("user", "Translate to Indonesian: {text}")

    ])

    model = ChatOpenAI(model="gpt-4", temperature=0)

    parser = StrOutputParser()

    chain = prompt | model | parser

    The entire chain is automatically traced

    result = chain.invoke({"text": "Good morning, how are you?"})

    print(result)

    Exporting Data to Other Backends

    Since OpenLIT uses OpenTelemetry, you can send data to any backend:

    Grafana (via Tempo + Prometheus)

    import openlit
    
    

    openlit.init(

    otlpendpoint="http://grafana-otel-collector:4318",

    applicationname="production-app",

    environment="production"

    )

    Datadog

    import openlit
    
    

    openlit.init(

    otlpendpoint="http://datadog-agent:4318",

    applicationname="production-app"

    )

    Jaeger

    import openlit
    
    

    openlit.init(

    otlpendpoint="http://jaeger:4318",

    applicationname="production-app"

    )

    Prompt Management with Vault

    OpenLIT Vault allows you to manage prompt templates centrally:

    import openlit
    
    

    openlit.init(

    applicationname="prompt-managed-app",

    otlpendpoint="http://localhost:4318"

    )

    Retrieve prompt from vault

    prompttemplate = openlit.getprompt(

    name="customer-support-v2",

    variables={

    "companyname": "Rubythalib",

    "language": "English"

    }

    )

    Use the prompt retrieved from vault

    from openai import OpenAI

    client = OpenAI()

    response = client.chat.completions.create(

    model="gpt-4",

    messages=[

    {"role": "system", "content": prompttemplate},

    {"role": "user", "content": "I need help with my account"}

    ]

    )

    Vault enables you to:

    • Version prompt templates
    • Change prompts without redeploying code
    • A/B test different prompts
    • Audit trail of prompt changes

    Best Practices

    1. Proper Environment Configuration

    Separate configurations based on environment:

    import os
    

    import openlit

    env = os.getenv("APPENV", "development")

    openlit.init(

    applicationname="my-app",

    environment=env,

    tracecontent=(env != "production"), # Disable in production

    )

    2. Use Descriptive Application Names

    # Bad
    

    openlit.init(applicationname="app")

    Good

    openlit.init(applicationname="customer-chatbot-service")

    3. Add Custom Attributes for Business Context

    from opentelemetry import trace
    
    

    span = trace.getcurrentspan()

    span.setattribute("customer.tier", "premium")

    span.setattribute("feature.name", "document-summarizer")

    span.setattribute("request.source", "mobile-app")

    4. Proactive Cost Monitoring

    OpenLIT automatically calculates cost estimates based on model and token count. Use the dashboard to:

    • Set alerts when daily costs exceed thresholds
    • Compare costs across models for the same task
    • Identify requests that use excessive tokens

    5. Set Up Alerting

    Configure alerts for critical metrics:

    • High latency: Alert if P95 latency > 5 seconds
    • Error rate: Alert if error rate > 5%
    • Cost: Alert if hourly cost exceeds budget
    • Token usage: Alert if there's a spike in token usage

    6. Disable Unnecessary Instrumentors

    If you only use one provider, disable other instrumentors to reduce overhead:

    import openlit
    
    

    openlit.init(

    applicationname="openai-only-app",

    disabledinstrumentors=["anthropic", "cohere", "mistral"]

    )

    Complete Application Example

    Here's a complete chatbot application with OpenLIT observability:

    import openlit
    

    import os

    import time

    from openai import OpenAI

    from opentelemetry import trace

    Initialize OpenLIT

    openlit.init(

    otlpendpoint=os.getenv("OTLPENDPOINT", "http://localhost:4318"),

    applicationname="support-chatbot",

    environment=os.getenv("APPENV", "development"),

    tracecontent=os.getenv("APPENV") != "production"

    )

    tracer = trace.gettracer("support-chatbot")

    client = OpenAI()

    class ChatBot:

    def init(self):

    self.conversationhistory = []

    self.systemprompt = (

    "You are a customer support assistant for Rubythalib Data Konsulta. "

    "Answer customer questions professionally and helpfully."

    )

    @tracer.startascurrentspan("chat")

    def chat(self, usermessage: str, customerid: str = None) -> str:

    span = trace.getcurrentspan()

    if customerid:

    span.setattribute("customer.id", customerid)

    span.setattribute("conversation.length", len(self.conversationhistory))

    self.conversationhistory.append({

    "role": "user",

    "content": usermessage

    })

    messages = [

    {"role": "system", "content": self.systemprompt}

    ] + self.conversationhistory[-10:] # Limit context to last 10 messages

    starttime = time.time()

    response = client.chat.completions.create(

    model="gpt-4",

    messages=messages,

    temperature=0.7,

    maxtokens=500

    )

    elapsed = time.time() - starttime

    span.setattribute("response.timeseconds", elapsed)

    assistantmessage = response.choices[0].message.content

    self.conversationhistory.append({

    "role": "assistant",

    "content": assistantmessage

    })

    return assistantmessage

    Usage

    bot = ChatBot()

    print(bot.chat("Hello, I'd like to ask about your data consulting services.", "CUST-042"))

    print(bot.chat("What are your hourly rates?"))

    print(bot.chat("Do you offer monthly packages?"))

    Troubleshooting

    Data Not Appearing in Dashboard

  • Verify OpenLIT server is running: docker compose ps
  • Check if the OTLP endpoint is correct
  • Verify no firewall is blocking port 4318
  • Performance Overhead Too High

  • Disable tracecontent in production
  • Use sampling to reduce data volume:
  • from opentelemetry.sdk.trace.sampling import TraceIdRatioBased
    
    

    openlit.init(

    applicationname="high-traffic-app",

    tracecontent=False,

    )

    Cost Estimates Inaccurate

    OpenLIT uses built-in pricing data. For custom models or special pricing:

    openlit.init(
    

    pricingjson="/path/to/custom-pricing.json"

    )

    Conclusion

    OpenLIT provides a comprehensive observability solution for LLM applications with minimal integration effort. With native OpenTelemetry support, auto-instrumentation for 30+ providers, and a built-in dashboard, OpenLIT helps you understand the performance, cost, and quality of your AI applications.

    Key takeaways from this tutorial:

    • Easy installation: Just pip install openlit and two lines of code
    • Multi-provider: Single setup to monitor all LLM providers
    • OpenTelemetry native: Data can be exported to any observability backend
    • GPU monitoring: Track hardware resource usage
    • Built-in evaluation: Guards for hallucination, toxicity, and bias
    • Prompt vault: Centralized and versioned prompt management

    For serious AI projects in production, observability is no longer optional. OpenLIT makes implementing it as simple as adding two lines of code to your existing application.

    Related Articles

    Arize Phoenix Tutorial: Comprehensive LLM Observability and Evaluation

    Tutorial Arize Phoenix: Observabilitas dan Evaluasi LLM yang Komprehensif Arize Phoenix adalah platform open-source untu...

    TorchServe: Deploying PyTorch Models to Production

    TorchServe: Panduan Lengkap Deployment Model PyTorch ke Production Penulis: Ruby Abdullah Kategori: Tutorial Tags: PyTor...

    LMDeploy Tutorial: A Complete Toolkit for Deploying and Serving Large Language Models

    Tutorial LMDeploy: Toolkit Lengkap untuk Deploy dan Serving Large Language Model Large Language Model (LLM) semakin bany...

    MLflow Tutorial: Open-Source Platform for End-to-End MLOps

    Tutorial MLflow: Platform Open-Source untuk MLOps End-to-End MLflow adalah platform open-source yang dikembangkan oleh D...