') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - braintrustdata/braintrust-sdk-java · GitHub
Skip to content

Repository files navigation

Braintrust

Braintrust Java Tracing & Eval SDK

javadocCI

Overview

This library provides tools for evaluating and tracing AI applications in Braintrust. Use it to:

  • Evaluate your AI models with custom test cases and scoring functions
  • Trace LLM calls and monitor AI application performance with OpenTelemetry
  • Integrate seamlessly with OpenAI, Anthropic, and other LLM providers

This SDK is currently in BETA status and APIs may change.

Quickstart

The fastest way to report data to Braintrust is to add the braintrust java agent to your jvm startup args.

springboot+gradle example:

configurations {
btAgent
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
btAgent "dev.braintrust:braintrust-java-agent:<version-goes-here>"
}
bootRun {
jvmArgs = [
// NOTE: if you're running with other java agents, add the braintrust agent last"-javaagent:${configurations.btAgent.singleFile.absolutePath}",
]
}

This will automatically instrument major AI clients and frameworks. No code changes required. A list of supported instrumentation can be found here

NOTE: Additional steps may be required for users running with other -javaagent flags. Consult braintrust docs for details.

Eval Quickstart

Add the Braintrust SDK to your package manager.

gradle example:

dependencies {
implementation 'dev.braintrust:braintrust-sdk-java:<version-goes-here>'
}

Use the SDK to create and send your eval:

varbraintrust = Braintrust.get();
braintrust.openTelemetryCreate();
varopenAIClient = OpenAIOkHttpClient.fromEnv();
Function<String, String> getFoodType =
(Stringfood) -> {
varrequest =
ChatCompletionCreateParams.builder()
.model(ChatModel.GPT_4O_MINI)
.addSystemMessage("Return a one word answer")
.addUserMessage("What kind of food is " + food + "?")
.build();
varresponse = openAIClient.chat().completions().create(request);
returnresponse.choices().get(0).message().content().orElse("").toLowerCase();
};
vareval = braintrust.<String, String>evalBuilder()
.name("java-eval-x-" + System.currentTimeMillis())
.cases(
DatasetCase.of("asparagus", "vegetable"),
DatasetCase.of("banana", "fruit"))
.taskFunction(getFoodType)
.scorers(
Scorer.of(
"exact_match",
(expected, result) -> expected.equals(result) ? 1.0 : 0.0))
.build();
varresult = eval.run();
System.out.println("\n\n" + result.createReportString());

Manual Instrumentation

Alternatively, sdk users can manually apply instrumentation instead of using the java agent.

varbraintrust = Braintrust.get();
varopenTelemetry = braintrust.openTelemetryCreate();
OpenAIClientopenAIClient = BraintrustOpenAI.wrapOpenAI(openTelemetry, OpenAIOkHttpClient.fromEnv());
varrequest =
ChatCompletionCreateParams.builder()
.model(ChatModel.GPT_4O_MINI)
.addUserMessage("What is the capital of France?")
.build();
// openai calls will be traced and reported to braintrustvarresponse = openAIClient.chat().completions().create(request);

A list of supported instrumentation can be found here

Running Examples

Example source code can be found here. Each example is its own Gradle subproject under examples/ with its own :run target.

export BRAINTRUST_API_KEY="your-braintrust-api-key"export OPENAI_API_KEY="your-oai-api-key"# to run oai examplesexport ANTHROPIC_API_KEY="your-anthropic-api-key"# to run anthropic examples# install java 17 or later
brew install openjdk@17 # macOS
sudo apt install openjdk-17-jdk # ubuntu# to run a specific example
./gradlew :examples:simple-open-telemetry:run
# to list every example subproject
./gradlew projects

Logging

The SDK uses a standard slf4j logger and will use the default log level (or not log at all if slf4j is not installed).

All Braintrust loggers will log into the dev.braintrust namespace. To adjust the log level, consult your logger documentation.

For example, to enable debug logging for slf4j-simple you would set the system property org.slf4j.simpleLogger.log.dev.braintrust=DEBUG

See Also

About

No description, website, or topics provided.

Resources

Contributing

Stars

21 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages