-
Notifications
You must be signed in to change notification settings - Fork 535
feat(contrib/googleapis/go-genai): add Google GenAI Go SDK integration #4951
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
Open
billyac
wants to merge
7
commits into
main
Choose a base branch
from
feat/contrib-googleapis-go-genai
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,560
−6
Open
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7a9f5b0
feat(contrib/googleapis/go-genai): add LLM Observability integration
billyac b6c933b
fix(contrib/googleapis/go-genai): address review and CI
billyac 6260d31
ci: add missing otelgrpc v0.63.0 h1 entry to go.work.sum
billyac 9adb68b
ci: retrigger flaky build-metrics job
billyac fd1c70a
test(ddtrace/tracer): bump integration count 58 -> 59 post-rebase
billyac 0e44ff9
refactor(contrib/google.golang.org/genai): address review comments
billyac bbdae1c
ci(contrib/google.golang.org/genai): retidy for go-libddwaf v4 -> v5
billyac 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| # Google GenAI Integration | ||
|
|
||
| This integration provides Datadog LLM Observability tracing for the | ||
| [google.golang.org/genai](https://github.com/googleapis/go-genai) SDK. | ||
|
|
||
| ## Usage | ||
|
|
||
| ```go | ||
| import ( | ||
| "context" | ||
|
|
||
| genaitrace "github.com/DataDog/dd-trace-go/contrib/googleapis/go-genai/v2" | ||
| "github.com/DataDog/dd-trace-go/v2/ddtrace/tracer" | ||
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| func main() { | ||
| tracer.Start() | ||
| defer tracer.Stop() | ||
|
|
||
| raw, err := genai.NewClient(context.Background(), &genai.ClientConfig{ | ||
| APIKey: "...", | ||
| Backend: genai.BackendGeminiAPI, | ||
| }) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| client := genaitrace.WrapClient(raw) | ||
|
|
||
| resp, err := client.Models.GenerateContent( | ||
| context.Background(), | ||
| "gemini-2.0-flash", | ||
| []*genai.Content{{Role: "user", Parts: []*genai.Part{{Text: "Hello!"}}}}, | ||
| nil, | ||
| ) | ||
| _ = resp | ||
| _ = err | ||
| } | ||
| ``` | ||
|
|
||
| The returned `*Client` exposes the same `Models` and `Chats` services as the | ||
| upstream SDK. For services that are not (yet) instrumented, call `Raw()` to get | ||
| the underlying `*genai.Client`. | ||
|
|
||
| ## Features | ||
|
|
||
| The integration automatically produces LLM Observability spans for: | ||
|
|
||
| - **`Models.GenerateContent`** — LLM span with prompt/response messages, | ||
| generation parameters (temperature, top_p, top_k, max_output_tokens, stop | ||
| sequences) and token usage metrics. | ||
| - **`Models.GenerateContentStream`** — LLM span covering the entire stream; | ||
| output text is reassembled from chunks and final usage metadata is captured. | ||
| - **`Models.EmbedContent`** — Embedding span with input documents and a summary | ||
| of the returned vectors. | ||
| - **`Chats.Create` / `Chat.SendMessage` / `Chat.SendMessageStream`** — LLM | ||
| spans whose input includes the existing chat history plus the new user | ||
| message. | ||
|
|
||
| Spans are tagged with the model provider derived from the underlying client's | ||
| backend (`google` for Gemini API, `google_vertexai` for Vertex AI, | ||
| `google_enterprise` for the Enterprise Agent Platform). |
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,114 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2025 Datadog, Inc. | ||
|
|
||
| package genaitrace | ||
|
|
||
| import ( | ||
| "context" | ||
| "iter" | ||
|
|
||
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| // Chats wraps *genai.Client.Chats with LLM Observability tracing. | ||
| type Chats struct { | ||
| c *genai.Chats | ||
| provider string | ||
| } | ||
|
|
||
| // Create creates a new chat session. The returned *Chat is a tracing wrapper; | ||
| // its SendMessage and SendMessageStream methods produce LLM spans. | ||
| func (c *Chats) Create(ctx context.Context, model string, config *genai.GenerateContentConfig, history []*genai.Content) (*Chat, error) { | ||
| if c == nil || c.c == nil { | ||
| return nil, errNilClient | ||
| } | ||
| chat, err := c.c.Create(ctx, model, config, history) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &Chat{ | ||
| chat: chat, | ||
| model: model, | ||
| provider: c.provider, | ||
| config: config, | ||
| }, nil | ||
| } | ||
|
|
||
| // Chat is a tracing wrapper around *genai.Chat. | ||
| type Chat struct { | ||
| chat *genai.Chat | ||
| model string | ||
| provider string | ||
| config *genai.GenerateContentConfig | ||
| } | ||
|
|
||
| // Raw returns the underlying *genai.Chat. | ||
| func (c *Chat) Raw() *genai.Chat { | ||
| if c == nil { | ||
| return nil | ||
| } | ||
| return c.chat | ||
| } | ||
|
|
||
| // History delegates to the underlying *genai.Chat. | ||
| func (c *Chat) History(curated bool) []*genai.Content { | ||
| return c.chat.History(curated) | ||
| } | ||
|
|
||
| // SendMessage sends a message to the chat and emits an LLM span. The input | ||
| // captured on the span is a pre-call snapshot of the chat history plus the | ||
| // new user message (genai.Chat mutates History during a successful call). | ||
| func (c *Chat) SendMessage(ctx context.Context, parts ...genai.Part) (*genai.GenerateContentResponse, error) { | ||
| if c == nil || c.chat == nil { | ||
| return nil, errNilClient | ||
| } | ||
| input := c.snapshotInput(parts) | ||
| span, ctx := startLLMSpan(ctx, "genai.chat.send_message", c.model, c.provider) | ||
|
|
||
| resp, err := c.chat.SendMessage(ctx, parts...) | ||
| finishLLMSpan(span, input, c.config, resp, err) | ||
| return resp, err | ||
| } | ||
|
|
||
| // SendMessageStream sends a message and streams the response, emitting an | ||
| // LLM span covering the stream. | ||
| func (c *Chat) SendMessageStream(ctx context.Context, parts ...genai.Part) iter.Seq2[*genai.GenerateContentResponse, error] { | ||
| return func(yield func(*genai.GenerateContentResponse, error) bool) { | ||
| if c == nil || c.chat == nil { | ||
| yield(nil, errNilClient) | ||
| return | ||
| } | ||
| input := c.snapshotInput(parts) | ||
| span, ctx := startLLMSpan(ctx, "genai.chat.send_message_stream", c.model, c.provider) | ||
|
|
||
| acc := newStreamAccumulator() | ||
| var lastErr error | ||
| for chunk, err := range c.chat.SendMessageStream(ctx, parts...) { | ||
| if err != nil { | ||
| lastErr = err | ||
| } else { | ||
| acc.add(chunk) | ||
| } | ||
| if !yield(chunk, err) { | ||
| break | ||
| } | ||
| } | ||
| finishLLMSpan(span, input, c.config, acc.response(), lastErr) | ||
| } | ||
| } | ||
|
|
||
| // snapshotInput returns the history at call time plus the new user message, | ||
| // taken before genai.Chat mutates History with the turn being sent. | ||
| func (c *Chat) snapshotInput(parts []genai.Part) []*genai.Content { | ||
| src := c.chat.History(false) | ||
| hist := make([]*genai.Content, len(src)) | ||
| copy(hist, src) | ||
| userParts := make([]*genai.Part, 0, len(parts)) | ||
| for i := range parts { | ||
| p := parts[i] | ||
| userParts = append(userParts, &p) | ||
| } | ||
| return append(hist, &genai.Content{Parts: userParts, Role: string(genai.RoleUser)}) | ||
| } |
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,59 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2025 Datadog, Inc. | ||
|
|
||
| package genaitrace | ||
|
|
||
| import ( | ||
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| // Client is a tracing wrapper around *genai.Client. Calls on its Models and | ||
| // Chats fields produce LLM Observability spans. Use Raw to access the | ||
| // underlying *genai.Client for services that are not (yet) instrumented. | ||
| type Client struct { | ||
| raw *genai.Client | ||
| provider string | ||
|
|
||
| // Models wraps the underlying *genai.Client.Models with tracing. | ||
| Models *Models | ||
| // Chats wraps the underlying *genai.Client.Chats with tracing. | ||
| Chats *Chats | ||
| } | ||
|
|
||
| // WrapClient returns a tracing wrapper around the given *genai.Client. | ||
| // The returned *Client exposes wrapper Models and Chats with the same | ||
| // method signatures as the upstream SDK. | ||
| func WrapClient(c *genai.Client) *Client { | ||
| if c == nil { | ||
| return nil | ||
| } | ||
| provider := backendProvider(c) | ||
| tc := &Client{ | ||
| raw: c, | ||
| provider: provider, | ||
| } | ||
| tc.Models = &Models{m: c.Models, provider: provider} | ||
| tc.Chats = &Chats{c: c.Chats, provider: provider} | ||
| return tc | ||
| } | ||
|
|
||
| // Raw returns the underlying *genai.Client. | ||
| func (c *Client) Raw() *genai.Client { | ||
| if c == nil { | ||
| return nil | ||
| } | ||
| return c.raw | ||
| } | ||
|
|
||
| func backendProvider(c *genai.Client) string { | ||
| switch c.ClientConfig().Backend { | ||
| case genai.BackendVertexAI: | ||
| return "google_vertexai" | ||
| case genai.BackendEnterprise: | ||
| return "google_enterprise" | ||
| default: | ||
| return "google" | ||
| } | ||
| } | ||
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,61 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2025 Datadog, Inc. | ||
|
|
||
| package genaitrace_test | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "google.golang.org/genai" | ||
|
|
||
| genaitrace "github.com/DataDog/dd-trace-go/contrib/googleapis/go-genai/v2" | ||
|
|
||
| "github.com/DataDog/dd-trace-go/v2/ddtrace/tracer" | ||
| ) | ||
|
|
||
| func Example() { | ||
| tracer.Start() | ||
| defer tracer.Stop() | ||
|
|
||
| raw, err := genai.NewClient(context.Background(), &genai.ClientConfig{ | ||
| APIKey: "your-api-key", | ||
| Backend: genai.BackendGeminiAPI, | ||
| }) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| client := genaitrace.WrapClient(raw) | ||
|
|
||
| resp, err := client.Models.GenerateContent( | ||
| context.Background(), | ||
| "gemini-2.0-flash", | ||
| []*genai.Content{{Role: "user", Parts: []*genai.Part{{Text: "Hello!"}}}}, | ||
| nil, | ||
| ) | ||
| _ = resp | ||
| _ = err | ||
| } | ||
|
|
||
| func Example_chat() { | ||
| tracer.Start() | ||
| defer tracer.Stop() | ||
|
|
||
| raw, err := genai.NewClient(context.Background(), &genai.ClientConfig{ | ||
| APIKey: "your-api-key", | ||
| Backend: genai.BackendGeminiAPI, | ||
| }) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| client := genaitrace.WrapClient(raw) | ||
|
|
||
| chat, err := client.Chats.Create(context.Background(), "gemini-2.0-flash", nil, nil) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| resp, err := chat.SendMessage(context.Background(), genai.Part{Text: "Hello!"}) | ||
| _ = resp | ||
| _ = err | ||
| } |
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,22 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2025 Datadog, Inc. | ||
|
|
||
| // Package genaitrace provides Datadog LLM Observability tracing for the | ||
| // Google GenAI Go SDK (google.golang.org/genai). | ||
| // | ||
| // Wrap a *genai.Client with [WrapClient] and use the returned *Client in | ||
| // place of the original; calls on its Models and Chats fields produce | ||
| // LLM Observability spans automatically. | ||
| package genaitrace // import "github.com/DataDog/dd-trace-go/contrib/googleapis/go-genai/v2" | ||
|
|
||
| import ( | ||
| "github.com/DataDog/dd-trace-go/v2/instrumentation" | ||
| ) | ||
|
|
||
| var instr *instrumentation.Instrumentation | ||
|
|
||
| func init() { | ||
| instr = instrumentation.Load(instrumentation.PackageGoogleAPIsGoGenAI) | ||
| } |
Oops, something went wrong.
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.
usually we accept here a variadic
opts ...Optionargument in case we want to provide configuration for the integration. Even if we don't have any option in mind right now, its worth it to add it to avoid introducing breaking changes in the api if we need it in the future.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.
Done in 0e44ff9: added an Option type and WrapClient(c *genai.Client, opts ...Option) — no options exported yet, but the variadic form is in place to avoid a breaking change later.