12 KiB
AI EmbeddingModel Module
Summary
Add an EmbeddingModel module to effect/unstable/ai that provides a
provider-agnostic service for generating vector embeddings from text, with
built-in batching via RequestResolver and telemetry integration.
Background
The v3 @effect/ai package included an EmbeddingModel module that used
Effect's Request/RequestResolver system for batching and optional caching.
It also had a makeDataLoader variant using @effect/experimental. In v4, the
AI modules have been consolidated into the core effect package under
effect/unstable/ai, following new patterns:
- Services use
ServiceMap.Service(notContext.Tag) RequestResolvernatively supports data loader patterns viasetDelay/batchN- Caching is handled via
RequestResolver.withCache/asCache - Providers can expose the service via
Layer.effect
Goals
- Define an
EmbeddingModelservice following v4ServiceMap.Servicepatterns - Provide
embed(single string) andembedMany(batch) operations - Return response classes with metadata (usage/token info), consistent with
LanguageModel.GenerateTextResponse - Use
RequestResolverfor batching; let users compose caching/delay via resolver combinators - Keep the provider API minimal: batch inputs in, vectors out
- Add spans around the resolver and service methods
- Keep the module focused and simple compared to
LanguageModel
Non-goals
- Streaming embeddings (not a standard pattern)
- Token array inputs (only string inputs)
- Built-in caching in the constructor (composable via
RequestResolverAPIs) - Image or multimodal embeddings
Requirements
Service Definition
The EmbeddingModel service class must use the ServiceMap.Service pattern:
export class EmbeddingModel extends ServiceMap.Service<EmbeddingModel, Service>()(
"effect/unstable/ai/EmbeddingModel"
) {}
Service Interface
export interface Service {
readonly resolver: RequestResolver.RequestResolver<EmbeddingRequest>
readonly embed: (
input: string
) => Effect.Effect<EmbedResponse, AiError.AiError>
readonly embedMany: (
input: ReadonlyArray<string>
) => Effect.Effect<EmbedManyResponse, AiError.AiError>
}
The resolver property exposes the pre-constructed RequestResolver so users
can compose caching, delay, and batch sizing via resolver combinators
(RequestResolver.withCache, setDelay, batchN, etc.) without
reimplementing the batching logic.
Response Types
Schema classes using Schema.Class, following the pattern used by
Response.Usage in Response.ts. This enables serialization for RPC,
persistence, and devtools.
EmbeddingUsage -- token usage for embedding operations:
export class EmbeddingUsage extends Schema.Class<EmbeddingUsage>(
"effect/ai/EmbeddingModel/EmbeddingUsage"
)({
inputTokens: Schema.UndefinedOr(Schema.Finite)
}) {}
Named inputTokens to align with OpenTelemetry gen_ai.usage.input_tokens
and the Response.Usage pattern. Embedding APIs only report input tokens
(no output tokens like language models). Uses Schema.UndefinedOr since the
field is always present but may be undefined when the provider doesn't
report token counts.
EmbedResponse -- response for a single embedding:
export class EmbedResponse extends Schema.Class<EmbedResponse>(
"effect/ai/EmbeddingModel/EmbedResponse"
)({
vector: Schema.Array(Schema.Finite)
}) {}
Individual EmbedResponse from embed does not include usage. When requests
are batched by the resolver, the provider returns one aggregated usage for the
entire batch. Attributing per-request usage is not possible since the provider
reports a single total. Usage is only available at the batch level via
EmbedManyResponse.
EmbedManyResponse -- response for batch embeddings:
export class EmbedManyResponse extends Schema.Class<EmbedManyResponse>(
"effect/ai/EmbeddingModel/EmbedManyResponse"
)({
embeddings: Schema.Array(EmbedResponse),
usage: EmbeddingUsage
}) {}
Provider Interface
Providers implement embedMany only. The make constructor wraps it:
export interface ProviderOptions {
readonly inputs: ReadonlyArray<string>
}
export interface ProviderResponse {
readonly results: Array<Array<number>>
readonly usage: {
readonly inputTokens: number | undefined
}
}
ProviderOptions does not include a span field. The resolver batches
requests from multiple concurrent embed callers, so there is no single
natural parent span. Spans are managed by the resolver and service methods,
not the provider callback. Provider implementations can add their own spans
internally if they need more detail.
Constructor
The make constructor takes a provider's embedMany function and creates
the service:
export const make: (params: {
readonly embedMany: (
options: ProviderOptions
) => Effect.Effect<ProviderResponse, AiError.AiError>
}) => Effect.Effect<Service>
Internal behavior using v4 RequestResolver.make pattern:
-
Create a
RequestResolverusingRequestResolver.make. The resolver callback receives the current batch ofRequest.Entry<EmbeddingRequest>:const resolver = RequestResolver.make( (entries) => { // 1. Collect inputs from entries const inputs = entries.map((e) => e.request.input) // 2. Call provider's embedMany // 3. Validate the provider returned one vector per input // 4. Complete entries by index order } ) -
For each entry in the batch, extract
entry.request.inputto build the input array. -
Call the provider's
embedMany({ inputs }). -
On success, validate
response.results.length === inputs.length, then iterate the returned vectors and complete each entry by index:entries[i].completeUnsafe( Exit.succeed(new EmbedResponse({ vector: response.results[i] })) ) -
If the provider returns the wrong number of vectors, fail with an
AiError.InvalidOutputErrordescribing the mismatch. -
embed(input)creates a singleEmbeddingRequestand resolves it viaEffect.request(new EmbeddingRequest({ input }), resolver), wrapped inEffect.withSpan("EmbeddingModel.embed"). -
embedMany(inputs)calls the provider'sembedManydirectly (bypassing the resolver), maps theProviderResponseinto anEmbedManyResponse, and wraps inEffect.withSpan("EmbeddingModel.embedMany"). -
Empty array handling:
embedMany([])returns immediately with an emptyEmbedManyResponse(empty embeddings array, usage withinputTokens: 0). The provider is never called.
Provider integration with Layer:
Providers wrap make in a Layer for dependency injection:
// In a provider package (e.g., @effect/ai-openai)
const layer = Layer.effect(
EmbeddingModel.EmbeddingModel,
EmbeddingModel.make({
embedMany: (options) => /* call provider API */
})
)
Request Type
Public tagged request class for the resolver (exported so users can work
with the resolver property directly):
export class EmbeddingRequest extends Request.TaggedClass("EmbeddingRequest")<
{ readonly input: string },
EmbedResponse,
AiError.AiError
> {}
Telemetry
Span behavior:
embedis wrapped inEffect.withSpan("EmbeddingModel.embed").- The shared resolver is wrapped in
RequestResolver.withSpan("EmbeddingModel.resolver"). embedManyis wrapped inEffect.withSpan("EmbeddingModel.embedMany").- Provider callbacks stay focused on data conversion; provider-specific telemetry is optional and local to the provider implementation.
Module JSDoc
Follow the established pattern from Tokenizer.ts and LanguageModel.ts:
- Module-level JSDoc with
@exampleblocks showing basic usage @since 4.0.0- Category annotations:
services,models,constructors
Barrel Export
The module must be exported from packages/effect/src/unstable/ai/index.ts.
Since barrel files are auto-generated, run pnpm codegen after creating the
module.
Testing
Tests go in packages/effect/test/unstable/ai/EmbeddingModel.test.ts.
Use @effect/vitest with it.effect pattern. Use assert (not expect).
Test Cases
-
embedreturns a vector -- Create a mock provider that returns a fixed vector. Callembed("hello"). Assert the vector matches. -
embedManyreturns multiple vectors with usage -- Create a mock provider that returns vectors and usage. CallembedMany(["hello", "world"]). Assert both vectors are returned with correct ordering and usage is populated. -
embedbatches multiple concurrent calls -- Create a mock provider that tracks call count. Fire multipleembedcalls concurrently withEffect.all([embed("a"), embed("b"), embed("c")]). Assert the provider'sembedManywas called once (all requests batched together). -
Error propagation -- Create a mock provider that fails with an
AiError. Callembed. Assert the error propagates correctly with the right tag and reason. -
embedManywith empty array -- CallembedMany([]). Assert it returns anEmbedManyResponsewith empty embeddings andinputTokens: 0usage. -
Invalid provider result count -- Create a mock provider that returns fewer vectors than requested. Assert
embedandembedManyfail withAiError.InvalidOutputError.
Validation
After implementation, run in order:
pnpm codegen(regenerate barrel exports -- must run before check/test)pnpm lint-fixpnpm test packages/effect/test/unstable/ai/EmbeddingModel.test.tspnpm check:tsgo(if failing,pnpm cleanthen re-run)pnpm docgen
Acceptance Criteria
EmbeddingModelservice defined withServiceMap.ServicepatternembedandembedManymethods on the service interfaceEmbedResponse,EmbedManyResponse, andEmbeddingUsageresponse classesmakeconstructor wraps provider'sembedManywithRequestResolver- Provider responses return vectors in positional order via
results - Automatic batching when multiple
embedcalls are concurrent - Spans on
resolver,embed, andembedMany - All errors typed as
AiError.AiError - Module exported from
effect/unstable/aibarrel - Tests pass covering core functionality, batching, and error propagation
- All validation commands pass (
codegen,lint-fix,test,check:tsgo,docgen)
Implementation Plan
Task 1: Create EmbeddingModel module with service, types, constructor, and tests
Create packages/effect/src/unstable/ai/EmbeddingModel.ts containing:
EmbeddingModelservice class (ServiceMap.Service)Serviceinterface withembedandembedManyEmbedResponse,EmbedManyResponse,EmbeddingUsageschema-based classesProviderOptionsandProviderResponseinterfaces- Internal
EmbeddingRequesttagged request class makeconstructor that:- Creates a
RequestResolverusingRequestResolver.makewith the v4 entry-based API - Implements
embedusingEffect.request+ the resolver - Implements
embedManyby calling the provider directly - Validates provider result counts before constructing responses
- Wraps both in
Effect.withSpan
- Creates a
Then run pnpm codegen to add the barrel export to
packages/effect/src/unstable/ai/index.ts.
Create packages/effect/test/unstable/ai/EmbeddingModel.test.ts with tests
for: single embed, embedMany with usage, batching behavior, error propagation,
and empty input.
Validation: pnpm codegen && pnpm lint-fix && pnpm test packages/effect/test/unstable/ai/EmbeddingModel.test.ts && pnpm check:tsgo && pnpm docgen