Java AI SDK
Use the Statsig Java AI SDK to serve Agent Experimentation configs, trace OpenAI, Anthropic, and Gemini calls with OpenTelemetry, log eval grades, and run evals from a Java server.
The Statsig Java AI SDK (com.statsig:ai-java) is the Java server SDK for Agent Experimentation. It serves configs, so you can change prompts and models without deploying code. These are Agent Experimentation configs, not Dynamic Configs. It also traces OpenAI, Anthropic, and Gemini calls to Traces as OpenTelemetry spans, logs eval grades that your code computes, and runs evals from code. The SDK builds on the Statsig Java Server SDK.
The SDK uses prompt, the earlier name for a config, in its class and method names. For example, getPrompt() returns a Prompt, which is a config. The console shows the scorers that you pass to Eval, and the graderName that you pass to logEvalGrade(), as evaluators.
This page describes com.statsig:ai-java version 0.0.1-beta.1, the first release. The SDK is in beta, so check the release notes before you upgrade.
Set up the SDK
Install the SDK
The SDK requires Java 8 or later. Add it from Maven Central:
dependencies { implementation 'com.statsig:ai-java:0.0.1-beta.1' }The SDK brings in the Java Server SDK (
com.statsig:javacore) version 0.11.1, OpenTelemetry version 1.53.0, and the OpenAI Java SDK (com.openai:openai-java) version 4.7.1.The SDK doesn't bring in the Anthropic or Google Gen AI SDKs. To trace Anthropic or Gemini calls, add
com.anthropic:anthropic-javaorcom.google.genai:google-genaito your app. Statsig built version0.0.1-beta.1againstanthropic-java2.71.0 andgoogle-genai1.79.0.Initialize the SDK
Initialize the AI SDK with a Server Secret Key. The examples on this page read the key from the
STATSIG_SDK_KEYenvironment variable, which the trace exporter also reads.Keep Server Secret Keys private. If you expose one, disable it and create a new key in the Statsig console.
Choose one of these setups:
The AI SDK creates and owns its own Statsig instance.
StatsigOptionsaccepts any Statsig option.javaimport com.statsig.StatsigOptions; import com.statsig.ai.StatsigAI; import com.statsig.ai.StatsigInitConfig; StatsigOptions options = new StatsigOptions.Builder().setEnvironment("production").build(); StatsigAI statsigAI = StatsigAI.newShared( StatsigInitConfig.coreIndependent(System.getenv("STATSIG_SDK_KEY"), options)) .join();StatsigAI.newShared()creates the instance, initializes it, and registers it as the shared instance. It returns aCompletableFuturethat completes when initialization finishes. Get the shared instance anywhere in your app withStatsigAI.shared().The tracing wrappers and
GenAISpanslog each traced call as astatsig::gen_aievent through the shared instance. When no shared instance exists, they print[StatsigAI] No shared StatsigAI instance. Call StatsigAI.newShared().once and skip the events. Their spans still reach Statsig.newShared()keeps an existing shared instance. A second call prints a warning and returns an instance that makes no network calls. To replace the shared instance, callStatsigAI.removeSharedInstance()first.removeSharedInstance()doesn't shut down the old instance. To create an instance that isn't shared, pass the same configuration tonew StatsigAI(), then callinitialize().
Get a config
A config holds versions of a prompt and its model settings, so you can change them in the Statsig console without deploying code. For details, go to Configs.
Call getPrompt() with a user and the config name. The SDK evaluates the config for that user and returns its Live and Candidate versions.
import com.statsig.StatsigUser;
import com.statsig.ai.Prompt;
import com.statsig.ai.PromptMessage;
import com.statsig.ai.PromptVersion;
import java.util.Collections;
import java.util.List;
StatsigUser user = new StatsigUser.Builder().setUserID("user-123").build();
Prompt prompt = statsigAI.getPrompt(user, "support_bot");
// The Live version, and any Candidate versions
PromptVersion live = prompt.getLive();
PromptVersion[] candidates = prompt.getCandidates();
// Read the version's settings, and render its messages
String model = live.getModel("gpt-6.1-terra");
List<PromptMessage> messages =
live.getPromptMessages(Collections.singletonMap("question", "How do I reset my password?"));
A version (PromptVersion) has these methods:
| Method | Returns |
|---|---|
getName(), getId() | The version name and ID. |
getPromptName() | The config name. |
getModel(), getProvider() | The model and provider strings. |
getTemperature(), getMaxTokens(), getTopP(), getFrequencyPenalty(), getPresencePenalty() | Model parameters. getMaxTokens() returns an int, and the others return a double. |
getValue(key, fallback) | Any other value stored on the version. Returns the fallback when the value is missing or has a different type from the fallback. Numbers match any number type, and lists match arrays. |
getPromptMessages(variables) | The version's messages as PromptMessage objects, with getRole() and getContent(), rendered with the variables that you pass as a Map. |
isLiveForUser() | true for the Live version, and false for a Candidate version. |
The model, provider, and parameter getters accept an optional fallback, which they return when the version doesn't set the value. Without a fallback, the model and provider getters return "" and the parameter getters return 0, so pass a fallback for any parameter you send to your model provider.
getPromptMessages() renders each message as a Mustache template, as the Node AI SDK does:
- Each
{{variable}}becomes the variable's value. Sections, lists, and dotted names, such as{{user.name}}, also work. For a dotted name, pass a nestedMap. - A variable that you don't pass renders as an empty string.
- The SDK doesn't HTML-escape the values. Booleans render as
trueandfalse, and adoublesuch as1.0renders as1.0.
Trace model calls
Tracing sends each model call to Statsig as an OpenTelemetry span. The spans appear in Traces, where online evaluators can grade them.
Initialize tracing
Call Otel.initialize() once, when your app starts:
import com.statsig.ai.trace.Otel;
import com.statsig.ai.trace.options.InitializeTracingOptions;
import com.statsig.ai.trace.options.StatsigOTLPTraceExporterOptions;
Otel.initialize(
InitializeTracingOptions.builder()
.setExporterOptions(new StatsigOTLPTraceExporterOptions(System.getenv("STATSIG_SDK_KEY")))
.setServiceName("support-bot")
.setEnvironment("production")
.build());
In version 0.0.1-beta.1, always call setExporterOptions(). Without exporter options, Otel.initialize() throws NullPointerException. To read the key from the STATSIG_SDK_KEY environment variable, pass new StatsigOTLPTraceExporterOptions(null).
Otel.initialize() throws IllegalArgumentException: Statsig SDK Key is required for StatsigOTLPTraceExporter unless you pass a key in the exporter options or set the STATSIG_SDK_KEY environment variable. Creating a StatsigAI instance doesn't set up tracing. Spans reach Statsig only after you call Otel.initialize().
InitializeTracingOptions.builder() takes these options:
| Option | Description |
|---|---|
setExporterOptions | A StatsigOTLPTraceExporterOptions(sdkKey, dsn). When sdkKey is null, the exporter reads the STATSIG_SDK_KEY environment variable. dsn is a custom endpoint, to which the SDK appends /v1/traces. dsn defaults to https://api.statsig.com/otlp. |
setServiceName | The service.name resource attribute. Defaults to the OTEL_SERVICE_NAME or SERVICE_NAME environment variable. |
setVersion | The service.version resource attribute. |
setEnvironment | The deployment.environment.name and env resource attributes. Go to Set the environment. |
setEnableGlobalTraceProviderRegistration | When true, registers the SDK's OpenTelemetry instance as GlobalOpenTelemetry, so other instrumentation that uses GlobalOpenTelemetry exports to Statsig. Off by default, so the SDK doesn't replace your app's own global OpenTelemetry instance. |
Otel.initialize() returns the OpenTelemetry instance that exports to Statsig. Spans from tracers that you get from this instance also reach Statsig. The SDK batches spans with OpenTelemetry's default BatchSpanProcessor settings.
Wrap your model client
Wrap each model client once, and use the wrapped client everywhere you call the model. The wrappers look up their tracer when each span starts, so you can wrap a client before or after you call Otel.initialize(). Calls made before Otel.initialize() don't send spans to Statsig.
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.google.genai.Client;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.statsig.ai.instrumentation.anthropic.AnthropicWrapper;
import com.statsig.ai.instrumentation.gemini.GeminiModels;
import com.statsig.ai.instrumentation.gemini.GeminiWrapper;
import com.statsig.ai.instrumentation.openai.GenAICaptureOptions;
import com.statsig.ai.instrumentation.openai.OpenAIWrapper;
import com.statsig.ai.instrumentation.openai.OpenAIWrapperConfig;
OpenAIWrapperConfig config =
OpenAIWrapperConfig.builder()
.setCaptureOptions(GenAICaptureOptions.builder().captureAll(true).build())
.build();
OpenAIClient openai = OpenAIWrapper.wrap(OpenAIOkHttpClient.fromEnv(), config);
AnthropicClient anthropic = AnthropicWrapper.wrap(AnthropicOkHttpClient.fromEnv(), config);
GeminiModels gemini = GeminiWrapper.wrap(new Client(), config);
Each wrapper traces these methods, including streaming calls:
| Wrapper | Client | Traced methods |
|---|---|---|
OpenAIWrapper | com.openai:openai-java | chat().completions().create() and createStreaming(), completions().create() and createStreaming(), responses().create() and createStreaming(), embeddings().create(), images().generate() |
AnthropicWrapper | com.anthropic:anthropic-java | messages().create() and createStreaming() |
GeminiWrapper | com.google.genai:google-genai | generateContent() and generateContentStream() on the GeminiModels that wrap() returns, and on its async() models |
OpenAIWrapper.wrap() and AnthropicWrapper.wrap() also take an async client, such as an OpenAIClientAsync. On a wrapped blocking client, async() returns a wrapped async client.
The Gemini Client and its models are final classes, so GeminiWrapper.wrap() can't wrap them in place. GeminiWrapper.wrap() returns a GeminiModels with the same generateContent() and generateContentStream() methods. Call those instead of client.models:
import com.google.genai.types.GenerateContentResponse;
GenerateContentResponse response =
gemini.generateContent(prompt.getLive().getModel(), "How do I reset my password?", null);
For calls that the wrapper doesn't trace, gemini.getModels() returns the client's own models.
A streamed call's span ends when you read the stream to the end or close it. An async call's span ends when its future completes. The wrappers pass every other method through without tracing it.
All three wrappers take an OpenAIWrapperConfig, with these options:
| Option | Description |
|---|---|
setCaptureOptions | A GenAICaptureOptions that sets which message content to record. All options are off by default. |
setCustomAttributes | Attributes to add to every span from this client, such as Collections.singletonMap("team", "support"). They can't override the attributes the SDK sets. |
setMaxJsonChars | The longest JSON value to record per attribute, in characters. Defaults to 40000. The SDK cuts off longer values, ends them with …(truncated), and records the full length as <attribute>_len. |
Record message content
By default, the wrappers record the model, token counts, and timing, but no message content. Turn on GenAICaptureOptions to view messages in the trace drawer. Online evaluators grade only spans that record both input and output messages.
| Option | Records |
|---|---|
captureAll | Everything in this table. |
captureInputMessages | gen_ai.input.messages, plus the variables passed to getPromptMessages(). |
captureOutputMessages | gen_ai.output.messages. |
captureSystemInstructions | gen_ai.system_instructions: system and developer messages, the OpenAI instructions parameter, the Anthropic system parameter, and the Gemini systemInstruction setting. |
captureToolDefinitions | gen_ai.tool.definitions: the tools you pass to the model. |
Turn on each option with its builder method, such as GenAICaptureOptions.builder().captureInputMessages(true).captureOutputMessages(true).build().
The SDK records messages in the OpenTelemetry GenAI format, where each message has a role and a list of parts. For every attribute the spans carry, go to the span attribute reference.
Tag model calls with a config version
Run each model call inside prompt.withLive() or prompt.withVersion(), so its span records which config version produced it. Online evaluators attribute each grade to the version on the span. A span without these attributes isn't linked to a config: it doesn't appear on the config's Traces tab, and its grades don't count toward any version.
The examples on this page turn a version into OpenAI request parameters with this helper:
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.statsig.ai.PromptMessage;
import com.statsig.ai.PromptVersion;
import java.util.Map;
// Renders a config version as OpenAI chat completion parameters
static ChatCompletionCreateParams buildParams(PromptVersion version, Map<String, ?> variables) {
ChatCompletionCreateParams.Builder params =
ChatCompletionCreateParams.builder().model(version.getModel("gpt-6.1-terra"));
for (PromptMessage message : version.getPromptMessages(variables)) {
if ("system".equals(message.getRole())) {
params.addSystemMessage(message.getContent());
} else if ("assistant".equals(message.getRole())) {
params.addAssistantMessage(message.getContent());
} else {
params.addUserMessage(message.getContent());
}
}
return params.build();
}
Call the helper inside withLive() or withVersion(), so the span records the variables that it renders:
import com.openai.models.chat.completions.ChatCompletion;
import com.statsig.ai.Prompt;
import com.statsig.ai.PromptVersion;
import java.util.Collections;
import java.util.Map;
Prompt prompt = statsigAI.getPrompt(user, "support_bot");
Map<String, String> variables = Collections.singletonMap("question", question);
// Serve the Live version
ChatCompletion completion =
prompt.withLive(
() -> openai.chat().completions().create(buildParams(prompt.getLive(), variables)));
// Serve a Candidate version
PromptVersion[] candidates = prompt.getCandidates();
if (candidates.length > 0) {
PromptVersion candidate = candidates[0];
ChatCompletion candidateCompletion =
prompt.withVersion(
candidate,
() -> openai.chat().completions().create(buildParams(candidate, variables)));
}
withLive() and withVersion() run the Supplier or Runnable that you pass, and return the Supplier's result. Wrapped model calls and GenAISpans spans inside them get these attributes:
| Attribute | Value |
|---|---|
statsig.llm.prompt_name | The config name. |
statsig.llm.prompt_version | The version name. |
statsig.llm.prompt_version_id | The version ID. |
statsig.llm.prompt_template_variables | The variables passed to getPromptMessages(), as JSON. Call getPromptMessages() inside withLive() or withVersion(). Model call spans record the variables only when you capture input messages. Workflow spans always record them. |
The spans also record the user you passed to getPrompt(). An inner withVersion() replaces an outer one. To tag spans with the config name and user, but no version, use prompt.withContext(). It keeps any version that an outer call set.
Trace workflows and tools
GenAISpans traces your own code, such as an agent turn or a tool call, as spans in the same trace as the model calls it makes:
wrap(options, fn)takes aSupplier,Function, orRunnable, and returns the same type. Each call of the returned function runs in its own span.wrapCallable()takes aCallable, and rethrows its checked exceptions unchanged.startWorkflow(name, body)runsbodyimmediately in a workflow span, and returns its result. It also takes aWrapOptionsinstead of a name.startWorkflowCallable()does the same for aCallable.
Build the options with WrapOptions.workflow(name) or WrapOptions.tool(name). GenAISpans looks up its tracer when each span starts, so you can wrap functions before you call Otel.initialize().
import static com.statsig.ai.trace.GenAISpans.startWorkflow;
import static com.statsig.ai.trace.GenAISpans.wrap;
import com.openai.models.chat.completions.ChatCompletion;
import com.statsig.ai.PromptVersion;
import com.statsig.ai.trace.options.WrapOptions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
// A tool span each time the function runs
static final Function<String, List<String>> searchDocs =
wrap(
WrapOptions.tool("search_docs").setToolType("retrieval").build(),
query -> docsIndex.search(query));
// A workflow span for each agent turn
static String handleTurn(PromptVersion version, String question) {
return startWorkflow(
"support_turn",
() -> {
List<String> docs = searchDocs.apply(question);
Map<String, String> variables = new HashMap<>();
variables.put("question", question);
variables.put("docs", String.join("\n", docs));
ChatCompletion completion =
openai.chat().completions().create(buildParams(version, variables));
return completion.choices().get(0).message().content().orElse("");
});
}
// Run the turn inside withLive, so its spans record the config version
String answer = prompt.withLive(() -> handleTurn(prompt.getLive(), question));
| Option | Description |
|---|---|
WrapOptions.workflow(name), WrapOptions.tool(name) | A workflow span, for a unit of work such as an agent turn, or a tool span, for a tool call. The SDK records the name as statsig.gen_ai.workflow.name or statsig.gen_ai.tool.name. |
setToolType | Tool spans only. Recorded as gen_ai.tool.type. |
setAttribute, setAttributes | Extra span attributes. |
setUser, setActivityID | Tag this span and the spans inside it, like withStatsigContext(). |
The SDK names workflow spans invoke_workflow and tool spans execute_tool. If the code throws, the span records the exception and an ERROR status, and the exception propagates. When the code returns a CompletableFuture, the span ends when the future completes, and you receive a future that completes after the span ends.
Online evaluators grade a workflow span as the turn's answer, and never grade tool spans. The SDK doesn't mark the model calls inside a workflow span with statsig.span.llm_root, so online evaluators don't grade them on their own.
The SDK doesn't record messages on workflow spans, and online evaluators skip a workflow span without them. To grade a workflow span, set its input and output messages on the span before it ends. Inside the workflow, Span.current() returns the workflow span. This example builds the JSON with Jackson, which the OpenAI Java SDK brings in:
import static com.statsig.ai.trace.GenAISpans.startWorkflow;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.statsig.ai.trace.options.WrapOptions;
import io.opentelemetry.api.trace.Span;
String answer =
prompt.withLive(
() ->
startWorkflow(
WrapOptions.workflow("support_turn").setUser(user).build(),
() -> {
String reply = runAgent(prompt.getLive(), question);
// Set the turn's question and final answer for online evaluators to read
ArrayNode input = JsonNodeFactory.instance.arrayNode();
input.addObject().put("role", "user").put("content", question);
ArrayNode output = JsonNodeFactory.instance.arrayNode();
output.addObject().put("role", "assistant").put("content", reply);
Span.current().setAttribute("gen_ai.input.messages", input.toString());
Span.current().setAttribute("gen_ai.output.messages", output.toString());
return reply;
}));
For details, go to Grade a multi-step agent turn.
Add users and activity IDs to spans
Static methods on com.statsig.ai.trace.StatsigContextUtils add a user, and optionally an activity ID, to the spans that start inside the code you pass:
withStatsigUserContext(user, body): Records the user's ID asstatsig.user_idand the user's custom IDs asstatsig.custom_ids, on every span that starts insidebody.withStatsigContext(user, activityID, body): Records the user, and adds the activity ID to the custom IDs asstatsig.activity_id, on wrapped model calls andGenAISpansspans insidebody. Pass anulluser when you have only an activity ID.
Each method runs a Supplier and returns its result, or runs a Runnable. Overloads that take an OpenTelemetry Context return a new context instead, for code that manages its own scopes.
Use an activity ID to group the spans of a multi-turn conversation or a long-running job. The Traces page groups spans with the same activity ID in the trace drawer, even across traces.
import static com.statsig.ai.trace.StatsigContextUtils.withStatsigContext;
String answer =
withStatsigContext(
user, conversationID, () -> prompt.withLive(() -> handleTurn(prompt.getLive(), question)));
Set the environment
Statsig reads each span's environment to filter the Traces page and to choose which spans online evaluators grade. Set the environment for all spans with setEnvironment() in InitializeTracingOptions, as Initialize tracing shows. The SDK records it as the deployment.environment.name and env resource attributes. The environment option has no default.
To tag only some spans, run the code that creates them inside withStatsigEnvironment(). Spans that start inside it get a statsig.environment attribute, which overrides the resource value for those spans.
import static com.statsig.ai.trace.StatsigContextUtils.withStatsigEnvironment;
// Tag canary traffic that runs in the production process
withStatsigEnvironment("staging_canary", () -> handleRequest(request));
Use production for live traffic. Statsig reserves eval, online_eval_judge, and shadow for spans it generates, and online evaluators never grade them. Eval runs its tasks and scorers with statsig.environment set to eval. Don't use the reserved values for your own spans, except eval for the requests that a workflow run sends. For details, go to Join a workflow run's trace. For how Statsig reads environments, go to Environments.
Join a workflow run's trace
In an offline run of a config version with a custom workflow, Statsig sends each dataset row to your endpoint as a POST request. Each request carries these headers:
traceparent: The W3C trace context of the row's trace on the Traces page.x-statsig-eval-run: The ID of the run.
Run your handler inside withIncomingTraceContext(), so the wrapped model calls and GenAISpans spans it starts join the row's trace. The trace drawer then shows them under the row's root span.
import static com.statsig.ai.trace.StatsigContextUtils.withIncomingTraceContext;
// Spring
@PostMapping("/agent")
public Map<String, String> agent(
@RequestHeader HttpHeaders headers, @RequestBody Map<String, String> body) {
return withIncomingTraceContext(
headers::getFirst, () -> Collections.singletonMap("output", runAgent(body.get("input"))));
}
// Servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String input = request.getReader().lines().collect(Collectors.joining("\n"));
String output = withIncomingTraceContext(request::getHeader, () -> runAgent(input));
response.getWriter().write(output);
}
withIncomingTraceContext() reads the traceparent and tracestate headers. Pass a Map<String, String> of headers, or a function that returns a header's value, such as Spring's headers::getFirst or a servlet request's request::getHeader. It matches header names in a Map without regard to case. It runs your code with the caller's span as the parent. Without a valid traceparent, your code runs in the current context, so you can wrap every request. If OpenTelemetry HTTP instrumentation, such as the OpenTelemetry Java agent, already started a span in the incoming trace, withIncomingTraceContext() keeps that span as the parent.
Spans from your endpoint use your app's environment, such as production. Online evaluators skip the spans that join a dataset row's trace in the config's project, so a run doesn't grade them a second time. The Traces page still lists them with your production traces. To mark requests from a run as eval traffic everywhere, including spans that don't join the row's trace, run them inside withStatsigEnvironment("eval", ...):
import static com.statsig.ai.trace.StatsigContextUtils.withIncomingTraceContext;
import static com.statsig.ai.trace.StatsigContextUtils.withStatsigEnvironment;
@PostMapping("/agent")
public Map<String, String> agent(
@RequestHeader HttpHeaders headers, @RequestBody Map<String, String> body) {
boolean isEvalRun = headers.getFirst("x-statsig-eval-run") != null;
return withIncomingTraceContext(
headers::getFirst,
() -> isEvalRun ? withStatsigEnvironment("eval", () -> handle(body)) : handle(body));
}
Only check x-statsig-eval-run on requests that your endpoint authenticates, such as with the auth header that you set on the workflow. Otherwise any caller can add the header to keep their requests out of online evaluation. Without the Java AI SDK, set the span attribute statsig.environment to eval on the spans that your handler starts.
Statsig sends these headers only during a run, not when you click Test Connection. A header that you set on the workflow with the same name replaces Statsig's.
Log eval grades
Use logEvalGrade() to send a grade that your own code computes, such as user feedback or a check in your app, to Statsig. Statsig shows these grades with the source SDK.
import com.statsig.ai.AIEvalGradeData;
import com.statsig.ai.PromptVersion;
PromptVersion version = statsigAI.getPrompt(user, "support_bot").getLive();
AIEvalGradeData gradeData = new AIEvalGradeData(conversationID);
gradeData.setReasoning("The user rated the reply as helpful.");
statsigAI.logEvalGrade(user, version, 1.0, "user_feedback", gradeData);
logEvalGrade(user, version, score, graderName, gradeData) takes the config version that produced the output, and a score from 0 to 1. The SDK drops a score outside that range and prints [StatsigAI] Invalid score provided; skipping eval grade logging. Pass null as gradeData when you have no options to set.
AIEvalGradeData takes these options. Pass the session ID to the constructor, or set each option with its setter:
| Option | Description |
|---|---|
setSessionID | Groups grades from the same session. |
setActivityID | Sets statsig.activity_id on the user's custom IDs. |
setTraceID, setSpanID | The span the grade belongs to, as lowercase hex strings. When you set neither, the SDK uses the active span, so a grade logged inside a workflow belongs to that workflow span. To grade a span after it ends, such as from feedback that arrives later, save its IDs while it's active, then set both. Span.current().getSpanContext().getTraceId() and getSpanId() return them in this format. |
setReasoning | Why the evaluator gave this score. |
setMetadata | Extra string fields to log with the grade, as a Map<String, String>. |
The SDK logs each grade as a statsig::eval_result event. For how grades appear in Statsig, go to Online Evaluation.
Flush events and spans
The SDK sends events and spans in batches. Before a short-lived process exits, such as a batch job or a serverless function, flush them:
statsigAI.flushEvents().join();
flushEvents() returns a CompletableFuture that completes when the flush finishes. It always flushes spans. It flushes Statsig events, including eval grades, only when the AI SDK created the Statsig instance. If you passed in your own instance, flush that instance too:
statsig.flushEvents().join();
To flush and stop the SDK when your server shuts down, call statsigAI.shutdown().join(). It shuts down the Statsig instance if the AI SDK created it, flushes spans, and leaves the tracer provider running.
Run an eval from code
Eval runs a task over records you define in code, scores each output, and sends the results to a run group in Statsig. Before you run an eval:
- Set the
STATSIG_API_KEYenvironment variable to a Console API key, or pass the key toapiKey(). Without a key,build()throwsIllegalStateException. - Create a run group with the Console API's Create Eval, or create a run under Agent Experimentation > Runs and type a new run group name. Pass the run group's name as the first argument to
Eval.builder(). If no run group has that name, Statsig rejects the results, and the SDK logs[StatsigAI] Failed to send eval results: 404 Not Found.
import com.statsig.ai.evals.Eval;
import com.statsig.ai.evals.EvalDataRecord;
import com.statsig.ai.evals.EvalResult;
import java.util.Arrays;
import java.util.List;
List<EvalDataRecord<String, String>> data =
Arrays.asList(
EvalDataRecord.of("world", "Hello world"), EvalDataRecord.of("test", "Hello test"));
EvalResult<String, String, String> result =
Eval.builder("greeting_eval", data)
.task((input, hooks) -> "Hello " + input)
.scorer(args -> args.getOutput().equals(args.getExpected()))
.evalRunName("run-123") // optional
.build()
.run();
run() blocks until the run finishes. To get the result as a CompletableFuture instead, call runAsync().
Create each record with EvalDataRecord.of(), from an input, an optional expected output, and an optional category or list of categories. Eval.builder(name, data) takes the run group name and the records, and returns a builder with these methods:
| Method | Description |
|---|---|
task | A function that returns the output for an input. It receives the input and an EvalHooks, with getParameter(), getParameters(), getCategories(), and reportTokens(). |
asyncTask | Use instead of task for a function that returns a CompletableFuture of the output. |
scorer, scorers | A scorer function, or a Map of named scorer functions. scorer(fn) names the scorer Grader, and scorer(name, fn) uses the name that you pass. A scorer receives an EvalScorerArgs, with getInput(), getOutput(), getExpected(), getCategories(), and getRowID(). It returns a Number, a Boolean, a ScoreWithMetadata, or a CompletionStage of one of these. true counts as 1 and false as 0. |
parameter, parameters | Values that the task reads with hooks.getParameter(name). |
evalRunName | A name for this run. |
dataset | The name or ID of the Statsig dataset that the records come from. Each record then needs the row ID of a different row of the dataset. StatsigDataset sets this for you. |
summaryScores | A function that receives every result and returns summary scores, as a Map of numbers. |
executor | The Executor that runs tasks and scorers. By default, each run uses its own pool of up to 32 threads. |
apiKey | The Console API key. Defaults to the STATSIG_API_KEY environment variable. |
run() returns an EvalResult with getResults(), getSummaryScores(), and isError(). Each result (EvalResultRecord) has the record's input, expected value, categories, and row ID, plus the output, a getScores() map, an isError() flag, and the record's latency and tokens. With tracing on, each result also has the record's trace ID and span ID. Results keep the order of the data. Records run at the same time, and so do each record's scorers.
Statsig stores each result's input, output, expected value, and score metadata as strings. Eval sends other values as JSON. The results that run() returns keep the original values.
Errors don't stop the run:
- When a task throws, the SDK logs a warning, scores every scorer 0 for that record, and the record's
isError()returnstrue. Statsig gets"[Error]"as the record's output, and the result'sgetOutput()returnsnull.EvalResult.isError()istruewhen any record has an error. - When a scorer throws or returns another type, the SDK logs a warning and scores that scorer 0 for that record.
- When the SDK can't send the results,
run()logs a warning and still returns them.
The following example uses named scorers, a parameter, categories, and a summary score:
import com.statsig.ai.evals.Eval;
import com.statsig.ai.evals.EvalDataRecord;
import com.statsig.ai.evals.EvalResult;
import com.statsig.ai.evals.ScoreWithMetadata;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
List<EvalDataRecord<String, String>> data =
Arrays.asList(
EvalDataRecord.of("world", "Hi world", "greeting"),
EvalDataRecord.of("test", "Hi test", Arrays.asList("greeting", "test")));
EvalResult<String, String, String> result =
Eval.builder("greeting_eval", data)
.task(
(input, hooks) -> {
String greeting = hooks.getParameter("greeting");
return greeting + " " + input;
})
.parameter("greeting", "Hi")
.scorer("correctness", args -> args.getOutput().equals(args.getExpected()))
.scorer(
"starts_with_greeting",
args ->
ScoreWithMetadata.of(
args.getOutput().startsWith("Hi"),
Collections.singletonMap("length", args.getOutput().length())))
.summaryScores(
results -> {
long correct =
results.stream().filter(r -> r.getScores().get("correctness") == 1).count();
return Collections.singletonMap("accuracy", (double) correct / results.size());
})
.build()
.run();
Record latency and tokens
Eval times each record's task, from the call until the task returns its output, and sends the time with the record's result as latencyMs. For asyncTask, the time ends when the task's CompletableFuture completes. The time is in whole milliseconds and doesn't include scorers.
Eval can't see the model calls that a task makes, so the task reports its own tokens. Call hooks.reportTokens(inputTokens, outputTokens) on the EvalHooks that the task receives. Each call adds to the record's totals, so a task that makes several model calls can report each call, or report the total once. You can call reportTokens() from any thread.
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.statsig.ai.evals.Eval;
Eval.builder("support_bot_quality", data)
.task(
(input, hooks) -> {
ChatCompletion completion =
openai
.chat()
.completions()
.create(
ChatCompletionCreateParams.builder()
.model("gpt-6.1-terra")
.addUserMessage(input)
.build());
completion
.usage()
.ifPresent(
usage -> hooks.reportTokens(usage.promptTokens(), usage.completionTokens()));
return completion.choices().get(0).message().content().orElse("");
})
.scorer(args -> args.getOutput().equals(args.getExpected()))
.build()
.run();
Statsig stores each record's latency and tokens with the run and doesn't grade them. They appear in the run's CSV export and in the Console API. Each result that run() returns also has getLatencyMs(), getInputTokens(), and getOutputTokens().
- A record whose task throws sends no latency or tokens.
- A record whose task never calls
reportTokens()sends no tokens. - Calls to
reportTokens()after the task returns its output don't count. reportTokens()ignores a call with a negative count, and logs a warning.
Run an eval on a Statsig dataset
To run on a dataset from the Statsig console, pass StatsigDataset.of(name, toRecord) to Eval.builder() instead of a list of records. The eval loads every row of the dataset with its Console API key, and toRecord turns each row into a record. The run records the dataset, so a run's Compare view can compare it row by row with other runs on that dataset.
import com.statsig.ai.evals.Eval;
import com.statsig.ai.evals.EvalDataRecord;
import com.statsig.ai.evals.StatsigDataset;
Eval.builder(
"support_bot_quality",
StatsigDataset.of(
"support_cases",
row ->
EvalDataRecord.of(
row.getColumns().get("question"),
row.getColumns().get("answer"),
row.getGroups())))
.task((input, hooks) -> answer(input))
.scorer(args -> args.getOutput().equals(args.getExpected()))
.build()
.run();
StatsigDataset.of() takes the dataset's name or ID. toRecord receives each row as a StatsigDatasetRow, with getRowID(), getColumns(), and getGroups():
getColumns()maps each column name to the row's value, as a string.getGroups()lists the row's categories.
Each record gets its row's ID. When the dataset can't load, run() throws before any task runs: IllegalStateException with the HTTP status, or UncheckedIOException for a network error. runAsync() completes exceptionally instead.
To run on records that you build yourself from a dataset, call dataset(name) on the builder, and give each record the ID of its row with withRowID(). run() throws IllegalArgumentException before any task runs when a record has no row ID or repeats one. Statsig rejects the results when a row ID isn't a row of the dataset.
Traces for eval records
When you call Otel.initialize() before you run an eval, each record runs in its own trace, even when you run the eval inside another span. The root of the trace is a workflow span with the run group name as its name, and these attributes:
| Attribute | Value |
|---|---|
statsig.eval.name | The run group name. |
statsig.eval.run_name | The evalRunName, when you set one. |
statsig.eval.record_index | The record's position in the data, counting from 0. |
Wrapped model calls and GenAISpans spans in the task become children of the root span. Each scorer runs in its own child workflow span, named after the scorer and tagged with statsig.eval.scorer_name. Every span in the trace has statsig.environment set to eval, so online evaluators don't grade them. The Traces page lists these spans. To hide them, use the Environment filter or search for #environment!:eval.
Eval sends each record's trace ID and span ID with its scores, so the scores also appear on the root span in Traces. Each result returns them from getTraceID() and getSpanID(). Eval flushes the spans before it sends the results, and waits up to 30 seconds. When the flush fails or times out, Eval logs a warning and sends the results anyway. Without Otel.initialize(), Eval doesn't create traces, but its tasks and scorers still run with statsig.environment set to eval.
An async task that hands work to its own threads must pass the OpenTelemetry context along, so the work joins the record's trace. For example, wrap the task's executor with Context.current().wrap():
import com.statsig.ai.evals.Eval;
import io.opentelemetry.context.Context;
import java.util.concurrent.CompletableFuture;
Eval.builder("support_bot_quality", data)
.asyncTask(
(input, hooks) ->
CompletableFuture.supplyAsync(
() -> askModel(input), Context.current().wrap(modelExecutor)))
.scorer(args -> args.getOutput().equals(args.getExpected()))
.build()
.run();
Use other Statsig SDK methods
getStatsig() returns the underlying Statsig instance, however you initialized the AI SDK. Use it for any Java Server SDK method:
import com.statsig.Statsig;
Statsig statsig = statsigAI.getStatsig();
// Check a gate
boolean enabled = statsig.checkGate(user, "my_gate");
// Log an event
statsig.logEvent(user, "my_event");
Was this helpful?
For AI agents: a documentation index is available at /llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.