Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/architecture/crds-and-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ ModelConfigSpec
- Provider-specific config (e.g. `openAI`) must only be set when provider matches
- `apiKeyPassthrough` and `apiKeySecret` are mutually exclusive
- `apiKeyPassthrough` not allowed for Gemini/VertexAI providers
- `apiKeyPassthrough` on a ModelConfig referenced via `memory.modelConfig` is only honored for openai, azure_openai, and foundry (other embedding providers ignore it)
- TLS `caCertSecretRef` and `caCertSecretKey` must be set together

---
Expand Down
48 changes: 40 additions & 8 deletions go/adk/pkg/embedding/embedding.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
"github.com/go-logr/logr"
"github.com/kagent-dev/kagent/go/adk/pkg/internal/azureai"
"github.com/kagent-dev/kagent/go/adk/pkg/models"
"github.com/kagent-dev/kagent/go/api/adk"
"github.com/ollama/ollama/api"
"github.com/openai/openai-go/v3"
Expand Down Expand Up @@ -110,14 +111,14 @@ func newOpenAIProvider(cfg *adk.EmbeddingConfig) (*openAIProvider, error) {
}, nil
}

func generateEmbeddings(ctx context.Context, client openai.Client, model, provider string, texts []string) ([][]float32, error) {
func generateEmbeddings(ctx context.Context, client openai.Client, cfg *adk.EmbeddingConfig, provider string, isAzureFamily bool, texts []string) ([][]float32, error) {
log := logr.FromContextOrDiscard(ctx)

resp, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{
Model: openai.EmbeddingModel(model),
Model: openai.EmbeddingModel(cfg.Model),
Input: openai.EmbeddingNewParamsInputUnion{OfArrayOfStrings: texts},
Dimensions: openai.Int(int64(TargetDimension)),
})
}, embeddingPassthroughOpts(ctx, cfg, isAzureFamily)...)
if err != nil {
return nil, fmt.Errorf("%s embeddings request failed: %w", provider, err)
}
Expand All @@ -129,8 +130,25 @@ func generateEmbeddings(ctx context.Context, client openai.Client, model, provid
return processEmbeddings(log, raw, provider)
}

// embeddingPassthroughOpts uses models.PassthroughToken so the embedding client
// resolves API key passthrough the same way as the chat/completions clients in
// go/adk/pkg/models.
func embeddingPassthroughOpts(ctx context.Context, cfg *adk.EmbeddingConfig, isAzureFamily bool) []option.RequestOption {
if cfg == nil {
return nil
}
token, ok := models.PassthroughToken(ctx, cfg.APIKeyPassthrough)
if !ok {
return nil
}
if isAzureFamily {
return []option.RequestOption{option.WithHeader("Api-Key", token)}
}
return []option.RequestOption{option.WithAPIKey(token)}
}

func (p *openAIProvider) generate(ctx context.Context, texts []string) ([][]float32, error) {
return generateEmbeddings(ctx, p.client, p.config.Model, "openai", texts)
return generateEmbeddings(ctx, p.client, p.config, "openai", false, texts)
}

type azureOpenAIProvider struct {
Expand Down Expand Up @@ -171,8 +189,16 @@ func newAzureOpenAIProvider(cfg *adk.EmbeddingConfig, cred azureai.TokenCredenti
APIVersion: apiVersion,
HTTPClient: defaultProviderHTTPClient(),
}
// Implicit auth mirrors NewAzureOpenAIModelWithLogger: the incoming bearer
// token when APIKeyPassthrough is enabled (a placeholder Api-Key is
// overwritten per request by embeddingPassthroughOpts), otherwise the
// AZURE_OPENAI_API_KEY Api-Key header, otherwise DefaultAzureCredential.
apiKey := os.Getenv("AZURE_OPENAI_API_KEY")
if cfg.APIKeyPassthrough {
apiKey = "passthrough"
}
if err := azureai.ApplyImplicitAuth(context.Background(), &clientCfg, azureai.AuthOptions{
APIKey: os.Getenv("AZURE_OPENAI_API_KEY"),
APIKey: apiKey,
Credential: cred,
}); err != nil {
return nil, err
Expand All @@ -189,7 +215,7 @@ func newAzureOpenAIProvider(cfg *adk.EmbeddingConfig, cred azureai.TokenCredenti
}

func (p *azureOpenAIProvider) generate(ctx context.Context, texts []string) ([][]float32, error) {
return generateEmbeddings(ctx, p.client, p.config.Model, "azure_openai", texts)
return generateEmbeddings(ctx, p.client, p.config, "azure_openai", true, texts)
}

type ollamaProvider struct {
Expand Down Expand Up @@ -408,8 +434,14 @@ func newFoundryProvider(cfg *adk.EmbeddingConfig, cred azureai.TokenCredential)
APIVersion: apiVersion,
HTTPClient: defaultProviderHTTPClient(),
}
// See newAzureOpenAIProvider - the passthrough placeholder short-circuits
// past DefaultAzureCredential resolution the same way it does for chat.
apiKey := os.Getenv(azureai.FoundryAPIKeyEnvVar)
if cfg.APIKeyPassthrough {
apiKey = "passthrough"
}
if err := azureai.ApplyImplicitAuth(context.Background(), &clientCfg, azureai.AuthOptions{
APIKey: os.Getenv(azureai.FoundryAPIKeyEnvVar),
APIKey: apiKey,
Credential: cred,
}); err != nil {
return nil, err
Expand All @@ -423,5 +455,5 @@ func newFoundryProvider(cfg *adk.EmbeddingConfig, cred azureai.TokenCredential)
}

func (p *foundryProvider) generate(ctx context.Context, texts []string) ([][]float32, error) {
return generateEmbeddings(ctx, p.client, p.config.Model, "foundry", texts)
return generateEmbeddings(ctx, p.client, p.config, "foundry", true, texts)
}
145 changes: 135 additions & 10 deletions go/adk/pkg/embedding/embedding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/go-logr/logr"
"github.com/kagent-dev/kagent/go/adk/pkg/auth"
"github.com/kagent-dev/kagent/go/adk/pkg/models"
"github.com/kagent-dev/kagent/go/api/adk"
)

Expand Down Expand Up @@ -45,15 +46,8 @@ func TestOpenAIProvider_UsesAPIKeyNotKagentToken(t *testing.T) {
t.Errorf("input = %v, want [hello]", req.Input)
}

vec := make([]float64, TargetDimension)
vec[0] = 1.0
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"object": "list",
"data": []map[string]any{{"object": "embedding", "index": 0, "embedding": vec}},
"model": req.Model,
"usage": map[string]any{"prompt_tokens": 1, "total_tokens": 1},
})
json.NewEncoder(w).Encode(embeddingResponse("text-embedding-3-small"))
}))
defer srv.Close()

Expand Down Expand Up @@ -87,6 +81,69 @@ func TestOpenAIProvider_UsesAPIKeyNotKagentToken(t *testing.T) {
}
}

func TestOpenAIProvider_APIKeyPassthrough(t *testing.T) {
t.Setenv("OPENAI_API_KEY", "")

var gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(embeddingResponse("text-embedding-3-small"))
}))
defer srv.Close()

client, err := New(Config{
EmbeddingConfig: &adk.EmbeddingConfig{
Provider: "openai",
Model: "text-embedding-3-small",
BaseUrl: srv.URL,
APIKeyPassthrough: true,
},
})
if err != nil {
t.Fatalf("New() error = %v", err)
}

ctx := context.WithValue(context.Background(), models.BearerTokenKey, "the-callers-token")
if _, err := client.Generate(ctx, []string{"hello"}); err != nil {
t.Fatalf("Generate() error = %v", err)
}
if gotAuth != "Bearer the-callers-token" {
t.Errorf("Authorization = %q, want Bearer the-callers-token", gotAuth)
}
}

func TestOpenAIProvider_APIKeyPassthroughDisabled_IgnoresContextToken(t *testing.T) {
t.Setenv("OPENAI_API_KEY", "sk-static-key")

var gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(embeddingResponse("text-embedding-3-small"))
}))
defer srv.Close()

client, err := New(Config{
EmbeddingConfig: &adk.EmbeddingConfig{
Provider: "openai",
Model: "text-embedding-3-small",
BaseUrl: srv.URL,
},
})
if err != nil {
t.Fatalf("New() error = %v", err)
}

ctx := context.WithValue(context.Background(), models.BearerTokenKey, "should-be-ignored")
if _, err := client.Generate(ctx, []string{"hello"}); err != nil {
t.Fatalf("Generate() error = %v", err)
}
if gotAuth != "Bearer sk-static-key" {
t.Errorf("Authorization = %q, want Bearer sk-static-key (passthrough disabled)", gotAuth)
}
}

func TestNormalizeL2(t *testing.T) {
normed := normalizeL2([]float32{3, 4})
var sum float64
Expand All @@ -106,7 +163,7 @@ func TestProcessEmbeddings_RejectsUndersized(t *testing.T) {
}
}

func azureEmbeddingResponse(model string) map[string]any {
func embeddingResponse(model string) map[string]any {
vec := make([]float64, TargetDimension)
vec[0] = 1.0
return map[string]any{
Expand Down Expand Up @@ -177,7 +234,7 @@ func TestAzureOpenAIProvider_RequestShape(t *testing.T) {
gotAPIKey = r.Header.Get("Api-Key")
gotAPIVersion = r.URL.Query().Get("api-version")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(azureEmbeddingResponse(deployment))
json.NewEncoder(w).Encode(embeddingResponse(deployment))
}))
defer srv.Close()

Expand Down Expand Up @@ -218,6 +275,74 @@ func TestAzureOpenAIProvider_RequestShape(t *testing.T) {
}
}

func TestAzureOpenAIProvider_APIKeyPassthrough(t *testing.T) {
t.Setenv("AZURE_OPENAI_API_KEY", "")

var gotAPIKey, gotAuth string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAPIKey = r.Header.Get("Api-Key")
gotAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(embeddingResponse("text-embedding-3-small"))
}))
defer srv.Close()

client, err := New(Config{
EmbeddingConfig: &adk.EmbeddingConfig{
Provider: "azure_openai",
Model: "text-embedding-3-small",
Endpoint: srv.URL,
APIKeyPassthrough: true,
},
})
if err != nil {
t.Fatalf("New() error = %v", err)
}

ctx := context.WithValue(context.Background(), models.BearerTokenKey, "the-callers-token")
if _, err := client.Generate(ctx, []string{"hello"}); err != nil {
t.Fatalf("Generate() error = %v", err)
}
if gotAPIKey != "the-callers-token" {
t.Errorf("Api-Key = %q, want the-callers-token", gotAPIKey)
}
if gotAuth != "" {
t.Errorf("Authorization = %q, want empty (Azure uses Api-Key)", gotAuth)
}
}

func TestAzureOpenAIProvider_APIKeyPassthroughOverridesStaticKey(t *testing.T) {
t.Setenv("AZURE_OPENAI_API_KEY", "static-key-should-be-overridden")

var gotAPIKey string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAPIKey = r.Header.Get("Api-Key")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(embeddingResponse("text-embedding-3-small"))
}))
defer srv.Close()

client, err := New(Config{
EmbeddingConfig: &adk.EmbeddingConfig{
Provider: "azure_openai",
Model: "text-embedding-3-small",
Endpoint: srv.URL,
APIKeyPassthrough: true,
},
})
if err != nil {
t.Fatalf("New() error = %v", err)
}

ctx := context.WithValue(context.Background(), models.BearerTokenKey, "the-callers-token")
if _, err := client.Generate(ctx, []string{"hello"}); err != nil {
t.Fatalf("Generate() error = %v", err)
}
if gotAPIKey != "the-callers-token" {
t.Errorf("Api-Key = %q, want the-callers-token", gotAPIKey)
}
}

func TestAzureOpenAIProvider_MissingEndpoint(t *testing.T) {
t.Setenv("AZURE_OPENAI_ENDPOINT", "")
_, err := New(Config{
Expand Down
Loading
Loading