Learn how to manually instrument your code with the LangWatch Python SDK
with
/async with
)langwatch.trace()
and langwatch.span()
functions can be used directly as asynchronous (async with
) or synchronous (with
) context managers. This is the recommended approach for manual instrumentation as it automatically handles ending the trace/span, even if errors occur.
Here’s how you can achieve the same instrumentation as the decorator examples, but using context managers:
with langwatch.trace(...)
or async with langwatch.trace(...)
to start a trace.with langwatch.span(...)
or async with langwatch.span(...)
inside a trace block to create nested spans.as trace:
or as span:
part of the with
statement.span.add_event()
, and primarily span.update(...)
/ trace.update(...)
to add details. The update()
method is flexible for adding structured data like input
, output
, metadata
, and contexts
.span.end()
)langwatch.span()
or langwatch.trace()
directly to start them, and then explicitly call the end()
method on the returned object (span.end()
or trace.end()
) when the operation finishes. This requires careful handling to ensure end()
is always called, even if errors occur (e.g., using try...finally
). Context managers are generally preferred as they handle this automatically.