-
Notifications
You must be signed in to change notification settings - Fork 402
BYOK: build an embedding service from a runtime-supplied key #1892
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
+633
−3
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
854dbd0
Build an embedding service from a runtime-supplied key
jasperblues 43a2be8
Reject a blank key on the embedding path too
jasperblues 4155921
Name the model when embedding validation fails
jasperblues feac1a7
One exit path for embedding validation, and a multi-line message
jasperblues d026678
Move the probe-and-stamp algorithm out of the OpenAI module
jasperblues 5949d96
Correct the extracted helper's contract, and drop a Pair from its test
jasperblues 583c9ab
Say what the validation try block actually covers, and drop a duplica…
jasperblues b5e2e28
Name the model ids in tests, and drop a redundant dependency declaration
jasperblues 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
77 changes: 77 additions & 0 deletions
77
...-common/embabel-agent-byok/src/main/kotlin/com/embabel/common/byok/embeddingValidation.kt
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,77 @@ | ||
| /* | ||
| * Copyright 2024-2026 Embabel Pty Ltd. | ||
| * | ||
| * 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 com.embabel.common.byok | ||
|
|
||
| import com.embabel.common.ai.model.EmbeddingService | ||
|
|
||
| /** Short, cheap text used to probe an embedding key. */ | ||
| private const val EMBEDDING_VALIDATION_PROBE = "Hi" | ||
|
|
||
| /** | ||
| * Validate a runtime-supplied embedding key by embedding one probe, and return a service that | ||
| * knows the width the model actually produced. | ||
| * | ||
| * Provider-agnostic: [build] supplies the provider's own [EmbeddingService], called once to | ||
| * probe and once more to produce the result with the observed width stamped on it. | ||
| * | ||
| * Stamping matters beyond saving a call. Spring AI's `AbstractEmbeddingModel.dimensions()` | ||
| * caches, but resolves via `dimensions(this, "Test", "Hello World")` — passing the literal | ||
| * `"Test"` as the model name, so its known-dimensions table can never hit and it always falls | ||
| * through to a live `embed()`. Left lazy that happens at an arbitrary later moment and can fail | ||
| * there. The probe already has the width; take it. | ||
| * | ||
| * The width is never taken from the caller: it is whatever the model returned. A caller writing | ||
| * into an existing index should compare [EmbeddingService.dimensions] against that index's width | ||
| * before storing anything — vectors of different widths cannot share an index. That check belongs | ||
| * to whatever owns the index. | ||
| * | ||
| * This never sees the API key — [build] closes over whatever credential the provider needs — so | ||
| * it cannot reject a blank one. Callers holding a key should check that themselves before getting | ||
| * here, so an empty string fails with something actionable rather than as a provider error. | ||
| * | ||
| * @param model the embedding model to validate. Always explicit: unlike an LLM it is never | ||
| * defaulted and never detected, because the width it commits an index to must not be decided by | ||
| * whichever provider happens to answer first. | ||
| * @param provider provider name, used only in the failure message | ||
| * @param build builds the provider's service, given the width to stamp (null while probing) | ||
| * @throws InvalidApiKeyException if the probe fails - an invalid key, an unreachable provider, a | ||
| * model the key cannot use - or if the model returns no vector | ||
| */ | ||
| fun validatedEmbeddingService( | ||
|
jasperblues marked this conversation as resolved.
|
||
| model: String, | ||
| provider: String, | ||
| build: (configuredDimensions: Int?) -> EmbeddingService, | ||
| ): EmbeddingService { | ||
| // All three failure modes here mean the same thing to the caller - the model could not be | ||
| // validated - so they share one exit rather than throwing from three places. Construction is | ||
| // inside the try on purpose: building the probe service is where a malformed base URL or an | ||
| // unusable credential surfaces for several providers, so it is part of validation rather than | ||
| // separate from it. The message names the model: it is caller-supplied and mandatory, so a | ||
| // typo in it arrives as the same provider error, and "invalid API key" alone would send | ||
| // someone to re-check a key that was fine. | ||
| val vector = try { | ||
| build(null).embed(EMBEDDING_VALIDATION_PROBE) | ||
| .also { require(it.isNotEmpty()) { "the model returned an empty vector" } } | ||
| } catch (e: Exception) { | ||
| throw InvalidApiKeyException( | ||
| "Could not validate embedding model '$model' on $provider: ${e.message ?: "no detail"}", | ||
| ) | ||
| } | ||
| // Outside the try, unlike the call above. The credential and the model have both just been | ||
| // proven to work, so anything thrown here is a bug in the builder and must not be reported as | ||
| // a rejected key - that would send someone to re-check a key this function just validated. | ||
| return build(vector.size) | ||
| } | ||
103 changes: 103 additions & 0 deletions
103
...mon/embabel-agent-byok/src/test/kotlin/com/embabel/common/byok/EmbeddingValidationTest.kt
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,103 @@ | ||
| /* | ||
| * Copyright 2024-2026 Embabel Pty Ltd. | ||
| * | ||
| * 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 com.embabel.common.byok | ||
|
|
||
| import com.embabel.common.ai.model.EmbeddingService | ||
| import com.embabel.common.ai.model.PricingModel | ||
| import org.junit.jupiter.api.Assertions.assertEquals | ||
| import org.junit.jupiter.api.Assertions.assertTrue | ||
| import org.junit.jupiter.api.Test | ||
| import org.junit.jupiter.api.assertThrows | ||
|
|
||
| /** | ||
| * The probe-and-stamp algorithm, independent of any provider. It lives here rather than in a | ||
| * provider module because nothing about it is provider-specific: the caller supplies the | ||
| * service, this supplies the validation. | ||
| */ | ||
| class EmbeddingValidationTest { | ||
|
|
||
| private class FakeEmbeddingService( | ||
| override val name: String, | ||
| override val provider: String, | ||
| private val configuredDimensions: Int?, | ||
| override val pricingModel: PricingModel? = null, | ||
| private val respond: (String) -> FloatArray, | ||
| ) : EmbeddingService { | ||
| override fun embed(text: String): FloatArray = respond(text) | ||
| override fun embed(texts: List<String>): List<FloatArray> = texts.map(respond) | ||
| override val dimensions: Int | ||
| get() = configuredDimensions ?: error("dimensions not configured") | ||
| } | ||
|
|
||
| /** | ||
| * Stands in for a provider's builder, recording the width it was asked to stamp on each call. | ||
| */ | ||
| private class RecordingBuilder( | ||
| private val respond: (String) -> FloatArray, | ||
| ) : (Int?) -> EmbeddingService { | ||
|
|
||
| val widthsRequested = mutableListOf<Int?>() | ||
|
|
||
| override fun invoke(configuredDimensions: Int?): EmbeddingService { | ||
| widthsRequested += configuredDimensions | ||
| return FakeEmbeddingService( | ||
| name = "text-embedding-3-small", | ||
| provider = "acme", | ||
| configuredDimensions = configuredDimensions, | ||
| respond = respond, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| fun `probes once, then stamps the width the model actually returned`() { | ||
| var probes = 0 | ||
| val build = RecordingBuilder { probes++; FloatArray(3072) } | ||
|
|
||
| val service = validatedEmbeddingService("text-embedding-3-large", "acme", build) | ||
|
|
||
| assertEquals(1, probes, "should probe exactly once") | ||
| assertEquals(3072, service.dimensions) | ||
| assertEquals( | ||
| listOf(null, 3072), | ||
| build.widthsRequested, | ||
| "probe with no width, then stamp the one observed", | ||
| ) | ||
| } | ||
|
|
||
| @Test | ||
| fun `a provider error is translated, and names the model`() { | ||
| val build = RecordingBuilder { throw RuntimeException("404 model not found") } | ||
|
|
||
| val e = assertThrows<InvalidApiKeyException> { | ||
| validatedEmbeddingService("text-embedding-3-smal", "acme", build) | ||
| } | ||
|
|
||
| // The model is caller-supplied and mandatory here, so a typo in it is at least as likely | ||
| // as a bad key and must be visible in the message. | ||
| assertTrue(e.message!!.contains("text-embedding-3-smal"), e.message) | ||
| assertTrue(e.message!!.contains("acme"), e.message) | ||
| } | ||
|
|
||
| @Test | ||
| fun `an empty vector is a validation failure, not a zero-width service`() { | ||
| val build = RecordingBuilder { FloatArray(0) } | ||
|
|
||
| assertThrows<InvalidApiKeyException> { | ||
| validatedEmbeddingService("text-embedding-3-small", "acme", build) | ||
| } | ||
| } | ||
| } |
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
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.
Uh oh!
There was an error while loading. Please reload this page.