Repository navigation
Description
What happens
EmbeddingModel.embed puts all calls from the same scheduler tick into one batch. The batch makes one embedMany call to the provider. This call runs with the context of the first caller in the batch. So if the provider reads a service inside embedMany, every caller gets the first caller's service. The services of the other callers are ignored, and there is no error.
OpenAiEmbeddingModel reads its Config in this way. This means withConfigOverride does not work reliably with embed. Example: two concurrent embed calls set dimensions to 256 and to 1024. Only one request is sent, with dimensions: 256. The caller that asked for 1024 gets a vector with 256 numbers.
embedMany does not have this bug, because it calls the provider in the caller's own fiber.
Reproduction
Effect main at 4cddd3c (effect 4.0.5). Save the code as a .ts file inside the repository and run it with node.
import { OpenAiClient, OpenAiEmbeddingModel } from "@effect/ai-openai"
import { Context, Effect, Layer, Redacted } from "effect"
import { EmbeddingModel } from "effect/ai"
import { HttpClient, type HttpClientError, HttpClientResponse } from "effect/http"
// 1. Core: a provider that reads a context service inside `embedMany`.
class InputType extends Context.Service<InputType, "query" | "document">()("probe/InputType") {}
const coreProbe = Effect.gen(function*() {
const seen: Array<{ inputs: ReadonlyArray<string>; inputType: string }> = []
const model = yield* EmbeddingModel.make({
embedMany: ({ inputs }) =>
Effect.gen(function*() {
const inputType = yield* Effect.serviceOption(InputType)
seen.push({ inputs, inputType: inputType._tag === "Some" ? inputType.value : "none" })
return { results: inputs.map(() => [0]), usage: { inputTokens: undefined } }
})
})
yield* Effect.all([
model.embed("a document").pipe(Effect.provideService(InputType, "document")),
model.embed("a query").pipe(Effect.provideService(InputType, "query"))
], { concurrency: "unbounded" })
return seen
})
// 2. OpenAiEmbeddingModel: `withConfigOverride({ dimensions })` on two concurrent `embed` calls.
const requests: Array<{ input: unknown; dimensions: unknown }> = []
const httpClient = HttpClient.makeWith(
Effect.fnUntraced(function*(requestEffect) {
const request = yield* requestEffect
const body = JSON.parse(new TextDecoder().decode((request.body as any).body))
requests.push({ input: body.input, dimensions: body.dimensions })
const size = body.dimensions ?? 1536
return HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
data: body.input.map((_: string, index: number) => ({
index,
embedding: Array.from({ length: size }, () => 0),
object: "embedding"
})),
model: body.model,
object: "list",
usage: { prompt_tokens: 1, total_tokens: 1 }
}),
{ status: 200, headers: { "content-type": "application/json" } }
)
)
}),
Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
)
const openAiProbe = Effect.gen(function*() {
const model = yield* EmbeddingModel.EmbeddingModel
const [small, large] = yield* Effect.all([
model.embed("small").pipe(OpenAiEmbeddingModel.withConfigOverride({ dimensions: 256 })),
model.embed("large").pipe(OpenAiEmbeddingModel.withConfigOverride({ dimensions: 1024 }))
], { concurrency: "unbounded" })
return { smallLength: small.vector.length, largeLength: large.vector.length }
}).pipe(
Effect.provide(OpenAiEmbeddingModel.layer({ model: "text-embedding-3-small" })),
Effect.provide(
OpenAiClient.layer({ apiKey: Redacted.make("sk-test") }).pipe(
Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient))
)
)
)
const main = Effect.gen(function*() {
console.log("core embedMany calls:", JSON.stringify(yield* coreProbe))
const lengths = yield* openAiProbe
console.log("openai requests:", JSON.stringify(requests))
console.log("openai vector lengths:", JSON.stringify(lengths))
})
Effect.runPromise(main)Output:
core embedMany calls: [{"inputs":["a document","a query"],"inputType":"document"}]
openai requests: [{"input":["small","large"],"dimensions":256}]
openai vector lengths: {"smallLength":256,"largeLength":256}
The first line shows that the query was sent with the document's input type. The other lines show that the caller that asked for 1024 dimensions got 256.
Expected
Each embed call uses the settings from its own context. Calls with equal settings can share a request. Calls with different settings must not share a request. In the reproduction, the query is embedded as a query, and the caller that asked for 1024 dimensions gets 1024 numbers.
Cause
EmbeddingModel.make (packages/effect/src/ai/EmbeddingModel.ts:226) creates its resolver with RequestResolver.make (:229). The resolver gives only the inputs to the provider (:232):
params.embedMany({ inputs: entries.map((entry) => entry.request.input) })RequestResolver.make puts all pending requests into one batch, because its default batch key is the same for every request. The batch fiber starts with the context of the fiber that created the batch (packages/effect/src/internal/request.ts:203 and :212). This is the first caller's context. Each Request.Entry has the context of its own caller (internal/request.ts:131), but EmbeddingModel.make does not give the entries to the provider. So the provider cannot group the inputs by its settings, and it cannot read the settings for each entry.
OpenAiEmbeddingModel.make (packages/ai/openai/src/OpenAiEmbeddingModel.ts:138) reads the scoped Config with Effect.contextWith inside embedMany. So it reads the context of the batch fiber. OpenAiClient reads a scoped OpenAiConfig.withClientTransform in the same way when it sends the request, so a client transform has the same problem. @effect/ai-openai-compat has the same code.
Who is affected
- Programs that call
embedconcurrently with differentwithConfigOverrideorOpenAiConfig.withClientTransformscopes. Some results use the wrong settings, and there is no error. WithwithClientTransform, the headers of one caller, for example a tenant header, can be sent with the request of another caller. - Providers where a setting changes the meaning of a vector. For example, Cohere Embed needs an
input_type. A search program embeds documents withsearch_documentand queries withsearch_query. WithEmbeddingModel.make, a concurrent query and document share one request with oneinput_type. We found the bug this way, while designing embeddings for an Amazon Bedrock provider built oneffect/ai. - A wrong
dimensionsoverride gives vectors with a different length than the caller expects. A vector store usually rejects these vectors later, far away from the cause.
Possible directions
EmbeddingModel.makegroups the requests withRequestResolver.makeGrouped, using a key built from each caller's context. Callers with different services get different batches. Callers with equal settings still share a batch.EmbeddingModel.makegives the context of each caller, or the entries, toembedMany, and each provider groups the batch itself. This gives more work to every provider, and a provider that forgets it still has the bug.- Document that
embedignores context overrides, and that programs that need settings per call must useembedMany. This does not fix the behaviour.
The embeddings for the Amazon Bedrock provider are not released yet. To avoid the bug, the current design builds the EmbeddingModel service with EmbeddingModel.of and its own embed resolver from RequestResolver.makeGrouped. It still uses embedMany from EmbeddingModel.make. With direction 1, the provider could use EmbeddingModel.make directly.
The same problem exists in RequestResolver itself, for example in RequestResolver.fromEffect, batchN, and SqlResolver. This issue is only about EmbeddingModel. A separate issue covers RequestResolver.
Activity