Skip to content

Commit bfbc167

Browse files
committed
support anthropic client 3
1 parent 4ce1f69 commit bfbc167

21 files changed

Lines changed: 3612 additions & 98 deletions

File tree

‎braintrust-sdk/instrumentation/anthropic_2_2_0/build.gradle‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,17 @@ muzzle {
55
pass {
66
group = 'com.anthropic'
77
module = 'anthropic-java'
8-
// 3.x is a breaking major (e.g. HttpRequest.body() now returns Optional); not yet supported
8+
// Upper-bounded below 3.0.0: 3.x is a breaking major (HttpRequest.body() now returns
9+
// Optional) and the anthropic_3_0_0 module takes over.
910
versions = '[2.2.0,3.0.0)'
1011
}
12+
// Assert the classLoaderMatcher rejects 3.0.0+ so the two anthropic modules never both
13+
// instrument the same client builder.
14+
fail {
15+
group = 'com.anthropic'
16+
module = 'anthropic-java'
17+
pinVersions '3.0.0'
18+
}
1119
}
1220

1321
dependencies {
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,155 @@
11
package dev.braintrust.instrumentation.anthropic;
22

33
import com.anthropic.client.AnthropicClient;
4+
import com.anthropic.client.AnthropicClientAsync;
45
import io.opentelemetry.api.OpenTelemetry;
6+
import io.opentelemetry.api.trace.Tracer;
7+
import java.lang.reflect.Method;
8+
import javax.annotation.Nullable;
9+
import lombok.extern.slf4j.Slf4j;
510

6-
/** Braintrust Anthropic client instrumentation. */
11+
/**
12+
* Braintrust Anthropic client instrumentation.
13+
*
14+
* <p>Dispatches to the module matching the anthropic-java version of each client: {@code
15+
* v3_0_0.BraintrustAnthropic} for 3.0.0 and up, {@code v2_2_0.BraintrustAnthropic} otherwise.
16+
*/
17+
@Slf4j
718
public final class BraintrustAnthropic {
819

20+
/**
21+
* Sentinel class that first appeared in anthropic-java 3.0.0. The {@code
22+
* AnthropicInstrumentationModule.classLoaderMatcher()}s key on the same class, so the manual
23+
* path picks the same module the agent would.
24+
*/
25+
private static final String V3_SENTINEL = "com.anthropic.models.messages.AssistantMessageParam";
26+
27+
private static final String V3_0_0_WRAPPER =
28+
"dev.braintrust.instrumentation.anthropic.v3_0_0.BraintrustAnthropic";
29+
30+
/**
31+
* Whether the anthropic-java that defined a client class is 3.0.0+. Probed on the client's own
32+
* classloader (not this class's), so it is correct per client even when several anthropic-java
33+
* versions are loaded side by side.
34+
*/
35+
private static final ClassValue<Boolean> IS_V3 =
36+
new ClassValue<>() {
37+
@Override
38+
protected Boolean computeValue(Class<?> clientClass) {
39+
try {
40+
Class.forName(V3_SENTINEL, false, clientClass.getClassLoader());
41+
return true;
42+
} catch (ClassNotFoundException | LinkageError e) {
43+
return false;
44+
}
45+
}
46+
};
47+
948
/** Instrument Anthropic client with Braintrust traces. */
1049
public static AnthropicClient wrap(OpenTelemetry openTelemetry, AnthropicClient client) {
50+
if (isV3(client)) {
51+
return forwardToV3(V3.WRAP_OTEL_SYNC, openTelemetry, client);
52+
}
1153
return dev.braintrust.instrumentation.anthropic.v2_2_0.BraintrustAnthropic.wrap(
1254
openTelemetry, client);
1355
}
56+
57+
/** Instrument an async Anthropic client with Braintrust traces. */
58+
public static AnthropicClientAsync wrap(
59+
OpenTelemetry openTelemetry, AnthropicClientAsync client) {
60+
if (isV3(client)) {
61+
return forwardToV3(V3.WRAP_OTEL_ASYNC, openTelemetry, client);
62+
}
63+
return dev.braintrust.instrumentation.anthropic.v2_2_0.BraintrustAnthropic.wrap(
64+
openTelemetry, client);
65+
}
66+
67+
/**
68+
* Instruments a client using the given tracer, replacing any tracer it was previously
69+
* instrumented with.
70+
*/
71+
public static AnthropicClient wrap(Tracer tracer, AnthropicClient client) {
72+
if (isV3(client)) {
73+
return forwardToV3(V3.WRAP_TRACER_SYNC, tracer, client);
74+
}
75+
return dev.braintrust.instrumentation.anthropic.v2_2_0.BraintrustAnthropic.wrap(
76+
tracer, client);
77+
}
78+
79+
/** Async counterpart of {@link #wrap(Tracer, AnthropicClient)}. */
80+
public static AnthropicClientAsync wrap(Tracer tracer, AnthropicClientAsync client) {
81+
if (isV3(client)) {
82+
return forwardToV3(V3.WRAP_TRACER_ASYNC, tracer, client);
83+
}
84+
return dev.braintrust.instrumentation.anthropic.v2_2_0.BraintrustAnthropic.wrap(
85+
tracer, client);
86+
}
87+
88+
private static boolean isV3(Object client) {
89+
return IS_V3.get(client.getClass());
90+
}
91+
92+
@SuppressWarnings("unchecked")
93+
private static <C> C forwardToV3(@Nullable Method wrap, Object tracing, C client) {
94+
if (wrap == null) {
95+
return client; // already logged when V3 was initialized
96+
}
97+
try {
98+
return (C) wrap.invoke(null, tracing, client);
99+
} catch (ReflectiveOperationException | LinkageError e) {
100+
log.error(
101+
"failed to forward to {}.wrap; client will not be instrumented",
102+
V3_0_0_WRAPPER,
103+
e);
104+
return client;
105+
}
106+
}
107+
108+
/**
109+
* {@code v3_0_0.BraintrustAnthropic.wrap} overloads, resolved on first use by a 3.x client.
110+
* Reflection keeps this module from depending on {@code anthropic_3_0_0}, which would put
111+
* anthropic-java 3.x on its compile classpath. A {@code null} method means the v3 module is
112+
* unexpectedly missing; v2_2_0 is binary-incompatible with 3.x, so there is no safe fallback.
113+
*/
114+
private static final class V3 {
115+
private static final Class<?> WRAPPER = loadWrapper();
116+
static final Method WRAP_OTEL_SYNC = method(OpenTelemetry.class, AnthropicClient.class);
117+
static final Method WRAP_OTEL_ASYNC =
118+
method(OpenTelemetry.class, AnthropicClientAsync.class);
119+
static final Method WRAP_TRACER_SYNC = method(Tracer.class, AnthropicClient.class);
120+
static final Method WRAP_TRACER_ASYNC = method(Tracer.class, AnthropicClientAsync.class);
121+
122+
@Nullable
123+
private static Class<?> loadWrapper() {
124+
try {
125+
return Class.forName(
126+
V3_0_0_WRAPPER, true, BraintrustAnthropic.class.getClassLoader());
127+
} catch (ClassNotFoundException | LinkageError e) {
128+
log.error(
129+
"anthropic-java 3.0.0+ detected but {} is unavailable; clients will not be"
130+
+ " instrumented",
131+
V3_0_0_WRAPPER,
132+
e);
133+
return null;
134+
}
135+
}
136+
137+
@Nullable
138+
private static Method method(Class<?> tracingType, Class<?> clientType) {
139+
if (WRAPPER == null) {
140+
return null;
141+
}
142+
try {
143+
return WRAPPER.getMethod("wrap", tracingType, clientType);
144+
} catch (NoSuchMethodException | LinkageError e) {
145+
log.error(
146+
"{}.wrap({}, {}) is unavailable; such clients will not be instrumented",
147+
V3_0_0_WRAPPER,
148+
tracingType.getSimpleName(),
149+
clientType.getSimpleName(),
150+
e);
151+
return null;
152+
}
153+
}
154+
}
14155
}

‎braintrust-sdk/instrumentation/anthropic_2_2_0/src/main/java/dev/braintrust/instrumentation/anthropic/v2_2_0/BraintrustAnthropic.java‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import io.opentelemetry.api.OpenTelemetry;
88
import io.opentelemetry.api.trace.Tracer;
99
import java.lang.reflect.Field;
10+
import java.lang.reflect.Method;
1011
import java.lang.reflect.Modifier;
1112
import java.util.function.Consumer;
1213
import lombok.extern.slf4j.Slf4j;
@@ -111,11 +112,49 @@ private static void instrumentHttpClient(Tracer tracer, Object client, boolean r
111112
}
112113
}
113114

114-
/** Swaps both HTTP client fields on a {@link ClientOptions} for tracing wrappers. */
115+
/**
116+
* Swaps both HTTP client fields on a {@link ClientOptions} for tracing wrappers and turns off
117+
* the SDK's built-in tracing.
118+
*/
115119
private static void instrumentClientOptions(
116120
Tracer tracer, ClientOptions clientOptions, boolean replaceTracer) {
117121
swapHttpClient(tracer, clientOptions, "originalHttpClient", replaceTracer);
118122
swapHttpClient(tracer, clientOptions, "httpClient", replaceTracer);
123+
disableNativeTracing(clientOptions);
124+
}
125+
126+
/**
127+
* anthropic-java 2.72.0+ has built-in OTel tracing, on by default via GlobalOpenTelemetry,
128+
* which would emit a duplicate {@code com.anthropic.sdk.java} span around each of ours. The SDK
129+
* re-reads {@code ClientOptions.openTelemetry().traces().enabled()} on every API call, so
130+
* replacing the field disables it for this client. Reflective because this module compiles
131+
* against 2.2.0, which predates that API; a no-op on older versions. Best-effort: on failure we
132+
* keep our instrumentation and accept the duplicate spans.
133+
*/
134+
private static void disableNativeTracing(ClientOptions clientOptions) {
135+
Method openTelemetryGetter;
136+
try {
137+
openTelemetryGetter = ClientOptions.class.getMethod("openTelemetry");
138+
} catch (NoSuchMethodException e) {
139+
return; // anthropic-java < 2.72.0: no built-in tracing
140+
}
141+
try {
142+
Object otel = openTelemetryGetter.invoke(clientOptions);
143+
Object traces = otel.getClass().getMethod("traces").invoke(otel);
144+
if (!(Boolean) traces.getClass().getMethod("enabled").invoke(traces)) {
145+
return;
146+
}
147+
Object builder = otel.getClass().getMethod("toBuilder").invoke(otel);
148+
builder.getClass().getMethod("traces", boolean.class).invoke(builder, false);
149+
setPrivateField(
150+
clientOptions,
151+
"openTelemetry",
152+
builder.getClass().getMethod("build").invoke(builder));
153+
} catch (ReflectiveOperationException | RuntimeException e) {
154+
log.warn(
155+
"failed to disable anthropic-java built-in tracing; spans may be duplicated",
156+
e);
157+
}
119158
}
120159

121160
private static void swapHttpClient(

0 commit comments

Comments
 (0)