|
| 1 | +require "test_helper" |
| 2 | + |
| 3 | +class InstrumentationTest < Minitest::Test |
| 4 | + def setup |
| 5 | + EXPORTER.reset |
| 6 | + |
| 7 | + RubyLLM.configure do |c| |
| 8 | + c.openai_api_key = "fake-key-for-testing" |
| 9 | + end |
| 10 | + end |
| 11 | + |
| 12 | + def test_creates_span_with_attributes |
| 13 | + stub_request(:post, "https://api.openai.com/v1/chat/completions") |
| 14 | + .to_return( |
| 15 | + status: 200, |
| 16 | + headers: { "Content-Type" => "application/json" }, |
| 17 | + body: { |
| 18 | + id: "chatcmpl-123", |
| 19 | + object: "chat.completion", |
| 20 | + model: "gpt-4o-mini", |
| 21 | + choices: [ |
| 22 | + { |
| 23 | + index: 0, |
| 24 | + message: { role: "assistant", content: "Hello, world!" }, |
| 25 | + finish_reason: "stop" |
| 26 | + } |
| 27 | + ], |
| 28 | + usage: { |
| 29 | + prompt_tokens: 10, |
| 30 | + completion_tokens: 5, |
| 31 | + total_tokens: 15 |
| 32 | + } |
| 33 | + }.to_json |
| 34 | + ) |
| 35 | + |
| 36 | + chat = RubyLLM.chat(model: "gpt-4o-mini") |
| 37 | + chat.ask("Hi") |
| 38 | + |
| 39 | + spans = EXPORTER.finished_spans |
| 40 | + assert_equal 1, spans.length |
| 41 | + |
| 42 | + span = spans.first |
| 43 | + assert_equal OpenTelemetry::Trace::SpanKind::CLIENT, span.kind |
| 44 | + assert_equal "chat gpt-4o-mini", span.name |
| 45 | + assert_equal "openai", span.attributes["gen_ai.provider.name"] |
| 46 | + assert_equal "gpt-4o-mini", span.attributes["gen_ai.request.model"] |
| 47 | + assert_equal "chat", span.attributes["gen_ai.operation.name"] |
| 48 | + assert_equal 10, span.attributes["gen_ai.usage.input_tokens"] |
| 49 | + assert_equal 5, span.attributes["gen_ai.usage.output_tokens"] |
| 50 | + end |
| 51 | + |
| 52 | + def test_records_error_on_api_failure |
| 53 | + stub_request(:post, "https://api.openai.com/v1/chat/completions") |
| 54 | + .to_return(status: 500, body: "Internal Server Error") |
| 55 | + |
| 56 | + chat = RubyLLM.chat(model: "gpt-4o-mini") |
| 57 | + |
| 58 | + assert_raises do |
| 59 | + chat.ask("Hi") |
| 60 | + end |
| 61 | + |
| 62 | + spans = EXPORTER.finished_spans |
| 63 | + span = spans.last |
| 64 | + |
| 65 | + assert_equal "chat gpt-4o-mini", span.name |
| 66 | + assert span.attributes["error.type"] |
| 67 | + assert_equal OpenTelemetry::Trace::Status::ERROR, span.status.code |
| 68 | + end |
| 69 | +end |
0 commit comments