-
Notifications
You must be signed in to change notification settings - Fork 96
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
74 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""Middleware for making it easier to do distributed tracing.""" | ||
Check notice on line 1 in python/langsmith/middleware.py GitHub Actions / benchmarkBenchmark results
Check notice on line 1 in python/langsmith/middleware.py GitHub Actions / benchmarkComparison against main
|
||
|
||
|
||
class TracingMiddleware: | ||
"""Middleware for propagating distributed tracing context using LangSmith. | ||
This middleware checks for the 'langsmith-trace' header and propagates the | ||
tracing context if present. It does not start new traces by default. | ||
It is designed to work with ASGI applications. | ||
Attributes: | ||
app: The ASGI application being wrapped. | ||
""" | ||
|
||
def __init__(self, app): | ||
"""Initialize the middleware.""" | ||
from langsmith.run_helpers import tracing_context # type: ignore | ||
|
||
self._with_headers = tracing_context | ||
self.app = app | ||
|
||
async def __call__(self, scope: dict, receive, send): | ||
"""Handle incoming requests and propagate tracing context if applicable. | ||
Args: | ||
scope: A dict containing ASGI connection scope. | ||
receive: An awaitable callable for receiving ASGI events. | ||
send: An awaitable callable for sending ASGI events. | ||
If the request is HTTP and contains the 'langsmith-trace' header, | ||
it propagates the tracing context before calling the wrapped application. | ||
Otherwise, it calls the application directly without modifying the context. | ||
""" | ||
if scope["type"] == "http" and "headers" in scope: | ||
headers = dict(scope["headers"]) | ||
if b"langsmith-trace" in headers: | ||
with self._with_headers(parent=headers): | ||
await self.app(scope, receive, send) | ||
return | ||
await self.app(scope, receive, send) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters