Class: Ollama::Middleware::Tracing

Inherits:
Ollama::Middleware show all
Defined in:
lib/ollama/middleware/tracing.rb

Overview

Tracing middleware - adds distributed tracing support

Defined Under Namespace

Classes: NoOpContext, NoOpSpan

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Ollama::Middleware

#around

Constructor Details

#initialize(tracer: nil, service_name: "ollama-client") ⇒ Tracing

Returns a new instance of Tracing.



11
12
13
14
15
# File 'lib/ollama/middleware/tracing.rb', line 11

def initialize(tracer: nil, service_name: "ollama-client")
  super()
  @tracer = tracer || default_tracer
  @service_name = service_name
end

Instance Attribute Details

#service_nameObject (readonly)

Returns the value of attribute service_name.



9
10
11
# File 'lib/ollama/middleware/tracing.rb', line 9

def service_name
  @service_name
end

#tracerObject (readonly)

Returns the value of attribute tracer.



9
10
11
# File 'lib/ollama/middleware/tracing.rb', line 9

def tracer
  @tracer
end

Instance Method Details

#after_response(response, env) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ollama/middleware/tracing.rb', line 46

def after_response(response, env)
  span = env[:trace_span]
  return response unless span

  span.set_tag("http.status_code", response.status)
  span.set_tag("ollama.success", response.success?.to_s)

  span.set_tag("duration_ms", env[:duration_ms]) if env[:duration_ms]

  span.finish
  env[:trace_span] = nil
  response
end

#before_request(request, env) ⇒ Object



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
# File 'lib/ollama/middleware/tracing.rb', line 17

def before_request(request, env)
  return request unless @tracer

  span = @tracer.start_span(
    "ollama.request",
    service: @service_name,
    tags: {
      "ollama.endpoint" => request.endpoint,
      "ollama.model" => request.model,
      "ollama.streaming" => request.streaming?.to_s,
      "span.kind" => "client"
    }
  )

  env[:trace_span] = span

  # Inject trace context into headers if both the tracer and the
  # request object support it (Ollama::Request itself does not carry
  # headers — auth/headers are applied at the transport layer — but a
  # custom Request-like object passed by a caller might).
  if @tracer.respond_to?(:inject) && request.respond_to?(:with_headers) && request.respond_to?(:headers)
    headers = {}
    @tracer.inject(span.context, headers)
    request = request.with_headers(request.headers.merge(headers))
  end

  request
end

#on_error(error, env) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ollama/middleware/tracing.rb', line 60

def on_error(error, env)
  span = env[:trace_span]
  return nil unless span

  span.set_tag("error", true)
  span.set_tag("error.type", error.class.name)
  span.set_tag("error.message", error.message)
  span.finish
  env[:trace_span] = nil
  nil
end