braintrust 0.0.1.alpha.2 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2f2fd3e289b473dc2f40c2fe9df914c1b1b7ee2ac06db54656fa24eb06a3ff5a
4
- data.tar.gz: 562aadfd39d224e5052685ed73c4f2a504db4df01fd26445bf4b0411a8987bb5
3
+ metadata.gz: be1db72d5636027cfb0b1744e0c30ac9b7169b7f898d4a911639d9f437e0654a
4
+ data.tar.gz: 725708134bfa2a8d12a3fb0c74e9a54f97afe2f249ed6e3d26184cc5c97a3775
5
5
  SHA512:
6
- metadata.gz: db90cc0be88cd3c5a88b59d0b87829c88cec76f15bb1213840efb239474a389c95be62ba41efcdb0b87e069845f71873ee7cfefc224e2ba1d4e5d7affbd536a3
7
- data.tar.gz: 8ff1ace52cc31b7feae57c557e029f09f8fd811cc2163fb042a5b9e9965b6a9eef2f00e9c543d5c177ec52b04163b119bb5c68dfb57d73d72d7dc63b2974f213
6
+ metadata.gz: 85cda56b35738299973d2d58a001c9cb746c168437de56e9cf443a2787728dc98014b2b63cf5d6f0d781b8d5c443feedc42dab5abaae2827b60f1c80eb38329a
7
+ data.tar.gz: e99f24f4cfabbffbdc21822e35145794ccdf29bd22d2e47889dfaab30b4428b49ae173c3ad3e12c4fc7169e3a61ed493670c55bacacd25a800c5df28dc68269f
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Braintrust
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md CHANGED
@@ -1,24 +1,196 @@
1
1
  # Braintrust Ruby SDK
2
2
 
3
- Ruby SDK for [Braintrust](https://www.braintrust.dev) - AI evaluation and observability platform.
3
+ [![Gem Version](https://badge.fury.io/rb/braintrust.svg)](https://badge.fury.io/rb/braintrust)
4
+ ![Beta](https://img.shields.io/badge/status-beta-yellow)
4
5
 
5
- ## Status
6
+ ## Overview
6
7
 
7
- 🚧 Under active development
8
+ This library provides tools for **evaluating** and **tracing** AI applications in [Braintrust](https://www.braintrust.dev). Use it to:
8
9
 
9
- ## Development
10
+ - **Evaluate** your AI models with custom test cases and scoring functions
11
+ - **Trace** LLM calls and monitor AI application performance with OpenTelemetry
12
+ - **Integrate** seamlessly with OpenAI and other LLM providers
13
+
14
+ This SDK is currently in BETA status and APIs may change.
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'braintrust'
22
+ ```
23
+
24
+ And then execute:
10
25
 
11
26
  ```bash
12
- ./scripts/install-deps.sh
13
- mise install
14
- cp .env.example .env
15
- rake test
27
+ bundle install
16
28
  ```
17
29
 
18
- ## License
30
+ Or install it yourself as:
31
+
32
+ ```bash
33
+ gem install braintrust
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ### Set up your API key
39
+
40
+ ```bash
41
+ export BRAINTRUST_API_KEY="your-api-key"
42
+ ```
43
+
44
+ ### Evals
45
+
46
+ ```ruby
47
+ require "braintrust"
48
+
49
+ # Initialize Braintrust
50
+ Braintrust.init
51
+
52
+ # Simple food classifier (the code being evaluated)
53
+ def classify_food(input)
54
+ fruit = %w[apple banana strawberry orange grape mango]
55
+ vegetable = %w[carrot broccoli spinach potato tomato cucumber]
56
+
57
+ input_lower = input.downcase
58
+ return "fruit" if fruit.any? { |f| input_lower.include?(f) }
59
+ return "vegetable" if vegetable.any? { |v| input_lower.include?(v) }
60
+ "unknown"
61
+ end
62
+
63
+ # Run an evaluation
64
+ result = Braintrust::Eval.run(
65
+ project: "my-project",
66
+ experiment: "food-classifier-eval",
67
+
68
+ # Test cases
69
+ cases: [
70
+ {input: "apple", expected: "fruit"},
71
+ {input: "carrot", expected: "vegetable"},
72
+ {input: "banana", expected: "fruit"},
73
+ {input: "broccoli", expected: "vegetable"}
74
+ ],
75
+
76
+ # Task to evaluate
77
+ task: ->(input) { classify_food(input) },
78
+
79
+ # Scorers to judge output quality
80
+ scorers: [
81
+ Braintrust::Eval.scorer("exact_match") { |input, expected, output|
82
+ (output == expected) ? 1.0 : 0.0
83
+ }
84
+ ]
85
+ )
86
+
87
+ # View results
88
+ puts "View results at: #{result.permalink}"
89
+ ```
90
+
91
+ ### Tracing
92
+
93
+ ```ruby
94
+ require "braintrust"
95
+ require "opentelemetry/sdk"
96
+
97
+ # Initialize Braintrust
98
+ Braintrust.init
19
99
 
20
- Apache-2.0
100
+ # Get a tracer
101
+ tracer = OpenTelemetry.tracer_provider.tracer("my-app")
102
+
103
+ # Create spans to track operations
104
+ tracer.in_span("process-data") do |span|
105
+ span.set_attribute("user.id", "123")
106
+ span.set_attribute("operation.type", "data_processing")
107
+
108
+ # Your code here
109
+ puts "Processing data..."
110
+ sleep 0.1
111
+
112
+ # Nested spans are automatically linked
113
+ tracer.in_span("nested-operation") do |nested_span|
114
+ nested_span.set_attribute("step", "1")
115
+ puts "Nested operation..."
116
+ end
117
+ end
118
+
119
+ # Shutdown to flush spans
120
+ OpenTelemetry.tracer_provider.shutdown
121
+
122
+ puts "View trace in Braintrust!"
123
+ ```
124
+
125
+ ### OpenAI Tracing
126
+
127
+ ```ruby
128
+ require "braintrust"
129
+ require "openai"
130
+
131
+ # Initialize Braintrust
132
+ Braintrust.init
133
+
134
+ # Create OpenAI client
135
+ client = OpenAI::Client.new(api_key: ENV["OPENAI_API_KEY"])
136
+
137
+ # Wrap the client with Braintrust tracing
138
+ Braintrust::Trace::OpenAI.wrap(client)
139
+
140
+ # Create a root span to capture the operation
141
+ tracer = OpenTelemetry.tracer_provider.tracer("openai-app")
142
+ root_span = nil
143
+
144
+ # Make a chat completion request (automatically traced!)
145
+ response = tracer.in_span("chat-completion") do |span|
146
+ root_span = span
147
+
148
+ client.chat.completions.create(
149
+ messages: [
150
+ {role: "system", content: "You are a helpful assistant."},
151
+ {role: "user", content: "Say hello!"}
152
+ ],
153
+ model: "gpt-4o-mini",
154
+ max_tokens: 100
155
+ )
156
+ end
157
+
158
+ puts "Response: #{response.choices[0].message.content}"
159
+
160
+ # View the trace
161
+ puts "View trace at: #{Braintrust::Trace.permalink(root_span)}"
162
+
163
+ # Shutdown to flush spans
164
+ OpenTelemetry.tracer_provider.shutdown
165
+ ```
166
+
167
+ ## Features
168
+
169
+ - **Evaluations**: Run systematic evaluations of your AI systems with custom scoring functions
170
+ - **Tracing**: Automatic instrumentation for OpenAI API calls with OpenTelemetry
171
+ - **Datasets**: Manage and version your evaluation datasets
172
+ - **Experiments**: Track different versions and configurations of your AI systems
173
+ - **Observability**: Monitor your AI applications in production
174
+
175
+ ## Examples
176
+
177
+ Check out the [`examples/`](./examples/) directory for complete working examples:
178
+
179
+ - [eval.rb](./examples/eval.rb) - Create and run evaluations with custom test cases and scoring functions
180
+ - [trace.rb](./examples/trace.rb) - Manual span creation and tracing
181
+ - [openai.rb](./examples/openai.rb) - Automatically trace OpenAI API calls
182
+ - [eval/dataset.rb](./examples/eval/dataset.rb) - Run evaluations using datasets stored in Braintrust
183
+ - [eval/remote_functions.rb](./examples/eval/remote_functions.rb) - Use remote scoring functions
184
+
185
+ ## Documentation
186
+
187
+ - [Braintrust Documentation](https://www.braintrust.dev/docs)
188
+ - [API Documentation](https://rubydoc.info/gems/braintrust)
21
189
 
22
190
  ## Contributing
23
191
 
24
- See [CONTRIBUTING.md](CONTRIBUTING.md)
192
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup and contribution guidelines.
193
+
194
+ ## License
195
+
196
+ This project is licensed under the Apache License 2.0. See the [LICENSE](./LICENSE) file for details.
@@ -26,6 +26,17 @@ module Braintrust
26
26
  # @return [AuthResult] org info
27
27
  # @raise [Braintrust::Error] if login fails
28
28
  def self.login(api_key:, app_url:, org_name: nil)
29
+ # Test mode: return fake auth for test API key
30
+ if api_key == "test-api-key"
31
+ Log.debug("Login: using test API key, returning fake auth")
32
+ return AuthResult.new(
33
+ org_id: "test-org-id",
34
+ org_name: org_name || "test-org",
35
+ api_url: "https://api.ruby-sdk-fixture.com",
36
+ proxy_url: "https://proxy.ruby-sdk-fixture.com"
37
+ )
38
+ end
39
+
29
40
  masked_key = mask_api_key(api_key)
30
41
  Log.debug("Login: attempting login with API key #{masked_key}, org #{org_name.inspect}, app URL #{app_url}")
31
42
 
@@ -4,12 +4,12 @@ module Braintrust
4
4
  # Configuration object that reads from environment variables
5
5
  # and allows overriding with explicit options
6
6
  class Config
7
- attr_reader :api_key, :org_name, :default_parent, :app_url, :api_url
7
+ attr_reader :api_key, :org_name, :default_project, :app_url, :api_url
8
8
 
9
- def initialize(api_key: nil, org_name: nil, default_parent: nil, app_url: nil, api_url: nil)
9
+ def initialize(api_key: nil, org_name: nil, default_project: nil, app_url: nil, api_url: nil)
10
10
  @api_key = api_key
11
11
  @org_name = org_name
12
- @default_parent = default_parent
12
+ @default_project = default_project
13
13
  @app_url = app_url
14
14
  @api_url = api_url
15
15
  end
@@ -20,7 +20,7 @@ module Braintrust
20
20
  defaults = {
21
21
  api_key: ENV["BRAINTRUST_API_KEY"],
22
22
  org_name: ENV["BRAINTRUST_ORG_NAME"],
23
- default_parent: ENV["BRAINTRUST_DEFAULT_PROJECT"],
23
+ default_project: ENV["BRAINTRUST_DEFAULT_PROJECT"],
24
24
  app_url: ENV["BRAINTRUST_APP_URL"] || "https://www.braintrust.dev",
25
25
  api_url: ENV["BRAINTRUST_API_URL"] || "https://api.braintrust.dev"
26
26
  }
@@ -6,12 +6,12 @@ module Braintrust
6
6
  # State object that holds Braintrust configuration
7
7
  # Thread-safe global state management
8
8
  class State
9
- attr_reader :api_key, :org_name, :org_id, :default_parent, :app_url, :api_url, :proxy_url, :logged_in
9
+ attr_reader :api_key, :org_name, :org_id, :default_project, :app_url, :api_url, :proxy_url, :logged_in
10
10
 
11
11
  @mutex = Mutex.new
12
12
  @global_state = nil
13
13
 
14
- def initialize(api_key: nil, org_name: nil, org_id: nil, default_parent: nil, app_url: nil, api_url: nil, proxy_url: nil, logged_in: false)
14
+ def initialize(api_key: nil, org_name: nil, org_id: nil, default_project: nil, app_url: nil, api_url: nil, proxy_url: nil, logged_in: false)
15
15
  # Instance-level mutex for thread-safe login
16
16
  @login_mutex = Mutex.new
17
17
  raise ArgumentError, "api_key is required" if api_key.nil? || api_key.empty?
@@ -19,7 +19,7 @@ module Braintrust
19
19
  @api_key = api_key
20
20
  @org_name = org_name
21
21
  @org_id = org_id
22
- @default_parent = default_parent
22
+ @default_project = default_project
23
23
  @app_url = app_url || "https://www.braintrust.dev"
24
24
  @api_url = api_url
25
25
  @proxy_url = proxy_url
@@ -0,0 +1,528 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry/sdk"
4
+ require "json"
5
+
6
+ module Braintrust
7
+ module Trace
8
+ module OpenAI
9
+ # Helper to safely set a JSON attribute on a span
10
+ # Only sets the attribute if obj is present
11
+ # @param span [OpenTelemetry::Trace::Span] the span to set attribute on
12
+ # @param attr_name [String] the attribute name (e.g., "braintrust.output_json")
13
+ # @param obj [Object] the object to serialize to JSON
14
+ # @return [void]
15
+ def self.set_json_attr(span, attr_name, obj)
16
+ return unless obj
17
+ span.set_attribute(attr_name, JSON.generate(obj))
18
+ end
19
+
20
+ # Parse usage tokens from OpenAI API response, handling nested token_details
21
+ # Maps OpenAI field names to Braintrust standard names:
22
+ # - input_tokens → prompt_tokens
23
+ # - output_tokens → completion_tokens
24
+ # - total_tokens → tokens
25
+ # - *_tokens_details.* → prefix_*
26
+ #
27
+ # @param usage [Hash, Object] usage object from OpenAI response
28
+ # @return [Hash<String, Integer>] metrics hash with normalized names
29
+ def self.parse_usage_tokens(usage)
30
+ metrics = {}
31
+ return metrics unless usage
32
+
33
+ # Convert to hash if it's an object
34
+ usage_hash = usage.respond_to?(:to_h) ? usage.to_h : usage
35
+
36
+ usage_hash.each do |key, value|
37
+ key_str = key.to_s
38
+
39
+ # Handle nested *_tokens_details objects
40
+ if key_str.end_with?("_tokens_details")
41
+ # Convert to hash if it's an object (OpenAI gem returns objects)
42
+ details_hash = value.respond_to?(:to_h) ? value.to_h : value
43
+ next unless details_hash.is_a?(Hash)
44
+
45
+ # Extract prefix (e.g., "prompt" from "prompt_tokens_details")
46
+ prefix = key_str.sub(/_tokens_details$/, "")
47
+ # Translate "input" → "prompt", "output" → "completion"
48
+ prefix = translate_metric_prefix(prefix)
49
+
50
+ # Process nested fields (e.g., cached_tokens, reasoning_tokens)
51
+ details_hash.each do |detail_key, detail_value|
52
+ next unless detail_value.is_a?(Numeric)
53
+ metrics["#{prefix}_#{detail_key}"] = detail_value.to_i
54
+ end
55
+ elsif value.is_a?(Numeric)
56
+ # Handle top-level token fields
57
+ case key_str
58
+ when "input_tokens"
59
+ metrics["prompt_tokens"] = value.to_i
60
+ when "output_tokens"
61
+ metrics["completion_tokens"] = value.to_i
62
+ when "total_tokens"
63
+ metrics["tokens"] = value.to_i
64
+ else
65
+ # Keep other numeric fields as-is (future-proofing)
66
+ metrics[key_str] = value.to_i
67
+ end
68
+ end
69
+ end
70
+
71
+ metrics
72
+ end
73
+
74
+ # Translate metric prefix to be consistent between different API formats
75
+ # @param prefix [String] the prefix to translate
76
+ # @return [String] translated prefix
77
+ def self.translate_metric_prefix(prefix)
78
+ case prefix
79
+ when "input"
80
+ "prompt"
81
+ when "output"
82
+ "completion"
83
+ else
84
+ prefix
85
+ end
86
+ end
87
+
88
+ # Aggregate streaming chunks into a single response structure
89
+ # Follows the Go SDK logic for aggregating deltas
90
+ # @param chunks [Array<Hash>] array of chunk hashes from stream
91
+ # @return [Hash] aggregated response with choices, usage, etc.
92
+ def self.aggregate_streaming_chunks(chunks)
93
+ return {} if chunks.empty?
94
+
95
+ # Initialize aggregated structure
96
+ aggregated = {
97
+ id: nil,
98
+ created: nil,
99
+ model: nil,
100
+ system_fingerprint: nil,
101
+ choices: [],
102
+ usage: nil
103
+ }
104
+
105
+ # Track aggregated content and tool_calls for each choice index
106
+ choice_data = {}
107
+
108
+ chunks.each do |chunk|
109
+ # Capture top-level fields from any chunk that has them
110
+ aggregated[:id] ||= chunk[:id]
111
+ aggregated[:created] ||= chunk[:created]
112
+ aggregated[:model] ||= chunk[:model]
113
+ aggregated[:system_fingerprint] ||= chunk[:system_fingerprint]
114
+
115
+ # Aggregate usage (usually only in last chunk if stream_options.include_usage is set)
116
+ if chunk[:usage]
117
+ aggregated[:usage] = chunk[:usage]
118
+ end
119
+
120
+ # Process choices
121
+ next unless chunk[:choices].is_a?(Array)
122
+ chunk[:choices].each do |choice|
123
+ index = choice[:index] || 0
124
+ choice_data[index] ||= {
125
+ index: index,
126
+ role: nil,
127
+ content: "",
128
+ tool_calls: [],
129
+ finish_reason: nil
130
+ }
131
+
132
+ delta = choice[:delta] || {}
133
+
134
+ # Aggregate role (set once from first delta that has it)
135
+ choice_data[index][:role] ||= delta[:role]
136
+
137
+ # Aggregate content
138
+ if delta[:content]
139
+ choice_data[index][:content] += delta[:content]
140
+ end
141
+
142
+ # Aggregate tool_calls (similar to Go SDK logic)
143
+ if delta[:tool_calls].is_a?(Array) && delta[:tool_calls].any?
144
+ delta[:tool_calls].each do |tool_call_delta|
145
+ # Check if this is a new tool call or continuation
146
+ if tool_call_delta[:id] && !tool_call_delta[:id].empty?
147
+ # New tool call
148
+ choice_data[index][:tool_calls] << {
149
+ id: tool_call_delta[:id],
150
+ type: tool_call_delta[:type],
151
+ function: {
152
+ name: tool_call_delta.dig(:function, :name) || "",
153
+ arguments: tool_call_delta.dig(:function, :arguments) || ""
154
+ }
155
+ }
156
+ elsif choice_data[index][:tool_calls].any?
157
+ # Continuation - append arguments to last tool call
158
+ last_tool_call = choice_data[index][:tool_calls].last
159
+ if tool_call_delta.dig(:function, :arguments)
160
+ last_tool_call[:function][:arguments] += tool_call_delta[:function][:arguments]
161
+ end
162
+ end
163
+ end
164
+ end
165
+
166
+ # Capture finish_reason
167
+ if choice[:finish_reason]
168
+ choice_data[index][:finish_reason] = choice[:finish_reason]
169
+ end
170
+ end
171
+ end
172
+
173
+ # Build final choices array
174
+ aggregated[:choices] = choice_data.values.sort_by { |c| c[:index] }.map do |choice|
175
+ message = {
176
+ role: choice[:role],
177
+ content: choice[:content].empty? ? nil : choice[:content]
178
+ }
179
+
180
+ # Add tool_calls to message if any
181
+ message[:tool_calls] = choice[:tool_calls] if choice[:tool_calls].any?
182
+
183
+ {
184
+ index: choice[:index],
185
+ message: message,
186
+ finish_reason: choice[:finish_reason]
187
+ }
188
+ end
189
+
190
+ aggregated
191
+ end
192
+
193
+ # Wrap an OpenAI::Client to automatically create spans for chat completions and responses
194
+ # Supports both synchronous and streaming requests
195
+ # @param client [OpenAI::Client] the OpenAI client to wrap
196
+ # @param tracer_provider [OpenTelemetry::SDK::Trace::TracerProvider] the tracer provider (defaults to global)
197
+ def self.wrap(client, tracer_provider: nil)
198
+ tracer_provider ||= ::OpenTelemetry.tracer_provider
199
+
200
+ # Wrap chat completions
201
+ wrap_chat_completions(client, tracer_provider)
202
+
203
+ # Wrap responses API if available
204
+ wrap_responses(client, tracer_provider) if client.respond_to?(:responses)
205
+
206
+ client
207
+ end
208
+
209
+ # Wrap chat completions API
210
+ # @param client [OpenAI::Client] the OpenAI client
211
+ # @param tracer_provider [OpenTelemetry::SDK::Trace::TracerProvider] the tracer provider
212
+ def self.wrap_chat_completions(client, tracer_provider)
213
+ # Create a wrapper module that intercepts chat.completions.create
214
+ wrapper = Module.new do
215
+ define_method(:create) do |**params|
216
+ tracer = tracer_provider.tracer("braintrust")
217
+
218
+ tracer.in_span("openai.chat.completions.create") do |span|
219
+ # Initialize metadata hash
220
+ metadata = {
221
+ "provider" => "openai",
222
+ "endpoint" => "/v1/chat/completions"
223
+ }
224
+
225
+ # Capture request metadata fields
226
+ metadata_fields = %i[
227
+ model frequency_penalty logit_bias logprobs max_tokens n
228
+ presence_penalty response_format seed service_tier stop
229
+ stream stream_options temperature top_p top_logprobs
230
+ tools tool_choice parallel_tool_calls user functions function_call
231
+ ]
232
+
233
+ metadata_fields.each do |field|
234
+ metadata[field.to_s] = params[field] if params.key?(field)
235
+ end
236
+
237
+ # Set input messages as JSON
238
+ # Pass through all message fields to preserve tool_calls, tool_call_id, name, etc.
239
+ if params[:messages]
240
+ messages_array = params[:messages].map(&:to_h)
241
+ span.set_attribute("braintrust.input_json", JSON.generate(messages_array))
242
+ end
243
+
244
+ # Call the original method
245
+ response = super(**params)
246
+
247
+ # Set output (choices) as JSON
248
+ # Use to_h to get the raw structure with all fields (including tool_calls)
249
+ if response.respond_to?(:choices) && response.choices&.any?
250
+ choices_array = response.choices.map(&:to_h)
251
+ span.set_attribute("braintrust.output_json", JSON.generate(choices_array))
252
+ end
253
+
254
+ # Set metrics (token usage with advanced details)
255
+ if response.respond_to?(:usage) && response.usage
256
+ metrics = Braintrust::Trace::OpenAI.parse_usage_tokens(response.usage)
257
+ span.set_attribute("braintrust.metrics", JSON.generate(metrics)) unless metrics.empty?
258
+ end
259
+
260
+ # Add response metadata fields
261
+ metadata["id"] = response.id if response.respond_to?(:id) && response.id
262
+ metadata["created"] = response.created if response.respond_to?(:created) && response.created
263
+ metadata["system_fingerprint"] = response.system_fingerprint if response.respond_to?(:system_fingerprint) && response.system_fingerprint
264
+ metadata["service_tier"] = response.service_tier if response.respond_to?(:service_tier) && response.service_tier
265
+
266
+ # Set metadata ONCE at the end with complete hash
267
+ span.set_attribute("braintrust.metadata", JSON.generate(metadata))
268
+
269
+ response
270
+ end
271
+ end
272
+
273
+ # Wrap stream_raw for streaming chat completions
274
+ define_method(:stream_raw) do |**params|
275
+ tracer = tracer_provider.tracer("braintrust")
276
+ aggregated_chunks = []
277
+ metadata = {
278
+ "provider" => "openai",
279
+ "endpoint" => "/v1/chat/completions"
280
+ }
281
+
282
+ # Start span with proper context (will be child of current span if any)
283
+ span = tracer.start_span("openai.chat.completions.create")
284
+
285
+ # Capture request metadata fields
286
+ metadata_fields = %i[
287
+ model frequency_penalty logit_bias logprobs max_tokens n
288
+ presence_penalty response_format seed service_tier stop
289
+ stream stream_options temperature top_p top_logprobs
290
+ tools tool_choice parallel_tool_calls user functions function_call
291
+ ]
292
+
293
+ metadata_fields.each do |field|
294
+ metadata[field.to_s] = params[field] if params.key?(field)
295
+ end
296
+ metadata["stream"] = true # Explicitly mark as streaming
297
+
298
+ # Set input messages as JSON
299
+ if params[:messages]
300
+ messages_array = params[:messages].map(&:to_h)
301
+ span.set_attribute("braintrust.input_json", JSON.generate(messages_array))
302
+ end
303
+
304
+ # Set initial metadata
305
+ span.set_attribute("braintrust.metadata", JSON.generate(metadata))
306
+
307
+ # Call the original stream_raw method with error handling
308
+ begin
309
+ stream = super(**params)
310
+ rescue => e
311
+ # Record exception if stream creation fails
312
+ span.record_exception(e)
313
+ span.status = ::OpenTelemetry::Trace::Status.error("OpenAI API error: #{e.message}")
314
+ span.finish
315
+ raise
316
+ end
317
+
318
+ # Wrap the stream to aggregate chunks
319
+ original_each = stream.method(:each)
320
+ stream.define_singleton_method(:each) do |&block|
321
+ original_each.call do |chunk|
322
+ aggregated_chunks << chunk.to_h
323
+ block&.call(chunk)
324
+ end
325
+ rescue => e
326
+ # Record exception if streaming fails
327
+ span.record_exception(e)
328
+ span.status = ::OpenTelemetry::Trace::Status.error("Streaming error: #{e.message}")
329
+ raise
330
+ ensure
331
+ # Always aggregate whatever chunks we collected and finish span
332
+ # This runs on normal completion, break, or exception
333
+ unless aggregated_chunks.empty?
334
+ aggregated_output = Braintrust::Trace::OpenAI.aggregate_streaming_chunks(aggregated_chunks)
335
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.output_json", aggregated_output[:choices])
336
+
337
+ # Set metrics if usage is included (requires stream_options.include_usage)
338
+ if aggregated_output[:usage]
339
+ metrics = Braintrust::Trace::OpenAI.parse_usage_tokens(aggregated_output[:usage])
340
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.metrics", metrics) unless metrics.empty?
341
+ end
342
+
343
+ # Update metadata with response fields
344
+ metadata["id"] = aggregated_output[:id] if aggregated_output[:id]
345
+ metadata["created"] = aggregated_output[:created] if aggregated_output[:created]
346
+ metadata["model"] = aggregated_output[:model] if aggregated_output[:model]
347
+ metadata["system_fingerprint"] = aggregated_output[:system_fingerprint] if aggregated_output[:system_fingerprint]
348
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.metadata", metadata)
349
+ end
350
+
351
+ span.finish
352
+ end
353
+
354
+ stream
355
+ end
356
+ end
357
+
358
+ # Prepend the wrapper to the completions resource
359
+ client.chat.completions.singleton_class.prepend(wrapper)
360
+ end
361
+
362
+ # Wrap responses API
363
+ # @param client [OpenAI::Client] the OpenAI client
364
+ # @param tracer_provider [OpenTelemetry::SDK::Trace::TracerProvider] the tracer provider
365
+ def self.wrap_responses(client, tracer_provider)
366
+ # Create a wrapper module that intercepts responses.create and responses.stream
367
+ wrapper = Module.new do
368
+ # Wrap non-streaming create method
369
+ define_method(:create) do |**params|
370
+ tracer = tracer_provider.tracer("braintrust")
371
+
372
+ tracer.in_span("openai.responses.create") do |span|
373
+ # Initialize metadata hash
374
+ metadata = {
375
+ "provider" => "openai",
376
+ "endpoint" => "/v1/responses"
377
+ }
378
+
379
+ # Capture request metadata fields
380
+ metadata_fields = %i[
381
+ model instructions modalities tools parallel_tool_calls
382
+ tool_choice temperature max_tokens top_p frequency_penalty
383
+ presence_penalty seed user metadata store response_format
384
+ ]
385
+
386
+ metadata_fields.each do |field|
387
+ metadata[field.to_s] = params[field] if params.key?(field)
388
+ end
389
+
390
+ # Set input as JSON
391
+ if params[:input]
392
+ span.set_attribute("braintrust.input_json", JSON.generate(params[:input]))
393
+ end
394
+
395
+ # Call the original method
396
+ response = super(**params)
397
+
398
+ # Set output as JSON
399
+ if response.respond_to?(:output) && response.output
400
+ span.set_attribute("braintrust.output_json", JSON.generate(response.output))
401
+ end
402
+
403
+ # Set metrics (token usage)
404
+ if response.respond_to?(:usage) && response.usage
405
+ metrics = Braintrust::Trace::OpenAI.parse_usage_tokens(response.usage)
406
+ span.set_attribute("braintrust.metrics", JSON.generate(metrics)) unless metrics.empty?
407
+ end
408
+
409
+ # Add response metadata fields
410
+ metadata["id"] = response.id if response.respond_to?(:id) && response.id
411
+
412
+ # Set metadata ONCE at the end with complete hash
413
+ span.set_attribute("braintrust.metadata", JSON.generate(metadata))
414
+
415
+ response
416
+ end
417
+ end
418
+
419
+ # Wrap streaming method
420
+ define_method(:stream) do |**params|
421
+ tracer = tracer_provider.tracer("braintrust")
422
+ aggregated_events = []
423
+ metadata = {
424
+ "provider" => "openai",
425
+ "endpoint" => "/v1/responses",
426
+ "stream" => true
427
+ }
428
+
429
+ # Start span with proper context
430
+ span = tracer.start_span("openai.responses.create")
431
+
432
+ # Capture request metadata fields
433
+ metadata_fields = %i[
434
+ model instructions modalities tools parallel_tool_calls
435
+ tool_choice temperature max_tokens top_p frequency_penalty
436
+ presence_penalty seed user metadata store response_format
437
+ ]
438
+
439
+ metadata_fields.each do |field|
440
+ metadata[field.to_s] = params[field] if params.key?(field)
441
+ end
442
+
443
+ # Set input as JSON
444
+ if params[:input]
445
+ span.set_attribute("braintrust.input_json", JSON.generate(params[:input]))
446
+ end
447
+
448
+ # Set initial metadata
449
+ span.set_attribute("braintrust.metadata", JSON.generate(metadata))
450
+
451
+ # Call the original stream method with error handling
452
+ begin
453
+ stream = super(**params)
454
+ rescue => e
455
+ # Record exception if stream creation fails
456
+ span.record_exception(e)
457
+ span.status = ::OpenTelemetry::Trace::Status.error("OpenAI API error: #{e.message}")
458
+ span.finish
459
+ raise
460
+ end
461
+
462
+ # Wrap the stream to aggregate events
463
+ original_each = stream.method(:each)
464
+ stream.define_singleton_method(:each) do |&block|
465
+ original_each.call do |event|
466
+ # Store the actual event object (not converted to hash)
467
+ aggregated_events << event
468
+ block&.call(event)
469
+ end
470
+ rescue => e
471
+ # Record exception if streaming fails
472
+ span.record_exception(e)
473
+ span.status = ::OpenTelemetry::Trace::Status.error("Streaming error: #{e.message}")
474
+ raise
475
+ ensure
476
+ # Always aggregate whatever events we collected and finish span
477
+ unless aggregated_events.empty?
478
+ aggregated_output = Braintrust::Trace::OpenAI.aggregate_responses_events(aggregated_events)
479
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.output_json", aggregated_output[:output]) if aggregated_output[:output]
480
+
481
+ # Set metrics if usage is included
482
+ if aggregated_output[:usage]
483
+ metrics = Braintrust::Trace::OpenAI.parse_usage_tokens(aggregated_output[:usage])
484
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.metrics", metrics) unless metrics.empty?
485
+ end
486
+
487
+ # Update metadata with response fields
488
+ metadata["id"] = aggregated_output[:id] if aggregated_output[:id]
489
+ Braintrust::Trace::OpenAI.set_json_attr(span, "braintrust.metadata", metadata)
490
+ end
491
+
492
+ span.finish
493
+ end
494
+
495
+ stream
496
+ end
497
+ end
498
+
499
+ # Prepend the wrapper to the responses resource
500
+ client.responses.singleton_class.prepend(wrapper)
501
+ end
502
+
503
+ # Aggregate responses streaming events into a single response structure
504
+ # Follows similar logic to Python SDK's _postprocess_streaming_results
505
+ # @param events [Array] array of event objects from stream
506
+ # @return [Hash] aggregated response with output, usage, etc.
507
+ def self.aggregate_responses_events(events)
508
+ return {} if events.empty?
509
+
510
+ # Find the response.completed event which has the final response
511
+ completed_event = events.find { |e| e.respond_to?(:type) && e.type == :"response.completed" }
512
+
513
+ if completed_event&.respond_to?(:response)
514
+ response = completed_event.response
515
+ # Convert the response object to a hash-like structure for logging
516
+ return {
517
+ id: response.respond_to?(:id) ? response.id : nil,
518
+ output: response.respond_to?(:output) ? response.output : nil,
519
+ usage: response.respond_to?(:usage) ? response.usage : nil
520
+ }
521
+ end
522
+
523
+ # Fallback if no completed event found
524
+ {}
525
+ end
526
+ end
527
+ end
528
+ end
@@ -51,7 +51,14 @@ module Braintrust
51
51
  private
52
52
 
53
53
  def default_parent
54
- @state.default_parent || "project_name:ruby-sdk-default-project"
54
+ # If default_project is set, format it as "project_name:value"
55
+ # The default_project should be a plain project name (e.g., "my-project")
56
+ # not a formatted parent string (e.g., "project_name:my-project")
57
+ if @state.default_project
58
+ "project_name:#{@state.default_project}"
59
+ else
60
+ "project_name:ruby-sdk-default-project"
61
+ end
55
62
  end
56
63
 
57
64
  # Get parent attribute from parent span in context
@@ -3,9 +3,16 @@
3
3
  require "opentelemetry/sdk"
4
4
  require "opentelemetry/exporter/otlp"
5
5
  require_relative "trace/span_processor"
6
- require_relative "trace/openai"
7
6
  require_relative "logger"
8
7
 
8
+ # OpenAI integration is optional - automatically loaded if openai gem is available
9
+ begin
10
+ require "openai"
11
+ require_relative "trace/contrib/openai"
12
+ rescue LoadError
13
+ # OpenAI gem not installed - integration will not be available
14
+ end
15
+
9
16
  module Braintrust
10
17
  module Trace
11
18
  def self.enable(tracer_provider, state: nil, exporter: nil)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Braintrust
4
- VERSION = "0.0.1.alpha.2"
4
+ VERSION = "0.0.1"
5
5
  end
data/lib/braintrust.rb CHANGED
@@ -38,7 +38,7 @@ module Braintrust
38
38
  # @param tracer_provider [TracerProvider, nil] Optional tracer provider to use instead of creating one
39
39
  # @param api_key [String, nil] Braintrust API key (overrides BRAINTRUST_API_KEY env var)
40
40
  # @param org_name [String, nil] Organization name (overrides BRAINTRUST_ORG_NAME env var)
41
- # @param default_parent [String, nil] Default parent for spans (overrides BRAINTRUST_DEFAULT_PROJECT env var, format: "project_name:my-project" or "project_id:uuid")
41
+ # @param default_project [String, nil] Default project for spans (overrides BRAINTRUST_DEFAULT_PROJECT env var, format: "project_name:my-project" or "project_id:uuid")
42
42
  # @param app_url [String, nil] App URL (overrides BRAINTRUST_APP_URL env var, default: https://www.braintrust.dev)
43
43
  # @param api_url [String, nil] API URL (overrides BRAINTRUST_API_URL env var, default: https://api.braintrust.dev)
44
44
  # @return [State] the created state
@@ -47,7 +47,7 @@ module Braintrust
47
47
  state = State.new(
48
48
  api_key: config.api_key,
49
49
  org_name: config.org_name,
50
- default_parent: config.default_parent,
50
+ default_project: config.default_project,
51
51
  app_url: config.app_url,
52
52
  api_url: config.api_url
53
53
  )
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: braintrust
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1.alpha.2
4
+ version: 0.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Braintrust
@@ -108,19 +108,47 @@ dependencies:
108
108
  - !ruby/object:Gem::Version
109
109
  version: '0.22'
110
110
  - !ruby/object:Gem::Dependency
111
- name: openai
111
+ name: vcr
112
112
  requirement: !ruby/object:Gem::Requirement
113
113
  requirements:
114
114
  - - "~>"
115
115
  - !ruby/object:Gem::Version
116
- version: '0.34'
116
+ version: '6.0'
117
117
  type: :development
118
118
  prerelease: false
119
119
  version_requirements: !ruby/object:Gem::Requirement
120
120
  requirements:
121
121
  - - "~>"
122
122
  - !ruby/object:Gem::Version
123
- version: '0.34'
123
+ version: '6.0'
124
+ - !ruby/object:Gem::Dependency
125
+ name: webmock
126
+ requirement: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - "~>"
129
+ - !ruby/object:Gem::Version
130
+ version: '3.0'
131
+ type: :development
132
+ prerelease: false
133
+ version_requirements: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - "~>"
136
+ - !ruby/object:Gem::Version
137
+ version: '3.0'
138
+ - !ruby/object:Gem::Dependency
139
+ name: appraisal
140
+ requirement: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - "~>"
143
+ - !ruby/object:Gem::Version
144
+ version: '2.5'
145
+ type: :development
146
+ prerelease: false
147
+ version_requirements: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - "~>"
150
+ - !ruby/object:Gem::Version
151
+ version: '2.5'
124
152
  description: OpenTelemetry-based SDK for Braintrust with tracing, OpenAI integration,
125
153
  and evals
126
154
  email:
@@ -129,6 +157,7 @@ executables: []
129
157
  extensions: []
130
158
  extra_rdoc_files: []
131
159
  files:
160
+ - LICENSE
132
161
  - README.md
133
162
  - lib/braintrust.rb
134
163
  - lib/braintrust/api.rb
@@ -146,7 +175,7 @@ files:
146
175
  - lib/braintrust/logger.rb
147
176
  - lib/braintrust/state.rb
148
177
  - lib/braintrust/trace.rb
149
- - lib/braintrust/trace/openai.rb
178
+ - lib/braintrust/trace/contrib/openai.rb
150
179
  - lib/braintrust/trace/span_processor.rb
151
180
  - lib/braintrust/version.rb
152
181
  homepage: https://github.com/braintrustdata/braintrust-sdk-ruby
@@ -1,87 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require "opentelemetry/sdk"
4
- require "json"
5
-
6
- module Braintrust
7
- module Trace
8
- module OpenAI
9
- # Wrap an OpenAI::Client to automatically create spans for chat completions
10
- # @param client [OpenAI::Client] the OpenAI client to wrap
11
- # @param tracer_provider [OpenTelemetry::SDK::Trace::TracerProvider] the tracer provider (defaults to global)
12
- def self.wrap(client, tracer_provider: nil)
13
- tracer_provider ||= ::OpenTelemetry.tracer_provider
14
-
15
- # Create a wrapper module that intercepts chat.completions.create
16
- wrapper = Module.new do
17
- define_method(:create) do |**params|
18
- tracer = tracer_provider.tracer("braintrust")
19
-
20
- tracer.in_span("openai.chat.completions.create") do |span|
21
- # Initialize metadata hash
22
- metadata = {
23
- "provider" => "openai",
24
- "endpoint" => "/v1/chat/completions"
25
- }
26
-
27
- # Capture request metadata fields
28
- metadata_fields = %i[
29
- model frequency_penalty logit_bias logprobs max_tokens n
30
- presence_penalty response_format seed service_tier stop
31
- stream stream_options temperature top_p top_logprobs
32
- tools tool_choice parallel_tool_calls user functions function_call
33
- ]
34
-
35
- metadata_fields.each do |field|
36
- metadata[field.to_s] = params[field] if params.key?(field)
37
- end
38
-
39
- # Set input messages as JSON
40
- if params[:messages]
41
- messages_array = params[:messages].map do |msg|
42
- {role: msg[:role].to_s, content: msg[:content]}
43
- end
44
- span.set_attribute("braintrust.input_json", JSON.generate(messages_array))
45
- end
46
-
47
- # Call the original method
48
- response = super(**params)
49
-
50
- # Set output (choices) as JSON
51
- # Use to_h to get the raw structure with all fields (including tool_calls)
52
- if response.respond_to?(:choices) && response.choices&.any?
53
- choices_array = response.choices.map(&:to_h)
54
- span.set_attribute("braintrust.output_json", JSON.generate(choices_array))
55
- end
56
-
57
- # Set metrics (token usage)
58
- if response.respond_to?(:usage) && response.usage
59
- metrics = {}
60
- metrics["prompt_tokens"] = response.usage.prompt_tokens if response.usage.prompt_tokens
61
- metrics["completion_tokens"] = response.usage.completion_tokens if response.usage.completion_tokens
62
- metrics["tokens"] = response.usage.total_tokens if response.usage.total_tokens
63
- span.set_attribute("braintrust.metrics", JSON.generate(metrics))
64
- end
65
-
66
- # Add response metadata fields
67
- metadata["id"] = response.id if response.respond_to?(:id) && response.id
68
- metadata["created"] = response.created if response.respond_to?(:created) && response.created
69
- metadata["system_fingerprint"] = response.system_fingerprint if response.respond_to?(:system_fingerprint) && response.system_fingerprint
70
- metadata["service_tier"] = response.service_tier if response.respond_to?(:service_tier) && response.service_tier
71
-
72
- # Set metadata ONCE at the end with complete hash
73
- span.set_attribute("braintrust.metadata", JSON.generate(metadata))
74
-
75
- response
76
- end
77
- end
78
- end
79
-
80
- # Prepend the wrapper to the completions resource
81
- client.chat.completions.singleton_class.prepend(wrapper)
82
-
83
- client
84
- end
85
- end
86
- end
87
- end