Skip to content
This repository was archived by the owner on Nov 11, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/python-integration-tests/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ runs:
- name: Install dependencies
run: |
poetry install --with dev
poetry run pip install -U langchain langchain-openai langchain-anthropic tiktoken rapidfuzz vcrpy numpy
poetry run pip install -U langchain langchain-openai langchain-anthropic tiktoken rapidfuzz vcrpy numpy opentelemetry-api opentelemetry-sdk
shell: bash
working-directory: python

Expand Down
64 changes: 54 additions & 10 deletions python/langsmith/_internal/_background_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,30 @@ def _tracing_thread_handle_batch(
tracing_queue.task_done()


def _otel_tracing_thread_handle_batch(
client: Client,
tracing_queue: Queue,
batch: List[TracingQueueItem],
) -> None:
"""Handle a batch of tracing queue items by exporting them to OTEL."""
try:
ops = combine_serialized_queue_operations([item.item for item in batch])

run_ops = [op for op in ops if isinstance(op, SerializedRunOperation)]

if run_ops and client.otel_exporter is not None:
client.otel_exporter.export_batch(run_ops)
Comment thread
angus-langchain marked this conversation as resolved.
Resolved

except Exception:
logger.error("Error in OTEL tracing queue", exc_info=True)
# Exceptions are logged elsewhere, but we need to make sure the
# background thread continues to run
finally:
# Mark all items in the batch as done
for _ in batch:
tracing_queue.task_done()


def get_size_limit_from_env() -> Optional[int]:
size_limit_str = ls_utils.get_env_var(
"BATCH_INGEST_SIZE_LIMIT",
Expand Down Expand Up @@ -223,8 +247,12 @@ def tracing_control_thread_func(client_ref: weakref.ref[Client]) -> None:
# 1 for this func, 1 for getrefcount, 1 for _get_data_type_cached
num_known_refs = 3

disable_compression = ls_utils.get_env_var("DISABLE_RUN_COMPRESSION")
if not ls_utils.is_truish(disable_compression) and use_multipart:
# Disable compression if explicitly set or if using OpenTelemetry
disable_compression = (
ls_utils.is_truish(ls_utils.get_env_var("DISABLE_RUN_COMPRESSION"))
or client.otel_exporter is not None
)
if not disable_compression and use_multipart:
if not (client.info.instance_flags or {}).get(
"zstd_compression_enabled", False
):
Expand Down Expand Up @@ -278,15 +306,23 @@ def keep_thread_active() -> bool:
sub_threads.append(new_thread)
new_thread.start()
if next_batch := _tracing_thread_drain_queue(tracing_queue, limit=size_limit):
_tracing_thread_handle_batch(
client, tracing_queue, next_batch, use_multipart
)
if client.otel_exporter is not None:
_otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
else:
_tracing_thread_handle_batch(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to have both OTEL and regular LangSmith tracing or would only go to one or the other?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one or the other, but ls accepts the otel messages

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ack on "one or the other", but the latter point "accepts the otel messages" is probably not that useful unless I missed something.

If you run it with opentelemetry-instrument to bootstrap the otel exporters, both langsmith and other instrumentation will export to the same collector. That's true.

However, they will be in different traces as the tracer implementation here is an export only-concern. Meaning it cannot propagate trace context to normal otel instrumentation. For that reason, they'd be in different traces, and likely less useful as a result.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adrian Cole (@codefromthecrypt) I was referring to LangSmith if a user wanted to fan out on receiver to multiple OTel backends. ack that this implementation is export only, but it should still be possible to inject headers into LangSmith OTel tracing. Would be happy to work with you as a design partner to discuss future features for distributed tracing with you though!

client, tracing_queue, next_batch, use_multipart
)

# drain the queue on exit
while next_batch := _tracing_thread_drain_queue(
tracing_queue, limit=size_limit, block=False
):
_tracing_thread_handle_batch(client, tracing_queue, next_batch, use_multipart)
if client.otel_exporter is not None:
_otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
else:
_tracing_thread_handle_batch(
client, tracing_queue, next_batch, use_multipart
)


def tracing_control_thread_func_compress_parallel(
Expand Down Expand Up @@ -446,14 +482,22 @@ def _tracing_sub_thread_func(
):
if next_batch := _tracing_thread_drain_queue(tracing_queue, limit=size_limit):
seen_successive_empty_queues = 0
_tracing_thread_handle_batch(
client, tracing_queue, next_batch, use_multipart
)
if client.otel_exporter is not None:
_otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
else:
_tracing_thread_handle_batch(
client, tracing_queue, next_batch, use_multipart
)
else:
seen_successive_empty_queues += 1

# drain the queue on exit
while next_batch := _tracing_thread_drain_queue(
tracing_queue, limit=size_limit, block=False
):
_tracing_thread_handle_batch(client, tracing_queue, next_batch, use_multipart)
if client.otel_exporter is not None:
_otel_tracing_thread_handle_batch(client, tracing_queue, next_batch)
else:
_tracing_thread_handle_batch(
client, tracing_queue, next_batch, use_multipart
)
74 changes: 74 additions & 0 deletions python/langsmith/_internal/otel/_otel_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""Client configuration for OpenTelemetry integration with LangSmith."""

import os

from langsmith import utils as ls_utils

HAS_OTEL = False
try:
if ls_utils.is_truish(ls_utils.get_env_var("OTEL_ENABLED")):
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import (
SERVICE_NAME,
Resource,
)
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
)

HAS_OTEL = True
except ImportError:
pass


def get_otlp_tracer_provider() -> "TracerProvider":
"""Get the OTLP tracer provider for LangSmith.

This function creates a tracer provider that exports spans using the OTLP protocol
with LangSmith-specific defaults:

- OTEL_EXPORTER_OTLP_ENDPOINT: https://api.smith.langchain.com/otel
- OTEL_EXPORTER_OTLP_HEADERS: Contains x-api-key from LangSmith API key and
Langsmith-Project header if project is configured

These defaults can be overridden by setting the environment variables before
calling this function.

Returns:
TracerProvider: The OTLP tracer provider.
"""
# Set LangSmith-specific defaults if not already set in environment
if not HAS_OTEL:
raise ImportError(
"OpenTelemetry packages are required to use this function. "
"Please install with `pip install langsmith[otel]`"
)

if "OTEL_EXPORTER_OTLP_ENDPOINT" not in os.environ:
ls_endpoint = ls_utils.get_api_url(None)
os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = f"{ls_endpoint}/otel"

# Configure headers with API key and project if available
if "OTEL_EXPORTER_OTLP_HEADERS" not in os.environ:
api_key = ls_utils.get_api_key(None)
headers = f"x-api-key={api_key}"

project = ls_utils.get_tracer_project()
if project:
headers += f",Langsmith-Project={project}"

os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers

service_name = os.environ.get("OTEL_SERVICE_NAME", "langsmith")
resource = Resource(attributes={SERVICE_NAME: service_name})

tracer_provider = TracerProvider(resource=resource)

otlp_exporter = OTLPSpanExporter()
span_processor = BatchSpanProcessor(otlp_exporter)
tracer_provider.add_span_processor(span_processor)

return tracer_provider
Loading