Tracing the OpenAI SDK and Azure OpenAI with Langfuse

A self-hosted Langfuse captures OpenAI and Azure OpenAI calls through a drop-in client import that changes only the import line. This page covers what gets logged, token and cost capture, user and session attributes, and pointing the SDK at your own host.

On this page

How the Langfuse OpenAI SDK integration captures every call

Applications that call OpenAI or Azure OpenAI directly leave the platform team with no central record of what was sent, what came back, or what it cost. The supported way to close that gap is the Langfuse drop-in replacement for the OpenAI Python SDK, which logs calls by changing only the import to from langfuse.openai import openai. The same wrapper works with both OpenAI and Azure OpenAI clients, so teams can keep their existing call sites and move the logging into the SDK layer without rewriting business logic. The Langfuse OpenAI SDK documentation sets out the exact client setup for each provider, and it is the first read before any rollout.

The integration is a client-side wrapper, which has a direct consequence for coverage. It records only the processes that import the wrapped client. A service that still uses the plain openai package, a notebook someone runs on a laptop, or a third-party tool that holds its own API key will send nothing to Langfuse. Before rollout, the platform team should inventory which services call the model provider, which SDK and language each one uses, and whether any of them reach the provider through a route the wrapper never sees. Anything outside the wrapper will need a different capture point, such as a gateway, which is a separate design decision.

Every wrapped call needs to be pointed at your self-hosted Langfuse host, not the cloud default. Set the host and the project keys in the environment that each service reads, and confirm in a test project that a request appears under the expected project before any production traffic is switched over. Keep the public and secret keys in your secrets manager rather than in source code, and treat the host address as configuration that differs per environment. Confirm the exact environment variable names against the current SDK documentation for the version you deploy, since those names are the first thing to check when traces do not arrive.

What you need before changing the import

The drop-in import only works once a few pieces are in place: a reachable self-hosted Langfuse, project keys, a compatible SDK and model credentials. Each card below is one piece to confirm before you edit application code, because a gap in any of them usually shows up as missing traces rather than a clear error.

A reachable self-hosted Langfuse

Confirm that the Langfuse web service is running and that the hosts running your OpenAI-calling code can open a connection to it on the network path you expect. Langfuse Web serves the UI and the ingestion APIs, so the application hosts need egress to that endpoint, typically through the same proxy or firewall rules that govern other internal services. Check this from a real application host, not from your laptop, before debugging anything in the SDK.

Self-hosting docs

Project API keys for each project

Create a project in the Langfuse UI and generate a public and secret key pair for it. Store both in your secrets manager and expose them to the application as environment variables, so the code does not carry them. Keys are scoped to a project, so decide now which team's traces go into which project, since moving history later is harder than choosing correctly at the start.

TLS trust for an internal host

If Langfuse is served with a certificate issued by an internal certificate authority, the Python process must trust that CA or the first request fails with a certificate verification error. Confirm which CA bundle your base image uses, and add the internal root to it or point the SDK at a bundle that includes it. Do not disable certificate verification to get past this error, because the API keys and prompt content travel over that connection.

Python SDK and Langfuse version match

The Python SDK v5 requires Langfuse v4.59.0 or later on the server. Check your running server version in the admin view or deployment manifest before installing the SDK, and pin the SDK version in your requirements file. If your instance is older, plan the server upgrade first, because the SDK and server version pairing is a common cause of unexplained ingestion failures.

OpenAI or Azure OpenAI credentials

Have working credentials for the model endpoint you will call: an OpenAI API key, or for Azure OpenAI the resource endpoint, deployment name and API version your client uses. Confirm that the same code path can make a successful call without Langfuse first, so that any later failure can be attributed to tracing rather than to the model connection. Keep these credentials separate from the Langfuse keys in your secrets store.

OpenAI SDK guide

Egress and sensitive content review

Before enabling traces, confirm that application hosts can reach Langfuse and that your data handling rules allow prompts and completions to be stored in it. Traces capture request inputs and model outputs, which can include personal or confidential data. Agree with the security and privacy owners who may read those traces, and which retention setting applies, before the first production call is captured.

Configuring the drop-in import step by step

This sequence takes a team from a running self-hosted Langfuse to OpenAI and Azure OpenAI calls that appear as traces in a project they own. Each step ends with a check, so a failure is caught at the point where it was introduced.

  1. Create project keys in Langfuse

    A Langfuse project administrator signs in to the self-hosted instance, opens the target project and creates a new API key pair in the project settings. Copy the public key and secret key into your secrets store at once, because the secret key is shown only at creation. Verification: the key pair appears in the project's key list with a public key prefix, and the team has confirmed the secret is stored where the application can read it.

  2. Set host and key environment variables

    The application owner sets LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_HOST in the runtime environment, pointing LANGFUSE_HOST at the URL of your own Langfuse deployment rather than the default cloud address. Use the same names in every environment so the code does not change between development, staging and production. Verification: printing the host variable from the runtime shows your internal address, and the secret value does not appear in logs or source control.

  3. Install the SDK and change the import

    The developer installs the Langfuse Python SDK in the application environment and replaces the usual OpenAI import with the drop-in import from the Langfuse OpenAI module, so the client is created through Langfuse. No other call sites need to change for basic capture. Verification: the application starts without import errors and the dependency lock file records the installed Langfuse version.

  4. Test an OpenAI client call

    The developer runs a single chat completion with the OpenAI client from the drop-in import, using a short, non-sensitive prompt against a model the team has approved. Record the returned response and the name of the trace that should appear. Verification: the call returns a normal response, and a trace for that call shows in the project within the Langfuse UI with the model name, input, output and token usage.

  5. Test the Azure OpenAI client with your deployment

    The developer creates the Azure client through the same drop-in import, using the endpoint, the API key and the API version the team already uses in production, and calls the deployment name that the application references, not the underlying model name. Confirm the API version against your own Azure configuration before running the call. Verification: the call succeeds, and the resulting trace records the deployment-based call, with token usage captured in the same way as the OpenAI test.

  6. Confirm both traces in the project

    A team member who did not write the test opens the project in your self-hosted Langfuse and locates both traces, checking that the OpenAI and Azure OpenAI calls are recorded as separate entries with the expected model or deployment, input, output and usage fields. Confirm the traces are visible to the users who should see them under your access model. Verification: both traces are listed, match the test inputs, and the reviewer signs off in the change record before application traffic is switched on.

  7. Record the configuration for the team

    The platform owner documents the environment variable names, the project the keys belong to, the Langfuse version tested, the SDK version pinned and the Azure API version in use, and stores the document with the deployment runbook. Include how to rotate the key pair and where the keys are kept. Verification: a second engineer can repeat the two test calls from the document alone and reach the same trace result.

How a wrapped call reaches your Langfuse host

The diagram starts in the application process, where the drop-in langfuse.openai client wraps the OpenAI or Azure OpenAI call. The model request crosses the trust boundary to the model provider, while the trace is sent to your self-hosted Langfuse web endpoint inside your network. From there, the worker processes events and writes to PostgreSQL, ClickHouse and blob storage. Check that the host setting points inside your boundary and that the trace arrives before you rely on it.

Wrapped OpenAI calls, the provider boundary and the self-hosted Langfuse components.

What gets logged for each OpenAI call and what does not

Capture scope is a design decision, not a default you can assume. When the drop-in client from langfuse.openai wraps an OpenAI or Azure OpenAI call, Langfuse records a generation that carries the model name, the input messages, the output, timing from which latency is derived, error information when a call fails, and token usage when the SDK returns it in the response. Those are the general categories the integration captures. The exact field list, how each one is named, and which attributes are populated for streaming, function calling and Azure deployments change between SDK and Langfuse versions, so confirm the current list in the Langfuse OpenAI integration docs against the versions you pin before you write a data handling statement that depends on it.

Treat prompt and completion content as personal data until your review proves otherwise. Users paste names, account numbers, health details and employee information into chat prompts, and models echo that content back in completions. Every one of those values lands in the self-hosted PostgreSQL and ClickHouse stores in your infrastructure, and it is also copied into any export or backup you take. Decide with your privacy and security teams which inputs and outputs must be stored in full, which can be shortened, and which should not be captured at all. Confirm in your own test environment, with synthetic prompts, that the fields you expect appear and that the ones you excluded do not. Record that result as evidence for the decision.

Some data is usually absent from the trace by default, and you should verify each gap explicitly. Authentication keys for OpenAI or Azure are not part of the generation payload, but request headers, tool outputs you pass in from your own code, and application context added to the trace may be. Also check whether any of your own surrounding logging captures the same content in a second place. Once the scope is set, test a failed call, a streamed call and a call with a redacted input, then document the findings in the data flow record that your compliance team uses for the deployment.

Mapping SDK arguments to Langfuse trace attributes

This table maps the arguments your application passes to the wrapped OpenAI or Azure OpenAI client against the Langfuse trace fields they populate. Read each row as a check to run in your own staging project before you rely on the attribute in dashboards, access reviews or retention queries. The main takeaway is that identifiers are only as useful as the values your application sends, so agree the naming scheme with your security and analytics teams first.

AttributeWhat you pass to the wrapped clientLangfuse trace field and what to confirm
User identifierA stable user ID per end user, passed with the callGroups traces by user in the UI. Use a pseudonymous ID, since names or emails in traces become personal data to govern.
Session identifierA conversation or session ID shared across related callsGroups multi-turn exchanges into one session. Confirm the argument name in the current Langfuse OpenAI integration docs.
TagsA list of short labels such as environment or feature nameFilters traces in the UI and API. Keep the tag vocabulary small and agreed, since free-form values fragment reporting.
Trace nameA readable name for the operation or workflowSets the trace name shown in the UI. Confirm whether the name applies per call or per parent trace in your setup.
MetadataKey-value pairs such as tenant, region or application versionStored on the trace or observation for filtering. Avoid placing secrets, raw customer data or credentials in metadata.
Model name (OpenAI)The model identifier sent in the request, such as the model parameterRecorded on the generation and used for token and cost mapping. Confirm that the name matches a pricing entry.
Deployment name (Azure OpenAI)The Azure deployment name used in the client endpoint and callAzure uses your deployment name, which can differ from the underlying model. Map it to the model name Langfuse uses for pricing, and confirm this in the integration docs before production use.
Azure endpoint and API versionYour resource endpoint and API version in the client configurationDetermines where calls go and which request shape applies. Confirm the supported configuration in the integration docs for your Azure client version.

How token counts and cost show up in Langfuse

Cost figures in Langfuse are only as accurate as the token counts it receives and the model price definitions it applies. The OpenAI drop-in import records the usage fields that the provider returns on each call, and Langfuse multiplies those counts by the prices defined for the matching model. Confirm in the Langfuse OpenAI integration documentation which usage fields are captured for your SDK version, and check on a test call that input, output and any cached or reasoning tokens appear on the generation with the values your provider reports.

Azure OpenAI needs particular attention. Azure bills by deployment name and by the contracted rate for your subscription, which can differ from list prices and may be negotiated. The model name Langfuse matches against may not equal your deployment name, so a generation can show no cost or the wrong cost. Plan to create a custom model definition in Langfuse that matches the prices in your Azure agreement, with the model name pattern that your deployments actually send, and review it whenever your contract or deployed models change.

Your team owns two cost lines. The first is the provider bill for the tokens themselves, which Langfuse can estimate but never replace. The second is the infrastructure that stores and queries the trace history, mainly ClickHouse, PostgreSQL and blob storage, whose size grows with trace volume and retention settings. Reconcile Langfuse totals against the provider invoice for a sample week before relying on dashboards for chargeback, and ask any partner quoting this work to include model price setup and that reconciliation in the written scope.

Protecting keys, prompts and the host connection

Tracing the OpenAI SDK and Azure OpenAI with Langfuse puts both provider credentials and prompt content into a central store, so the controls around them matter as much as the tracing itself. The cards below cover where each secret lives, how far each application's access reaches, how traffic to the host is protected, and how long captured content stays on the platform.

Store Langfuse and Azure keys in your secret store

The Langfuse public and secret keys and the Azure OpenAI API key should never be hardcoded in application code or committed to source control. Load them from your team's secret manager and inject them as environment variables at runtime, such as LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_HOST. Check that rotation for each key is documented, since rotating a key without updating every deployment that reads it will break tracing silently.

Issue one project key per application

Create a separate Langfuse project key pair for each application or environment so that a leaked key exposes one stream of traces instead of the whole organization's data. Project keys are scoped to a project, so separating production from staging also keeps test traffic out of production dashboards. Confirm with your Langfuse administrator which roles can create, view and revoke keys on a self-hosted instance, since project-level RBAC roles are an Enterprise license feature.

Require TLS to the self-hosted host

Every SDK call sends prompts, completions and user identifiers to the Langfuse host, so the connection must use HTTPS with a certificate your applications trust. Point LANGFUSE_HOST at the TLS-terminated address of your load balancer or ingress, not a plain HTTP port. If you run a private certificate authority, make sure the Python runtime and any containers trust its root certificate, otherwise trace export fails in ways that look like network errors.

Self-hosting docs

Mask sensitive fields before they are stored

Prompts and completions often contain customer names, account numbers or health details that should not reach a trace store in readable form. Decide which fields must be redacted and where that happens: in the application before the SDK call, or on the server. Server-side data masking is an Enterprise license feature, so on the open source tier, masking at the application layer is the control you own. Test it with realistic but synthetic data before enabling production tracing.

Set retention to match your data policy

Trace content persists until a retention policy removes it, so the retention period is a data governance decision rather than a default to accept. Data retention policies are an Enterprise license feature in self-hosted Langfuse, so confirm the retention options your license provides and whether deletion covers both ClickHouse and blob storage. Record the agreed period in your data inventory and check that backups follow the same schedule.

Why traces are missing or incomplete

This table pairs each common failure in OpenAI and Azure OpenAI tracing with its likely cause and the fix to apply. Work through the rows in order when calls do not appear in your self-hosted Langfuse, or when they appear without users, sessions or token counts. The main takeaway is that most gaps come from configuration and import mistakes that you can confirm in minutes, while ingestion backlog needs a check of the worker.

SymptomLikely causeFix
No traces appear at allHost or key variables point at Langfuse Cloud or a wrong projectConfirm the host variable names your self-hosted URL and that the public and secret keys belong to the project you are viewing
Calls appear in the wrong projectKeys copied from a different project or environmentRegenerate or copy keys from the target project and restart the application so the new values load
Calls are not traced but the app worksOld import still in use, so the plain OpenAI client is calledReplace the import with the Langfuse drop-in import and search the codebase for any remaining direct openai imports
Connection fails only on internal hostsInternal certificate authority missing from the client trust chainAdd your internal CA bundle to the runtime trust store, then confirm the host responds over HTTPS from the application container
Azure calls fail or are untracedEndpoint, deployment name or API version does not match the Azure resourceCompare the endpoint, deployment name and API version against the Azure OpenAI resource and use the same values in the client settings
Traces lack user or session attributesAttributes not set on each call or not passed through the request contextPass user and session identifiers on every request in your code path, including background jobs and retries
Traces arrive late or in burstsWorker backlog delaying asynchronous ingestionCheck worker CPU and queue behavior, then scale worker containers as described in the scaling guide
Token counts or cost are emptyModel name not recognized for usage or pricing, or response lacks usage dataConfirm the model identifier matches a known model and check the Azure deployment name mapping before adding custom pricing

Questions teams ask before connecting OpenAI and Azure OpenAI

What drives the cost of connecting the OpenAI SDK to a self-hosted Langfuse?

The cost is driven mostly by how many applications call OpenAI or Azure OpenAI, which client types they use, and the masking and retention decisions you make. Each application needs the import change, a key pair, a host setting and a check that the right attributes arrive. A small set of applications on one client type is a short job, while many services across several teams add review and coordination time. The platform itself is a separate cost: PostgreSQL, ClickHouse, Redis or Valkey and blob storage run in your infrastructure, so ask any partner to separate the integration fee from the platform build and from recurring operations. Ask for the quote to list each application, the masking rules and the retention period so the scope is clear.

Can our engineers make the OpenAI import change themselves?

In most cases, yes. Langfuse provides a drop-in replacement for the OpenAI Python SDK, so logging starts when the import changes from the standard openai module to langfuse.openai, and the same approach works for Azure OpenAI clients. The harder parts are not the import line. They are agreeing what content may be logged, setting user and session attributes consistently across services, confirming that the Langfuse host and keys are correct in each environment, and checking that traces show token counts and cost as expected. Teams with an internal platform group often handle the first application themselves and then decide whether a partner should cover the rest.

How long does a first test of OpenAI tracing take?

The length of a first test depends mainly on how much access your team has to the environment where the application runs. If developers can run the application against a self-hosted Langfuse they can reach, a first trace can be checked quickly. If the Langfuse instance, network path, keys or the application's deployment pipeline need approval or are in a restricted network, the first test waits on those steps. Before agreeing a timeline, confirm who can create project keys, whether the Langfuse host is reachable from development and staging, and whether a non-production Azure OpenAI or OpenAI key is available for testing. A written scope should state these dependencies.

What do our engineers and security reviewers need to provide?

Engineers need to identify each application that calls OpenAI or Azure OpenAI, the Python or other client code paths in use, and the environments where they run. Security reviewers need to decide what prompt and completion content may be stored, how long traces are kept, whether personal data must be masked, and who can view traces in the Langfuse interface. Both groups should confirm where keys are stored and how they rotate. Reviewers should also check that the Langfuse host is inside your approved network boundary and that traffic to the model provider is what you expect. Gathering these decisions before the work starts usually shortens review cycles.

Does the Azure OpenAI setup differ from the standard OpenAI setup?

The tracing approach is the same because Langfuse's OpenAI integration works with both OpenAI and Azure OpenAI clients. What changes is the client configuration: the endpoint, API version and deployment names come from your Azure resource, and those values must be set correctly in each application. Confirm the Azure resource details and the API version your applications use with your Azure administrators, and check that the model deployment names appear in traces so cost can be matched to the right model. Token and cost capture depends on the model being recognized, so verify pricing for each deployment you run.

When does a self-hosted Enterprise license matter for OpenAI tracing?

Tracing the OpenAI SDK itself does not require an Enterprise license key, because core tracing features are available in the MIT-licensed open source version. An Enterprise license becomes relevant when the rollout needs governance features such as project-level RBAC roles, data retention policies, audit logs, server-side data masking, or SCIM provisioning. If your security review requires those controls before traces containing prompts and completions are stored, plan for the license from the start. Confirm with Langfuse which features your use case needs and whether your organization's policies require them.

What should we confirm about token and cost capture before rollout?

Confirm that every model you call appears in traces with token counts, and that cost is calculated for the models you pay for. Langfuse records usage reported by the OpenAI or Azure OpenAI response, and cost depends on model pricing that Langfuse knows or that you configure. Ask your team to compare a sample of traces against the usage shown in your provider billing for a test period, and check how streaming responses and custom or fine-tuned model names are handled. Any gap should be written down as a known limit before reporting on spend.

Where the SDK wrapper stops and what to add

The drop-in OpenAI client only records calls made through that wrapped client inside Python code. Anything outside that boundary is invisible to Langfuse unless you add a second path. Before you sign off on coverage, inventory every place model calls originate: services written in other languages, batch jobs that call the REST API directly, third-party tools that hold their own API keys, and any internal gateway that forwards requests to OpenAI or Azure OpenAI. Each of those needs its own answer, and the wrapper will not provide it.

The usual alternatives are a gateway integration or OpenTelemetry. If requests already pass through a central gateway, logging at that layer captures traffic from many applications without changing each one, and the sibling topic on LiteLLM proxy integration covers the case where LiteLLM is that gateway. For applications written in other languages or built on frameworks, Langfuse accepts OpenTelemetry traces at its /api/public/otel endpoint, so instrumented services can send spans without the Python wrapper. Confirm with your own engineers which path each service will use, and record the decision per service so nobody assumes a call is traced when it is not.

Mixing paths creates a specific risk: the same request can appear twice, once from the wrapper and once from a gateway or instrumentation layer, which distorts token and cost totals. Decide which layer owns tracing for each model endpoint, and check in a test environment that one call produces one trace before you rely on the dashboards. Other integration topics in this group are listed in the sibling topics for this page, and you should use the ones that match your stack rather than assuming a connector exists for every tool.

How DeployOpen works on this

DeployOpen plans and deploys the Langfuse side of OpenAI and Azure OpenAI tracing inside your infrastructure, then hands over a configuration your engineers can review and run. The work covers the SDK change in your applications, the self-hosted Langfuse host they report to, and the user and session attributes your teams need to query traces later.

How we scope

  • Engagements are fixed-scope, with the list of OpenAI and Azure OpenAI applications to instrument agreed in writing before work starts.
  • The written scope names which Azure OpenAI deployments, client types and Python services are covered, and which are excluded.
  • We confirm with you which user and session identifiers may appear in traces and which fields must stay out of them.

How we build

  • We replace the standard OpenAI import with the Langfuse drop-in import in each in-scope service and test the call path end to end.
  • We point the SDK at your self-hosted Langfuse host through environment configuration, so no keys or host addresses sit in source code.
  • We verify token usage, model names and cost capture against a known set of test calls, and document any gaps we find.

How we hand over

  • You receive the code changes, configuration references and a runbook covering how to add user and session attributes to new calls.
  • We document which request content is logged, where it is stored, and how it can be reviewed by your security and compliance teams.
  • Knowledge transfer sessions with your engineers cover the Azure OpenAI setup, key rotation steps and how to confirm traces are arriving.

How we support

  • Ongoing support, SDK version updates and continuous testing are available as a retainer after handover.
  • A retainer can cover re-checking traces after OpenAI SDK upgrades or Langfuse SDK changes that affect the drop-in import.
  • Questions about SDK behavior, Azure endpoint settings or trace fields can be raised against the agreed scope during the engagement.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.