Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example middleware for langsmith tracing #101

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/server/main.py
Expand Up @@ -14,6 +14,7 @@
ExtractResponse,
extraction_runnable,
)
from server.middleware import add_langsmith_tracing

logger = logging.getLogger(__name__)

Expand All @@ -30,6 +31,9 @@
)


add_langsmith_tracing = app.middleware("http")(add_langsmith_tracing)


ROOT = Path(__file__).parent.parent

ORIGINS = os.environ.get("CORS_ORIGINS", "").split(",")
Expand Down
31 changes: 31 additions & 0 deletions backend/server/middleware.py
@@ -0,0 +1,31 @@
"""Add example middleware to enable langsmith tracing on selected endpoints.

This enables langsmith tracing on selected endpoints, showing how to add
tags and metadata to the traces.
"""
from urllib.parse import urlparse

from langchain_core.tracers.context import tracing_v2_enabled
from langsmith import trace
from starlette.requests import Request


async def add_langsmith_tracing(request: Request, call_next):
"""Add langsmith middleware"""
with tracing_v2_enabled():
parsed_url = urlparse(str(request.url))
if parsed_url.path not in {"/suggest", "/extract", "/extract/shared"}:
# Skip tracing for all other endpoints
return await call_next(request)

method = request.method

with trace(
name=parsed_url.path,
tags=[method],
metadata={
"__useragent": request.headers.get("user-agent"),
},
):
response = await call_next(request)
return response