Skip to content

Conversation

@viniciusdsmello
Copy link
Contributor

Pull Request

Summary

Fix context loss issue in LiteLLM streaming traces when generators are partially consumed or run in ASGI worker threads.

Changes

  • Preserve contextvars.Context in litellm_tracer.py using copy_context() and captured_context.run() for trace finalization
  • Add null guard for logger during Python interpreter shutdown in streaming finally block

Context

When using LiteLLM streaming with FastAPI/Starlette, traces showed "Processing..." and null output. Root cause: contextvars don't propagate when generators are consumed in different threads (via anyio.to_thread). The fix captures context at generator creation and restores it when finalizing the trace.

Testing

  • Manual testing

@viniciusdsmello viniciusdsmello self-assigned this Dec 29, 2025
@viniciusdsmello viniciusdsmello added the bug Something isn't working label Dec 29, 2025
@viniciusdsmello viniciusdsmello changed the title fix(tracer): handle missing active trace and improve error logging in LiteLLM integration fix(closes OPEN-8569): handle missing active trace and improve error logging in LiteLLM integration Dec 29, 2025
@viniciusdsmello viniciusdsmello force-pushed the vini/open-8569-bug-trace-context-is-lost-when-using-asgi-workers branch from 256cb4c to 2710dc9 Compare December 29, 2025 20:43
@viniciusdsmello viniciusdsmello merged commit d35f78c into main Dec 29, 2025
5 checks passed
@viniciusdsmello viniciusdsmello deleted the vini/open-8569-bug-trace-context-is-lost-when-using-asgi-workers branch December 29, 2025 20:48
@stainless-app stainless-app bot mentioned this pull request Dec 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants