-
Notifications
You must be signed in to change notification settings - Fork 0
Instrumentation for Lanchain4j's OpenAI Chat Model #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
examples/src/main/java/dev/braintrust/examples/LangchainExample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package dev.braintrust.examples; | ||
|
|
||
| import dev.braintrust.Braintrust; | ||
| import dev.braintrust.instrumentation.langchain.BraintrustLangchain; | ||
| import dev.langchain4j.data.message.UserMessage; | ||
| import dev.langchain4j.model.chat.ChatModel; | ||
| import dev.langchain4j.model.openai.OpenAiChatModel; | ||
|
|
||
| /** Basic OTel + LangChain4j instrumentation example */ | ||
| public class LangchainExample { | ||
|
|
||
| public static void main(String[] args) throws Exception { | ||
| if (null == System.getenv("OPENAI_API_KEY")) { | ||
| System.err.println( | ||
| "\nWARNING envar OPENAI_API_KEY not found. This example will likely fail.\n"); | ||
| } | ||
| var braintrust = Braintrust.get(); | ||
| var openTelemetry = braintrust.openTelemetryCreate(); | ||
|
|
||
| ChatModel model = | ||
| BraintrustLangchain.wrap( | ||
| openTelemetry, | ||
| OpenAiChatModel.builder() | ||
| .apiKey(System.getenv("OPENAI_API_KEY")) | ||
| .modelName("gpt-4o-mini") | ||
| .temperature(0.0)); | ||
|
|
||
| var rootSpan = | ||
| openTelemetry | ||
| .getTracer("my-instrumentation") | ||
| .spanBuilder("langchain4j-instrumentation-example") | ||
| .startSpan(); | ||
| try (var ignored = rootSpan.makeCurrent()) { | ||
| chatExample(model); | ||
| } finally { | ||
| rootSpan.end(); | ||
| } | ||
| var url = | ||
| braintrust.projectUri() | ||
| + "/logs?r=%s&s=%s" | ||
| .formatted( | ||
| rootSpan.getSpanContext().getTraceId(), | ||
| rootSpan.getSpanContext().getSpanId()); | ||
| System.out.println( | ||
| "\n\n Example complete! View your data in Braintrust: %s\n".formatted(url)); | ||
| } | ||
|
|
||
| private static void chatExample(ChatModel model) { | ||
| var message = UserMessage.from("What is the capital of France?"); | ||
| var response = model.chat(message); | ||
| System.out.println( | ||
| "\n~~~ LANGCHAIN4J CHAT RESPONSE: %s\n".formatted(response.aiMessage().text())); | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
src/main/java/dev/braintrust/instrumentation/langchain/BraintrustLangchain.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package dev.braintrust.instrumentation.langchain; | ||
|
|
||
| import dev.langchain4j.http.client.HttpClientBuilder; | ||
| import dev.langchain4j.http.client.HttpClientBuilderLoader; | ||
| import dev.langchain4j.model.openai.OpenAiChatModel; | ||
| import dev.langchain4j.model.openai.OpenAiStreamingChatModel; | ||
| import io.opentelemetry.api.OpenTelemetry; | ||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| /** Braintrust LangChain4j client instrumentation. */ | ||
| @Slf4j | ||
| public final class BraintrustLangchain { | ||
| /** Instrument langchain openai chat model with braintrust traces */ | ||
| public static OpenAiChatModel wrap( | ||
| OpenTelemetry otel, OpenAiChatModel.OpenAiChatModelBuilder builder) { | ||
| try { | ||
| HttpClientBuilder underlyingHttpClient = getPrivateField(builder, "httpClientBuilder"); | ||
| if (underlyingHttpClient == null) { | ||
| underlyingHttpClient = HttpClientBuilderLoader.loadHttpClientBuilder(); | ||
| } | ||
| HttpClientBuilder wrappedHttpClient = | ||
| wrap(otel, underlyingHttpClient, new Options("openai")); | ||
| return builder.httpClientBuilder(wrappedHttpClient).build(); | ||
| } catch (Exception e) { | ||
| log.warn( | ||
| "Braintrust instrumentation could not be applied to OpenAiChatModel builder", | ||
| e); | ||
| return builder.build(); | ||
| } | ||
| } | ||
|
|
||
| /** Instrument langchain openai chat model with braintrust traces */ | ||
| public static OpenAiStreamingChatModel wrap( | ||
| OpenTelemetry otel, OpenAiStreamingChatModel.OpenAiStreamingChatModelBuilder builder) { | ||
| try { | ||
| HttpClientBuilder underlyingHttpClient = getPrivateField(builder, "httpClientBuilder"); | ||
| if (underlyingHttpClient == null) { | ||
| underlyingHttpClient = HttpClientBuilderLoader.loadHttpClientBuilder(); | ||
| } | ||
| HttpClientBuilder wrappedHttpClient = | ||
| wrap(otel, underlyingHttpClient, new Options("openai")); | ||
| return builder.httpClientBuilder(wrappedHttpClient).build(); | ||
| } catch (Exception e) { | ||
| log.warn( | ||
| "Braintrust instrumentation could not be applied to OpenAiStreamingChatModel" | ||
| + " builder", | ||
| e); | ||
| return builder.build(); | ||
| } | ||
| } | ||
|
|
||
| private static HttpClientBuilder wrap( | ||
| OpenTelemetry otel, HttpClientBuilder builder, Options options) { | ||
| return new WrappedHttpClientBuilder(otel, builder, options); | ||
| } | ||
|
|
||
| public record Options(String providerName) {} | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| private static <T> T getPrivateField(Object obj, String fieldName) | ||
| throws ReflectiveOperationException { | ||
| java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName); | ||
| field.setAccessible(true); | ||
| return (T) field.get(obj); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This question is just for my own education: it looks like we're using reflection to access the private fields in order to instrument them, correct? What are the performance/stability risks associated with reflection? Are there other practical alternatives for instrumentation?
In the Ruby world, we generally would avoid accessing private fields because of the potential for instability (e.g. someone in a patch version changes the API.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes that's right, we're using reflection. There isn't much risk in this case because we'll just fail to apply instrumentation if something goes wrong
Performance is pretty good with reflection, but even if it wasn't this is only done once during client build
There isn't a viable alternative right now, but once we get into auto instrumentation for java we'll have more options