-
Notifications
You must be signed in to change notification settings - Fork 563
[Go] cross-language test: googleai embedder #423
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
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bcdf8b1
[Go] cross-language test: googleai embedder
jba 4433ff5
reviewer comments
jba d199ec7
use typed xltest
jba 2efb9d3
go mod tidy
jba f9bc518
remove replace from go.mod
jba c77f519
Update test trace to match what JS SDK
ssbushi 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
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
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
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,165 @@ | ||
| // Copyright 2024 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package tests | ||
|
|
||
| import ( | ||
| "cmp" | ||
| "context" | ||
| "flag" | ||
| "fmt" | ||
| "net/http" | ||
| "path/filepath" | ||
| "slices" | ||
| "testing" | ||
|
|
||
| "github.com/firebase/genkit/go/ai" | ||
| "github.com/firebase/genkit/go/core" | ||
| "github.com/firebase/genkit/go/core/tracing" | ||
| "github.com/firebase/genkit/go/internal" | ||
| "github.com/firebase/genkit/go/plugins/googleai" | ||
| gocmp "github.com/google/go-cmp/cmp" | ||
| "github.com/google/go-cmp/cmp/cmpopts" | ||
| "github.com/jba/xltest/go/xltest" | ||
| "google.golang.org/api/option" | ||
| ) | ||
|
|
||
| var update = flag.Bool("update", false, "update golden files with results") | ||
|
|
||
| type embedderResult struct { | ||
| Values []float32 | ||
| TraceFile string `yaml:"traceFile"` | ||
| trace *tracing.Data | ||
| } | ||
|
|
||
| func TestGoogleAI(t *testing.T) { | ||
| ctx := context.Background() | ||
| err := googleai.Init(ctx, googleai.Config{ | ||
| ClientOptions: []option.ClientOption{option.WithHTTPClient(mockClient())}, | ||
| Models: []string{"gemini-1.5-pro"}, | ||
| Embedders: []string{"embedding-001"}, | ||
| }) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
|
|
||
| t.Run("embed", func(t *testing.T) { | ||
| test, err := xltest.ReadFile[string, embedderResult](filepath.Join("testdata", "googleai-embedder.yaml")) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| testfunc := func(text string) (embedderResult, error) { | ||
| ts := &testTraceStore{} | ||
| remove := core.SetDevTraceStore(ts) | ||
| defer remove() | ||
| vals, err := ai.Embed(ctx, googleai.Embedder("embedding-001"), &ai.EmbedRequest{Document: ai.DocumentFromText(text, nil)}) | ||
| if err != nil { | ||
| return embedderResult{}, err | ||
| } | ||
| return embedderResult{Values: vals, trace: ts.td}, nil | ||
| } | ||
| valfunc := validateEmbedder | ||
| if *update { | ||
| valfunc = updateEmbedder | ||
| } | ||
| test.Run(t, testfunc, valfunc, nil) | ||
| }) | ||
| } | ||
|
|
||
| // validateEmbedder compares the results from running an embedder with | ||
| // the desired results. The latter are taken from a YAML file and so are in raw | ||
| // unmarshalled form. | ||
| func validateEmbedder(got, want embedderResult) error { | ||
| if err := internal.ReadJSONFile(filepath.Join("testdata", want.TraceFile), &want.trace); err != nil { | ||
| return err | ||
| } | ||
| if !slices.Equal(got.Values, want.Values) { | ||
| return fmt.Errorf("values: got %v, want %v", got.Values, want.Values) | ||
| } | ||
| renameSpans(got.trace) | ||
| renameSpans(want.trace) | ||
| opts := []gocmp.Option{ | ||
| cmpopts.IgnoreFields(tracing.Data{}, "TraceID", "StartTime", "EndTime"), | ||
| cmpopts.IgnoreFields(tracing.SpanData{}, "TraceID", "StartTime", "EndTime"), | ||
| } | ||
| if diff := gocmp.Diff(want.trace, got.trace, opts...); diff != "" { | ||
| return fmt.Errorf("traces: %s", diff) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // renameSpans changes the keys of td.Spans to s000, s001, ... in order of the span start time, | ||
| // as well as references to those IDs within the spans. | ||
| // This makes it possible to compare two span maps with different span IDs. | ||
| func renameSpans(td *tracing.Data) { | ||
| type item struct { | ||
| id string | ||
| t tracing.Milliseconds | ||
| } | ||
|
|
||
| var items []item | ||
| startTimes := map[tracing.Milliseconds]bool{} | ||
| for id, span := range td.Spans { | ||
| if startTimes[span.StartTime] { | ||
| panic("duplicate start times") | ||
| } | ||
| startTimes[span.StartTime] = true | ||
| items = append(items, item{id, span.StartTime}) | ||
| } | ||
| slices.SortFunc(items, func(i1, i2 item) int { | ||
| return cmp.Compare(i1.t, i2.t) | ||
| }) | ||
| oldIDToNew := map[string]string{} | ||
| for i, item := range items { | ||
| oldIDToNew[item.id] = fmt.Sprintf("s%03d", i) | ||
| } | ||
| // Re-create the span map with the new span IDs. | ||
| m := map[string]*tracing.SpanData{} | ||
| for oldID, span := range td.Spans { | ||
| newID := oldIDToNew[oldID] | ||
| if newID == "" { | ||
| panic(fmt.Sprintf("missing id: %q", oldID)) | ||
| } | ||
| m[newID] = span | ||
| // A span references it own span ID and possibly its parent's. | ||
| span.SpanID = oldIDToNew[span.SpanID] | ||
| if span.ParentSpanID != "" { | ||
| span.ParentSpanID = oldIDToNew[span.ParentSpanID] | ||
| } | ||
| } | ||
| td.Spans = m | ||
| } | ||
|
Comment on lines
+105
to
+142
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @pavelgj This code makes it possible to compare two traces completely, except for times and the trace ID. |
||
|
|
||
| func updateEmbedder(got, want embedderResult) error { | ||
| fmt.Printf("writing %s\n", want.TraceFile) | ||
| return internal.WriteJSONFile(want.TraceFile, got.trace) | ||
| } | ||
|
|
||
| func mockClient() *http.Client { | ||
| mrt := &MockRoundTripper{} | ||
| mrt.Handle("POST /v1beta/models/embedding-001:embedContent", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| fmt.Fprint(w, `{"embedding": {"values": [0.25, 0.25, 0.5]}}`) | ||
| })) | ||
| return &http.Client{Transport: mrt} | ||
| } | ||
|
|
||
| type testTraceStore struct { | ||
| tracing.Store | ||
| td *tracing.Data | ||
| } | ||
|
|
||
| func (ts *testTraceStore) Save(ctx context.Context, id string, td *tracing.Data) error { | ||
| ts.td = td | ||
| return nil | ||
| } | ||
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,48 @@ | ||
| // Copyright 2024 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package tests | ||
|
|
||
| import ( | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| ) | ||
|
|
||
| // MockRoundTripper is a RoundTripper whose responses can be set by the program. | ||
| // It is configured exactly like a ServeMux: by registering http.Handlers with | ||
| // patterns. When a request is received, the matching handler is run and | ||
| // its response is returned. | ||
| // | ||
| // This type is a convenience; the same result can be achieved by registering | ||
| // handlers with an httptest.Server and using its client. This avoids the | ||
| // (local) network round trip. | ||
| type MockRoundTripper struct { | ||
| mux http.ServeMux | ||
| } | ||
|
|
||
| // Handle registers a handle with the MockRoundTripper associated with the given pattern. | ||
| func (rt *MockRoundTripper) Handle(pattern string, handler http.Handler) { | ||
| rt.mux.Handle(pattern, handler) | ||
| } | ||
|
|
||
| func (rt *MockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { | ||
| h, pat := rt.mux.Handler(req) | ||
| if pat == "" { | ||
| return nil, errors.New("no matching handler matches") | ||
| } | ||
| w := httptest.NewRecorder() | ||
| h.ServeHTTP(w, req) | ||
| return w.Result(), nil | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.