<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ridhi Ratan on Medium]]></title>
        <description><![CDATA[Stories by Ridhi Ratan on Medium]]></description>
        <link>https://medium.com/@ratanridhi18?source=rss-aea7ea6149e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SPl5kyZW9wYkTABl7x17UA@2x.jpeg</url>
            <title>Stories by Ridhi Ratan on Medium</title>
            <link>https://medium.com/@ratanridhi18?source=rss-aea7ea6149e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:53:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ratanridhi18/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Langfuse Integration: The Different Ways to Plug It In]]></title>
            <link>https://medium.com/@ratanridhi18/langfuse-integration-the-different-ways-to-plug-it-in-b3bde7a76888?source=rss-aea7ea6149e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3bde7a76888</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-observability]]></category>
            <category><![CDATA[langfuse]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ridhi Ratan]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 16:41:04 GMT</pubDate>
            <atom:updated>2026-11-09T16:41:04.971Z</atom:updated>
            <content:encoded><![CDATA[<p>I am sure you have heard of many ‘lang’ words in the AI field by now. If you are one of those who have keen eyes for all AI affairs going around, you would have heard of LangSmith, Langfuse, LangChain, LangGraph, Langflow and all and all. Lucky you. I was the one struggling with the difference between Langfuse and LangChain until a while back. And once I knew the difference between these two, I was grappling with the difference between Langfuse and LangSmith!</p><p>A week into my new project, I was assigned the task of migrating it from LangSmith to Langfuse. Both solve the same problem, but the integration approaches and features differ.</p><p>LangSmith, Langfuse, OTEL… a lot of new terms to wrap my head around!”</p><p>Today I will try to navigate our way through these jargon, while keeping our pole majorly around Langfuse and it’s integration in place, the stack I recently worked on. Before starting, I’d like to clarify that today we will work our way mostly around the observability and tracing part rather than trying to grab all of Langfuse at once, phewww!</p><p>By the end of this article, you should be well versed with:</p><ul><li>why you’d want tracing in the first place, and why I picked Langfuse</li><li>how keys and the langfuse client work</li><li>the different ways to integrate langfuse to our project, and when each one makes sense</li><li>the problems I ran into, and you may too!</li><li>how to actually read the traces once they show up</li></ul><p>Prompt management, evals and datasets are great features, but they deserve their own article. This one stops once your traces are flowing.</p><h3>1. Why tracing, and why Langfuse</h3><p>Traditional softwares were deterministic, unlike the agentic systems that we see in today’s time. Executions do not follow a predefined path when we talk about agentic systems, engineering paradigms like harness engineering and loop engineering come into the picture and we need to closely monitor the decisions taken by our own agents and llm calls.</p><p><em>(Harness engineering is about building everything around the model: the prompts, tools, memory and guardrails it works with. Loop engineering is about designing the agent’s loop: how it thinks, calls a tool, looks at the result and decides what to do next, or when to stop.)</em></p><p>That’s why we need to have observability tool when working with agentic systems, so that our logs do not get submerged among the system logs. Agentic flows need tracing and session records for us developers to efficiently keep an eye on what’s going inside, in each step whether an llm call, retrieval step or even a retry on failures. We need to be wary of the input and output sent to our llm, what was interpreted and if it really did it’s job instead of just hallucinating</p><p>That’s what tracing gives you. A trace is the full story of one request, laid out as a tree. Generally one trace consists on an input+output structure. For example one question plus answer in your chatgpt conversation.</p><figure><img alt="A single Langfuse trace showing one question and its answer." src="https://cdn-images-1.medium.com/max/686/1*6VDKVJv2NSQ8rkyLT4bwtw.png" /><figcaption><em>A single Langfuse trace showing one question and its answer.</em></figcaption></figure><p>Langfuse is an open-source tool that collects these traces and shows them in a UI and that’s what we would be focussing on today.</p><h3>2. What are the options?</h3><p>Langfuse isn’t the only tool here. Apart from Langfuse, some of the common ones include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eaPdfA-DZ_tgWI2rcsjvA.png" /><figcaption>Comparison of LLM observability tools: Langfuse, LangSmith, Arize Phoenix, Helicone and Comet Opik.</figcaption></figure><p>There are others too, but for most teams out there, the real choice is between Langfuse and LangSmith.</p><h4>LangSmith vs Langfuse, in short</h4><p>So, LangSmith is made by the LangChain team, and thus comes in handy for most teams working with LangChain already. If your whole app is LangChain or LangGraph, it works with almost zero setup, set an env variable and you are good to go! The UI is polished. LangSmith Studio as well comes in very handy.</p><p>Langfuse works with LangChain too, but it’s not built only for it. It has integrations for OpenAI, LlamaIndex, Vercel AI SDK, LiteLLM and plain Python, and it speaks OpenTelemetry.</p><h4>Why I moved from LangSmith to Langfuse</h4><p>LangSmith had everything I needed (in fact, more than that), but I was looking for an open-source tool where data could stay completely within the company’s servers.</p><p>I will name a few things that made langfuse attractive given my use case:</p><ul><li><strong>Data stays with you:</strong> Prompts and outputs often contain user data. With self-hosting, traces never leave your servers, which makes privacy and compliance conversations much easier.</li><li><strong>No trace caps when self-hosted:</strong> You pay for your own infra, not per trace or per seat, unlike LangSmith.</li><li><strong>Not locked to one framework:</strong> If I ever move away from LangChain, my tracing doesn’t have to change.</li><li><strong>Built on OpenTelemetry:</strong> The newer SDK is OTel-based, so it fits into standard observability setups.</li><li><strong>Open code:</strong> When something behaves weirdly, you can read the source or check GitHub issues.</li></ul><p>For me, the major reason to move to Langfuse was that I needed to run the setup on-prem, and self-hosting LangSmith is an enterprise-only thing. Langfuse is MIT-licensed, so I could run the full product inside the company’s own network for free, with no trace limits. Prompts and outputs never leave that network, which made the security conversation much shorter.</p><h3>3. Integrating Langfuse into your project</h3><p>Enough talk. Now it’s time for the actual hands-on work.</p><p>All examples here are Python and use the current OpenTelemetry-based SDK (v3 and later). If you find older tutorials with from langfuse.decorators import ... or from langfuse.callback import ..., that&#39;s the old v2 style.</p><pre>pip install langfuse</pre><p>I am skipping the hosting part since I want to keep my focus on integration. In short, you can self-host (for example with Docker) or simply use Langfuse Cloud by heading to the URL: <a href="https://cloud.langfuse.com/">https://cloud.langfuse.com/</a></p><h4>3.1 Get your keys</h4><p>First things first, get your keys. Once you are on the landing page, you will have a view similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvvKDkA0Dw9QknnE-7vYmg.png" /><figcaption><em>Langfuse home screen for a new account, prompting you to create API keys.</em></figcaption></figure><p>With no project and no traces existing, it asks you to create API keys, or you can navigate to settings -&gt; API keys -&gt; create API keys.</p><p>You get two keys along with a base url:</p><ul><li><strong>Public key</strong> (pk-lf-...): this tells Langfuse which project the traces belong to. Think of it like a username.</li><li><strong>Secret key</strong> (sk-lf-...): this proves you&#39;re allowed to write to that project. Think of it like a password.</li></ul><p>You need both. The public key alone does nothing. The secret key should never go into git, frontend code or a screenshot.</p><p>The public key (pk-lf-...) tells Langfuse <em>which project</em> your traces belong to, a bit like a username. The secret key (sk-lf-...) proves you’re <em>allowed</em> to write to that project, like a password. And this isn’t just an analogy: when you call Langfuse’s API directly, it uses Basic Auth with the public key as the username and the secret key as the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkDW2uSc4pFNV56sN03Dxw.png" /><figcaption><em>Langfuse API keys screen with public key, secret key and base URL.</em></figcaption></figure><p>Put them in your .env:</p><pre>LANGFUSE_PUBLIC_KEY=&quot;pk-lf-...&quot;<br>LANGFUSE_SECRET_KEY=&quot;sk-lf-...&quot;<br>LANGFUSE_BASE_URL=&quot;https://cloud.langfuse.com&quot;  # or your self-hosted URL</pre><p>Older setups use LANGFUSE_HOST for the URL, so you may see either name.</p><h4>3.2 You don’t really create the client</h4><p>I expected to write something like client = Langfuse(key=..., secret=...) and pass it around everywhere. We don&#39;t have to do that.</p><p>The SDK reads those env variables on its own. Whenever we need the client, we will just call:</p><pre>from langfuse import get_client<br><br>langfuse = get_client()</pre><p>get_client() gives you one shared client for the whole app, already configured from your env. The callback handler and the @observe decorator use this same client behind the scenes, so most of the time you never touch it directly.</p><p>We only need Langfuse(public_key=..., secret_key=...) explicitly if one app has to send traces to more than one project.</p><h4>3.3 The different ways to integrate</h4><p>This is the real part. Here are the main options, from least code to most control.</p><h4>Option 1: LangChain / LangGraph callback handler</h4><p>If you use LangChain or LangGraph, this is the easiest. We create a handler and pass it in the config. Every chain step, LLM call, tool call and retriever is traced automatically, already nested properly.</p><pre>from langfuse.langchain import CallbackHandler<br>handler = CallbackHandler()<br>response = chain.invoke(<br>    {&quot;input&quot;: &quot;Hello&quot;},<br>    config={<br>        &quot;callbacks&quot;: [handler],<br>        &quot;metadata&quot;: {<br>            &quot;langfuse_session_id&quot;: &quot;chat-123&quot;,<br>            &quot;langfuse_user_id&quot;: &quot;user-42&quot;,<br>        },<br>    },<br>)</pre><p>The langfuse_session_id and langfuse_user_id keys in metadata are how you group traces into sessions and users. More on that in section 5.</p><p>This is what I use for my main flow.</p><h4>Option 2: The @observe decorator</h4><p>Let’s say we want traces for methods that are not covered by langchain runnables.</p><p><em>(In LangChain, a Runnable is anything you can call with </em><em>.invoke(): prompts, models, chains, tools and retrievers. The callback handler only traces these.)</em></p><p>My code also has plain Python functions: database calls, API calls, some processing. Those are invisible in the traces.</p><p>That’s where @observe comes in. Put it on any function and it becomes a span, with its inputs, output, timing and errors recorded.</p><pre>from langfuse import observe<br><br>@observe()<br>def fetch_customer_record(customer_id: str):<br>    ...  # your normal code<br>@observe(as_type=&quot;generation&quot;)<br>def call_my_model(prompt: str):<br>    ...  # mark it as an LLM call</pre><p>The nice part is nesting. If a decorated function calls another decorated function, or runs a chain with the callback handler inside it, everything lands in the same trace as children. That’s how I combined both: the callback handler covers the LangChain parts, and @observe covers my custom spans.</p><p>Tip: inputs and outputs are captured by default. If a function takes something huge or sensitive, turn that off with @observe(capture_input=False, capture_output=False).</p><h4>Option 3: Model provider SDKs (OpenAI, Anthropic, Gemini, DeepSeek…)</h4><p>Not every project uses a framework. Sometimes you just call the model provider’s SDK directly. For that, Langfuse gives you a drop-in client. Change one import:</p><pre># before: from openai import OpenAI<br>from langfuse.openai import OpenAI<br><br>client = OpenAI()  # point base_url to DeepSeek, Gemini, etc. if needed<br>response = client.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello&quot;}],<br>)</pre><p>The rest of your code stays the same. Every call is traced as a generation with model, tokens and cost.</p><p>And this isn’t limited to OpenAI. Many providers, like DeepSeek, Google Gemini and Anthropic, offer OpenAI-compatible APIs. Set the base_url and API key for that provider, and the same wrapper traces those calls too. If you&#39;d rather use a provider&#39;s own SDK (say, the native Anthropic or Gemini SDK), you can turn on its OpenTelemetry instrumentor instead. More on that in option 5.</p><h4>Option 4: Context managers</h4><p>Sometimes you want a span around a block of code, not a whole function. Use start_as_current_observation:</p><pre>from langfuse import get_client, propagate_attributes<br><br>langfuse = get_client()<br><br>with langfuse.start_as_current_observation(as_type=&quot;span&quot;, name=&quot;handle-request&quot;) as span:<br>    with propagate_attributes(user_id=&quot;user-42&quot;, session_id=&quot;chat-123&quot;):<br>        result = do_the_work()<br>        span.update(output=result)</pre><p>Anything traced inside the with block becomes a child of this span. propagate_attributes pushes the user and session IDs down to every child.</p><p>There’s also start_observation() without with, but then you must call .end() yourself, or the span goes missing.</p><h4>Option 5: OpenTelemetry</h4><p>The newer Langfuse SDK is itself built on OpenTelemetry. So any library that emits OTel spans can send them to Langfuse. For example, LlamaIndex tracing now uses a third-party OTel instrumentation:</p><pre>from langfuse import get_client<br>from openinference.instrumentation.llama_index import LlamaIndexInstrumentor<br><br>LlamaIndexInstrumentor().instrument()<br>langfuse = get_client()</pre><p>If your company already has an OTel setup for backend services, you can also point an OTLP exporter at Langfuse’s OTel endpoint and skip the Langfuse SDK. Good if you don’t want vendor lock-in. The downside is that Langfuse-specific things, like sessions and prompt linking, need extra attributes set by hand.</p><h4>Bonus: built-in framework integrations</h4><p>Many tools now have Langfuse support built in: LiteLLM, Vercel AI SDK, LlamaIndex, Flowise, Dify and more. If</p><p>Check the integrations page before writing anything yourself.</p><h4>So which one should we use?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rMTBeZhmoOcAtuvH3i1ThA.png" /><figcaption><em>Table matching common use cases to the Langfuse integration method to use.</em></figcaption></figure><p>Or you can implement a mix of these. They all share the same trace context, so a decorator, a callback handler and a context manager in one request still end up as one clean tree.</p><h3>4. Obstacles I faced (and things to take care of)</h3><p>Here’s what I’d tell anyone starting out with Langfuse.</p><ol><li><strong>Think about sensitive data:</strong> Prompts and outputs often contain personal data. Decide early what you want to mask. The SDK supports a mask function, and @observe can skip capturing input or output.</li><li><strong>Tracing should never break your app:</strong> Put it behind a flag like LANGFUSE_TRACING_ENABLED, so you can switch it off without a deploy if something goes wrong.</li><li><strong>Call </strong><strong>flush() in short scripts:</strong> The SDK sends traces in the background, in batches. Long-running servers are fine. But in a script, a test or a serverless function, the process can exit before anything is sent. Add langfuse.flush() at the end.</li><li><strong>Check the base URL and the project:</strong> Traces not showing up? Most of the time it’s one of these: the wrong region URL (Langfuse Cloud has EU, US and more), keys from a different project, or a typo in the env variable name.</li><li><strong>Self-hosted Langfuse is not one container:</strong> If you’re planning to self-host Langfuse with Docker, know that the current version runs a web container, a worker, Postgres, ClickHouse, Redis and S3-compatible storage. Start with the official docker-compose setup instead of building your own. If one of these is down, the UI may still load while traces silently go nowhere.</li><li><strong>Keep the SDK and server versions compatible:</strong> If you self-host, an old server may not accept data from a newer SDK. Check the compatibility page before upgrading either one.</li><li><strong>Expect some extra spans:</strong> Since the SDK is OpenTelemetry-based, it can also pick up spans from other OTel libraries in your app, like HTTP or database instrumentation. That’s noise in the UI, and more cost on the cloud plan. Langfuse lets you filter by instrumentation scope.</li></ol><h3>5. Reading your traces</h3><p>Once traces start coming in, this is how I find my way around the UI.</p><h4>Traces</h4><p>The Traces page lists every request. Click one and you see the tree: the root span at the top, and every step nested under it. Click any step to see its input, output, latency and metadata. Generations also show the model, token counts and cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Pc9GjWj431XUOc81GrrCg.png" /><figcaption><em>An opened Langfuse trace showing nested steps and their details.</em></figcaption></figure><h4>Sessions</h4><p>A chatbot conversation isn’t one request. It’s many turns. If every turn sends the same session_id (the langfuse_session_id metadata, or propagate_attributes), Langfuse groups them into one session. You can then replay the whole conversation in order, instead of hunting for separate traces.</p><p>The same idea works for users: send a user_id, and you can see all activity and cost per user.</p><h4>Filters</h4><p>The filter bar is where you’ll spend a lot of time. You can filter by:</p><ul><li>time range</li><li>trace name</li><li>user ID and session ID</li><li>tags and metadata</li><li>latency, cost and token counts</li><li>environment (for example dev, staging, production)</li><li>errors</li></ul><p>A tip: add tags and metadata generously in your code, like the feature name or the customer tier. It costs nothing, and it makes filtering much easier later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkOE_491NH_Ed-538Xi_PA.png" /><figcaption><em>The Langfuse filter bar with filters applied to the traces list.</em></figcaption></figure><h4>Per-project keys</h4><p>Remember, keys are tied to a project. You can use that to keep things separate, one project per service, or one per environment. That way dev experiments don’t mix with production traces, and you can give people access only to the projects they need.</p><p>If you’d rather keep one project, you can tag traces with an environment instead, using the LANGFUSE_TRACING_ENVIRONMENT variable, and filter by it.</p><h3>Wrapping up</h3><p>If I had to sum it up in three lines, remember:</p><ol><li>Put your keys in env variables and Langfuse will take care of client creation.</li><li>Understand the use case well to know which integration method you need: callback handler for LangChain, the drop-in client for direct model calls, @observe for your own functions or OpenTelemetry if you already have it.</li><li>Mix them freely. They all end up in the same trace.</li></ol><p>For me, the callback handler plus @observe covered almost everything. With this, I hope I was able to help you out with your Langfuse integration in your next project.</p><p>If you’re integrating Langfuse and got stuck somewhere, drop a comment. Happy to help, or at least tell you which Docker mistake I made first on my way to self-hosting :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3bde7a76888" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>