Class: LangsmithrbRails::RequestTracing

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/langsmithrb_rails/tracing/templates/request_tracing.rb

Overview

Middleware for tracing Rails requests in LangSmith

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ RequestTracing



6
7
8
# File 'lib/generators/langsmithrb_rails/tracing/templates/request_tracing.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/generators/langsmithrb_rails/tracing/templates/request_tracing.rb', line 10

def call(env)
  # Skip tracing if sampling rate check fails
  return @app.call(env) if rand > LangsmithrbRails::Config[:sampling_rate]

  req = ActionDispatch::Request.new(env)
  
  # Prepare metadata for the trace
  meta = {
    path: req.path,
    method: req.request_method,
    request_id: req.request_id,
    env: LangsmithrbRails::Config[:env]
  }
  
  # Add user reference if available (and not in development/test)
  if defined?(Current) && Current.respond_to?(:user) && Current.user && !%w[development test].include?(Rails.env)
    # Use a hash of the user ID to avoid sending PII
    meta[:user_ref] = Digest::SHA256.hexdigest(Current.user.id.to_s)
  end
  
  # Create the run in LangSmith
  client = LangsmithrbRails::Client.new
  started = Time.now
  
  # Create the run asynchronously if possible
  run = create_run_async(client, {
    name: "rails_request",
    run_type: "request",
    meta: meta.merge(started_at: started.iso8601)
  })
  
  # Store run ID in thread local for child spans
  Thread.current[:langsmith_run_id] = run&.dig(:body, "id")
  
  # Process the request
  status, headers, body = @app.call(env)
  
  # Update the run asynchronously if possible
  if run&.dig(:body, "id")
    update_run_async(client, run.dig(:body, "id"), {
      ended_at: Time.now.iso8601,
      output: { status: status }
    })
  end
  
  # Clean up thread local
  Thread.current[:langsmith_run_id] = nil
  
  [status, headers, body]
rescue => e
  # Log error but don't fail the request
  Rails.logger.error("LangSmith tracing error: #{e.message}")
  
  # Clean up thread local
  Thread.current[:langsmith_run_id] = nil
  
  # Continue with the request
  @app.call(env)
end