@opencode/ai 0.0.0-dev-1068 → 0.0.0-dev-1111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +94 -4
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/effect.d.ts +6 -0
  5. package/dist/effect.js +4 -0
  6. package/dist/embedding-client.d.ts +21 -0
  7. package/dist/embedding-client.js +30 -0
  8. package/dist/embedding.d.ts +111 -0
  9. package/dist/embedding.js +75 -0
  10. package/dist/image.d.ts +0 -1
  11. package/dist/image.js +0 -3
  12. package/dist/index.d.ts +7 -2
  13. package/dist/index.js +5 -0
  14. package/dist/protocols/google-embed-content.d.ts +34 -0
  15. package/dist/protocols/google-embed-content.js +110 -0
  16. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  17. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  18. package/dist/protocols/index.d.ts +3 -0
  19. package/dist/protocols/index.js +3 -0
  20. package/dist/protocols/openai-embeddings.d.ts +16 -0
  21. package/dist/protocols/openai-embeddings.js +76 -0
  22. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  23. package/dist/providers/alibaba/embeddings.js +1 -0
  24. package/dist/providers/alibaba.d.ts +2 -0
  25. package/dist/providers/alibaba.js +14 -1
  26. package/dist/providers/azure/embeddings.d.ts +2 -0
  27. package/dist/providers/azure/embeddings.js +1 -0
  28. package/dist/providers/azure.d.ts +2 -0
  29. package/dist/providers/azure.js +15 -0
  30. package/dist/providers/cohere/embeddings.d.ts +2 -0
  31. package/dist/providers/cohere/embeddings.js +1 -0
  32. package/dist/providers/cohere.d.ts +6 -0
  33. package/dist/providers/cohere.js +17 -1
  34. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  35. package/dist/providers/deepinfra/embeddings.js +1 -0
  36. package/dist/providers/deepinfra.d.ts +4 -1
  37. package/dist/providers/deepinfra.js +15 -1
  38. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  39. package/dist/providers/digitalocean/embeddings.js +1 -0
  40. package/dist/providers/digitalocean.d.ts +4 -0
  41. package/dist/providers/digitalocean.js +15 -0
  42. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  43. package/dist/providers/fireworks/embeddings.js +1 -0
  44. package/dist/providers/fireworks.d.ts +4 -1
  45. package/dist/providers/fireworks.js +15 -1
  46. package/dist/providers/google/embeddings.d.ts +2 -0
  47. package/dist/providers/google/embeddings.js +1 -0
  48. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  49. package/dist/providers/google-vertex/embeddings.js +1 -0
  50. package/dist/providers/google-vertex.d.ts +7 -0
  51. package/dist/providers/google-vertex.js +52 -0
  52. package/dist/providers/google.d.ts +6 -0
  53. package/dist/providers/google.js +14 -0
  54. package/dist/providers/openai/embeddings.d.ts +2 -0
  55. package/dist/providers/openai/embeddings.js +1 -0
  56. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  57. package/dist/providers/openai-compatible/embeddings.js +1 -0
  58. package/dist/providers/openai-compatible.d.ts +3 -0
  59. package/dist/providers/openai-compatible.js +13 -0
  60. package/dist/providers/openai.d.ts +6 -0
  61. package/dist/providers/openai.js +14 -0
  62. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  63. package/dist/providers/openrouter/embeddings.js +1 -0
  64. package/dist/providers/openrouter.d.ts +9 -0
  65. package/dist/providers/openrouter.js +15 -0
  66. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  67. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  68. package/dist/providers/vercel-ai-gateway.d.ts +4 -0
  69. package/dist/providers/vercel-ai-gateway.js +15 -1
  70. package/dist/public.d.ts +2 -0
  71. package/dist/public.js +1 -0
  72. package/dist/route/embedding.d.ts +61 -0
  73. package/dist/route/embedding.js +88 -0
  74. package/package.json +55 -3
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @opencode/ai
2
2
 
3
- Schema-first APIs for text, images, and decisions, built with Effect. Video, speech, transcription, extraction, and
3
+ Schema-first APIs for text, images, decisions, and embeddings, built with Effect. Video, speech, transcription, extraction, and
4
4
  realtime voice are [experimental](#experimental).
5
5
 
6
6
  `@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
@@ -16,7 +16,7 @@ const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
16
16
  const response = await ai.generate(input)
17
17
  console.log(response.text)
18
18
  const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
19
- await ai.write(generated.image, "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
19
+ await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
20
20
  for await (const event of ai.stream(ai.request(input))) {
21
21
  // LLMEvent
22
22
  }
@@ -226,7 +226,7 @@ const image = Effect.gen(function* () {
226
226
  resolution: "1K",
227
227
  providerOptions: { quality: "high" }, // typed per image model
228
228
  })
229
- yield* Media.write(response.image, "./garden.png")
229
+ yield* Media.write(response.images[0], "./garden.png")
230
230
  })
231
231
 
232
232
  // `Media.file` / `Media.write` use the Effect `FileSystem` service; provide your platform's layer.
@@ -357,6 +357,95 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
357
357
  OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
358
358
  DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
359
359
 
360
+ ## Embeddings
361
+
362
+ Embedding models turn each value into a vector, returned in value order.
363
+
364
+ ```ts
365
+ import { ai } from "@opencode/ai"
366
+ import { OpenAI } from "@opencode/ai/providers"
367
+
368
+ const response = await ai.embedding.generate({
369
+ model: OpenAI.configure().embedding("text-embedding-3-small"),
370
+ values: ["I was charged twice.", "How do I reset my password?"],
371
+ dimensions: 256,
372
+ inputType: "document",
373
+ })
374
+ const [charge, password] = response.embeddings
375
+ ```
376
+
377
+ A string value is text; media values are an `Asset` (or bytes or a URL) for hosts that embed images or documents.
378
+ `dimensions` asks models that can shorten their vectors for that length. `inputType` says whether the values are
379
+ search queries or stored documents; hosts with no such field (OpenAI's `/embeddings` API) ignore it, and host-specific
380
+ task types go in `providerOptions` (NVIDIA's `input_type: "passage"`). `response.usage.inputTokens` is the host's
381
+ token count, and its raw usage stays in `providerMetadata`. Media values fail the call on hosts that only embed text.
382
+
383
+ ```ts
384
+ import {
385
+ Alibaba,
386
+ Azure,
387
+ Cohere,
388
+ DeepInfra,
389
+ DigitalOcean,
390
+ Fireworks,
391
+ OpenAICompatible,
392
+ OpenRouter,
393
+ VercelAIGateway,
394
+ } from "@opencode/ai/providers"
395
+
396
+ OpenRouter.configure().embedding("openai/text-embedding-3-small")
397
+ VercelAIGateway.configure().embedding("openai/text-embedding-3-small")
398
+ Cohere.configure().embedding("embed-v4.0")
399
+ DeepInfra.configure().embedding("BAAI/bge-m3")
400
+ Fireworks.configure().embedding("nomic-ai/nomic-embed-text-v1.5")
401
+ DigitalOcean.configure().embedding("bge-m3")
402
+ Alibaba.configure({ region: "ap-southeast-1" }).embedding("text-embedding-v4")
403
+ Azure.configure({ resourceName }).embedding("text-embedding-3-small")
404
+ OpenAICompatible.configure({ provider: "nvidia", baseURL: "https://integrate.api.nvidia.com/v1" }).embedding(
405
+ "nvidia/nemotron-3.5-embed-1b",
406
+ )
407
+ ```
408
+
409
+ Every host here uses OpenAI's `/embeddings` API; Cohere through its compatibility API
410
+ (`https://api.cohere.ai/compatibility/v1`). Package entry points are `@opencode/ai/providers/<provider>/embeddings`.
411
+
412
+ Google embeds through `embedContent`, which also takes images, audio, video and PDFs on `gemini-embedding-2`. Each
413
+ value is its own content and gets its own vector (several parts in one content would be averaged into one). `dimensions`
414
+ is `outputDimensionality`, `inputType` becomes `taskType` `RETRIEVAL_QUERY` or `RETRIEVAL_DOCUMENT`, and `taskType` or
415
+ `title` in `providerOptions` replace or add to it. `gemini-embedding-2` ignores task types; Google recommends writing the
416
+ task into the text instead (`task: search result | query: …`, `title: none | text: …`).
417
+
418
+ ```ts
419
+ import { Google, GoogleVertex } from "@opencode/ai/providers"
420
+
421
+ const response = await ai.embedding.generate({
422
+ model: Google.configure().embedding("gemini-embedding-2"),
423
+ values: [await ai.file("./receipt.png"), "A receipt for two coffees."],
424
+ dimensions: 768,
425
+ })
426
+
427
+ GoogleVertex.configure({ project, location: "global" }).embedding("gemini-embedding-2")
428
+ ```
429
+
430
+ `GoogleVertex.configure().embedding(id)` picks the API from the model id: `gemini-embedding-2*` uses `embedContent`,
431
+ and every other model (`gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`) uses the
432
+ text-only `:predict` API, which also works with Express Mode keys. On `:predict`, `inputType` and the `taskType` and
433
+ `title` options go on each instance (`task_type`, `title`), and `dimensions`, `autoTruncate` and other options go under
434
+ `parameters`.
435
+
436
+ ```ts
437
+ GoogleVertex.configure({ apiKey }).embedding("text-embedding-005")
438
+ GoogleVertex.configure({ apiKey }).embedding("gemini-embedding-001")
439
+ ```
440
+
441
+ The Gemini API sends up to 100 values per `batchEmbedContents` request, and Vertex `:predict` up to 250 per request
442
+ (one for `gemini-embedding-001`, as Google documents). Vertex `embedContent` takes one value per request, so a call
443
+ sends one request per value, four at a time, and needs project credentials: Vertex Express Mode API keys can't call
444
+ `embedContent`. `gemini-embedding-2` runs in the `global`, `us` and `eu` Vertex locations. When a call
445
+ is split into several requests, the vectors stay in value order, `usage.inputTokens` is their sum, and each request's
446
+ metadata is listed in order under `providerMetadata.<provider>.responses`. The package entry points are
447
+ `@opencode/ai/providers/google/embeddings` and `@opencode/ai/providers/google-vertex/embeddings`.
448
+
360
449
  ## Alibaba Cloud Model Studio
361
450
 
362
451
  `Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
@@ -958,8 +1047,9 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
958
1047
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
959
1048
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
960
1049
  - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
1050
+ - **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`; `EmbeddingClient` is its Effect service and layer.
961
1051
  - **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
962
- - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image` and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
1052
+ - **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision` and `embedding` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
963
1053
  - **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
964
1054
 
965
1055
  ## Experimental
@@ -1,8 +1,8 @@
1
1
  import { Layer } from "effect";
2
2
  import { RequestExecutor } from "./route/executor.js";
3
3
  /** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
4
- export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
4
+ export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
5
5
  /** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
6
- export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
6
+ export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
7
7
  export type Services = Layer.Success<typeof layer>;
8
8
  export * as AIClient from "./ai-client.js";
package/dist/ai-client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Layer } from "effect";
2
2
  import { DecisionClient } from "./decision-client.js";
3
+ import { EmbeddingClient } from "./embedding-client.js";
3
4
  import { ImageClient } from "./image-client.js";
4
5
  import { LLMClient } from "./route/client.js";
5
6
  import { RequestExecutor } from "./route/executor.js";
@@ -7,7 +8,7 @@ import { SpeechClient } from "./speech-client.js";
7
8
  import { TranscriptionClient } from "./transcription-client.js";
8
9
  import { VideoClient } from "./video-client.js";
9
10
  /** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
10
- export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer).pipe(Layer.provideMerge(executor));
11
+ export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer, EmbeddingClient.layer).pipe(Layer.provideMerge(executor));
11
12
  /** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
12
13
  export const layer = layerWith(RequestExecutor.fetchLayer);
13
14
  export * as AIClient from "./ai-client.js";
package/dist/effect.d.ts CHANGED
@@ -19,6 +19,10 @@ export declare const ai: {
19
19
  readonly request: typeof import("./decision.js").request;
20
20
  readonly generate: typeof import("./decision.js").generate;
21
21
  };
22
+ readonly embedding: {
23
+ readonly request: typeof import("./embedding.js").request;
24
+ readonly generate: typeof import("./embedding.js").generate;
25
+ };
22
26
  /** Experimental: may change without compatibility guarantees. */
23
27
  readonly experimental: {
24
28
  readonly speech: {
@@ -50,6 +54,8 @@ export { ProviderPackage } from "./provider-package.js";
50
54
  export type { LLMClientService } from "./route/client.js";
51
55
  export { DecisionClient } from "./decision-client.js";
52
56
  export { DecisionRoute } from "./route/decision.js";
57
+ export { EmbeddingClient } from "./embedding-client.js";
58
+ export { EmbeddingRoute } from "./route/embedding.js";
53
59
  export { Generation } from "./generation.js";
54
60
  export { ToolFailure, emptyInputJsonSchema, toDefinitions, tool } from "./tool.js";
55
61
  export { ToolRuntime } from "./tool-runtime.js";
package/dist/effect.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Decision } from "./decision.js";
2
+ import { Embedding } from "./embedding.js";
2
3
  import { Image } from "./image.js";
3
4
  import { LLM } from "./llm.js";
4
5
  import { Speech } from "./speech.js";
@@ -15,6 +16,7 @@ export const ai = {
15
16
  canCompact: LLM.canCompact,
16
17
  image: Image,
17
18
  decision: Decision,
19
+ embedding: Embedding,
18
20
  /** Experimental: may change without compatibility guarantees. */
19
21
  experimental: {
20
22
  speech: Speech,
@@ -29,6 +31,8 @@ export { Auth } from "./route/auth.js";
29
31
  export { ProviderPackage } from "./provider-package.js";
30
32
  export { DecisionClient } from "./decision-client.js";
31
33
  export { DecisionRoute } from "./route/decision.js";
34
+ export { EmbeddingClient } from "./embedding-client.js";
35
+ export { EmbeddingRoute } from "./route/embedding.js";
32
36
  export { Generation } from "./generation.js";
33
37
  export { ToolFailure, emptyInputJsonSchema, toDefinitions, tool } from "./tool.js";
34
38
  export { ToolRuntime } from "./tool-runtime.js";
@@ -0,0 +1,21 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import type { EmbeddingModel, EmbeddingOptions, EmbeddingRequest, EmbeddingResponse } from "./embedding.js";
3
+ import { RequestExecutor } from "./route/executor.js";
4
+ import { AIError } from "./schema/index.js";
5
+ export type Execute = RequestExecutor.Interface["execute"];
6
+ export interface Interface {
7
+ readonly generate: <Options extends EmbeddingOptions>(request: EmbeddingRequest<EmbeddingModel<Options>>) => Effect.Effect<EmbeddingResponse, AIError>;
8
+ }
9
+ declare const Service_base: Context.ServiceClass<Service, "@opencode/AI/EmbeddingClient", Interface>;
10
+ export declare class Service extends Service_base {
11
+ }
12
+ export declare const generate: <Options extends EmbeddingOptions>(request: EmbeddingRequest<EmbeddingModel<Options>>) => Effect.Effect<EmbeddingResponse, AIError, Service>;
13
+ export declare const layer: Layer.Layer<Service, never, RequestExecutor.Service>;
14
+ export declare const fetchLayer: Layer.Layer<RequestExecutor.RequestExecutorService | Service, never, never>;
15
+ export declare const EmbeddingClient: {
16
+ readonly Service: typeof Service;
17
+ readonly layer: Layer.Layer<Service, never, RequestExecutor.RequestExecutorService>;
18
+ readonly fetchLayer: Layer.Layer<RequestExecutor.RequestExecutorService | Service, never, never>;
19
+ readonly generate: typeof generate;
20
+ };
21
+ export {};
@@ -0,0 +1,30 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { RequestExecutor } from "./route/executor.js";
3
+ import { AIError, InvalidProviderOutputError } from "./schema/index.js";
4
+ export class Service extends Context.Service()("@opencode/AI/EmbeddingClient") {
5
+ }
6
+ export const generate = (request) => Effect.flatMap(Service, (client) => client.generate(request));
7
+ export const layer = Layer.effect(Service, Effect.gen(function* () {
8
+ const executor = yield* RequestExecutor.Service;
9
+ return Service.of({
10
+ generate: Effect.fnUntraced(function* (request) {
11
+ const route = request.model.route;
12
+ const response = yield* route.generate(request, executor.execute);
13
+ if (response.embeddings.length === request.values.length)
14
+ return response;
15
+ return yield* new AIError({
16
+ reason: new InvalidProviderOutputError({
17
+ route: route.id,
18
+ message: `Expected ${request.values.length} embeddings, got ${response.embeddings.length}`,
19
+ }),
20
+ });
21
+ }),
22
+ });
23
+ }));
24
+ export const fetchLayer = layer.pipe(Layer.provideMerge(RequestExecutor.fetchLayer));
25
+ export const EmbeddingClient = {
26
+ Service,
27
+ layer,
28
+ fetchLayer,
29
+ generate,
30
+ };
@@ -0,0 +1,111 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Service, type Execute } from "./embedding-client.js";
3
+ import { Media } from "./media.js";
4
+ import { type AIError, type BaseRequest, type HttpOptions, ModelID, ProviderID, ProviderOptions } from "./schema/index.js";
5
+ /** One value to embed: text, or a media asset for hosts that embed images, audio or documents. */
6
+ export declare const EmbeddingValue: Schema.Union<readonly [Schema.String, Schema.decodeTo<Schema.declare<Media.Asset, Media.Asset>, Schema.Struct<{
7
+ readonly source: Schema.Union<readonly [Schema.Struct<{
8
+ readonly type: Schema.Literal<"bytes">;
9
+ readonly data: Schema.Uint8Array;
10
+ readonly mediaType: Schema.String;
11
+ }>, Schema.Struct<{
12
+ readonly type: Schema.Literal<"base64">;
13
+ readonly data: Schema.String;
14
+ readonly mediaType: Schema.String;
15
+ }>, Schema.Struct<{
16
+ readonly type: Schema.Literal<"url">;
17
+ readonly url: Schema.String;
18
+ readonly mediaType: Schema.optional<Schema.String>;
19
+ readonly expiresAt: Schema.optional<Schema.Number>;
20
+ }>, Schema.Struct<{
21
+ readonly type: Schema.Literal<"ref">;
22
+ readonly provider: Schema.brand<Schema.String, "AI.ProviderID">;
23
+ readonly id: Schema.String;
24
+ readonly mediaType: Schema.optional<Schema.String>;
25
+ }>]>;
26
+ readonly info: Schema.optional<Schema.Struct<{
27
+ readonly width: Schema.optional<Schema.Number>;
28
+ readonly height: Schema.optional<Schema.Number>;
29
+ readonly durationSeconds: Schema.optional<Schema.Number>;
30
+ readonly sampleRate: Schema.optional<Schema.Number>;
31
+ readonly channels: Schema.optional<Schema.Number>;
32
+ readonly encoding: Schema.optional<Schema.String>;
33
+ readonly format: Schema.optional<Schema.String>;
34
+ }>>;
35
+ readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
36
+ }>, never, never>]>;
37
+ export type EmbeddingValue = Schema.Schema.Type<typeof EmbeddingValue>;
38
+ /** A string is always text; media is an `Asset` or plain bytes or a URL, normalized with `Media.make`. */
39
+ export type EmbeddingValueInput = string | Exclude<Media.Input, string>;
40
+ /**
41
+ * What the vectors are for: a search `query`, or a `document` stored to be searched. Hosts without such a field embed
42
+ * both the same way and ignore it.
43
+ */
44
+ export type EmbeddingInputType = "query" | "document";
45
+ export type EmbeddingOptions = Record<string, unknown>;
46
+ /** What an embedding model's route does; `EmbeddingRoute.make(...).model(...)` builds one from a protocol. */
47
+ export interface EmbeddingModelRoute<Options extends EmbeddingOptions = EmbeddingOptions> {
48
+ readonly id: string;
49
+ generate(request: EmbeddingRequest<EmbeddingModel<Options>>, execute: Execute): Effect.Effect<EmbeddingResponse, AIError>;
50
+ }
51
+ export declare class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions> {
52
+ protected readonly _Options: Options;
53
+ readonly id: ModelID;
54
+ readonly provider: ProviderID;
55
+ readonly route: EmbeddingModelRoute<Options>;
56
+ readonly http?: HttpOptions;
57
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
58
+ readonly providerOptions?: ProviderOptions;
59
+ constructor(input: EmbeddingModel.Input<Options>);
60
+ static make<Options extends EmbeddingOptions = EmbeddingOptions>(input: EmbeddingModel.MakeInput<Options>): EmbeddingModel<Options>;
61
+ }
62
+ export declare namespace EmbeddingModel {
63
+ interface Input<Options extends EmbeddingOptions = EmbeddingOptions> {
64
+ readonly id: ModelID;
65
+ readonly provider: ProviderID;
66
+ readonly route: EmbeddingModelRoute<Options>;
67
+ readonly http?: HttpOptions;
68
+ readonly providerOptions?: ProviderOptions;
69
+ }
70
+ interface MakeInput<Options extends EmbeddingOptions = EmbeddingOptions> extends Omit<Input<Options>, "id" | "provider"> {
71
+ readonly id: string | ModelID;
72
+ readonly provider: string | ProviderID;
73
+ }
74
+ }
75
+ export declare const EmbeddingModelSchema: Schema.declare<EmbeddingModel<EmbeddingOptions>, EmbeddingModel<EmbeddingOptions>>;
76
+ export type EmbeddingModelOptions<Model> = Model extends EmbeddingModel<infer Options> ? Options : never;
77
+ /** A normalized embedding request, the plain object `ai.embedding.request(...)` returns. */
78
+ export interface EmbeddingRequest<Model extends EmbeddingModel = EmbeddingModel> extends BaseRequest<Model, EmbeddingModelOptions<Model>> {
79
+ readonly values: ReadonlyArray<EmbeddingValue>;
80
+ /** Requested vector length, for models that can shorten their output. */
81
+ readonly dimensions?: number;
82
+ readonly inputType?: EmbeddingInputType;
83
+ }
84
+ /** Input accepted by `ai.embedding.request` and `generate`. An `EmbeddingRequest` is also a valid input. */
85
+ export interface EmbeddingRequestInput<Model extends EmbeddingModel = EmbeddingModel> extends BaseRequest<Model, NoInfer<EmbeddingModelOptions<Model>>> {
86
+ readonly values: ReadonlyArray<EmbeddingValueInput>;
87
+ readonly dimensions?: number;
88
+ readonly inputType?: EmbeddingInputType;
89
+ }
90
+ declare const EmbeddingUsage_base: Schema.Class<EmbeddingUsage, Schema.Struct<{
91
+ readonly inputTokens: Schema.optional<Schema.Number>;
92
+ }>, {}>;
93
+ /** What embedding hosts report; their raw usage stays in the response's `providerMetadata`. */
94
+ export declare class EmbeddingUsage extends EmbeddingUsage_base {
95
+ }
96
+ declare const EmbeddingResponse_base: Schema.Class<EmbeddingResponse, Schema.Struct<{
97
+ /** One vector per value, in value order. */
98
+ readonly embeddings: Schema.$Array<Schema.$Array<Schema.Number>>;
99
+ readonly usage: Schema.optional<typeof EmbeddingUsage>;
100
+ readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
101
+ }>, {}>;
102
+ export declare class EmbeddingResponse extends EmbeddingResponse_base {
103
+ }
104
+ /** Normalize embedding request input into a plain `EmbeddingRequest`; non-string values become `Media.Asset`s. */
105
+ export declare const request: <const Model extends EmbeddingModel>(input: EmbeddingRequestInput<Model>) => EmbeddingRequest<Model>;
106
+ export declare function generate<const Model extends EmbeddingModel>(input: EmbeddingRequestInput<Model>): Effect.Effect<EmbeddingResponse, AIError, Service>;
107
+ export declare const Embedding: {
108
+ readonly request: typeof request;
109
+ readonly generate: typeof generate;
110
+ };
111
+ export {};
@@ -0,0 +1,75 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EmbeddingClient, Service } from "./embedding-client.js";
3
+ import { Media } from "./media.js";
4
+ import { tryRequest } from "./media-model.js";
5
+ import { ModelID, ProviderID, ProviderMetadata, ProviderOptions, } from "./schema/index.js";
6
+ // ---------------------------------------------------------------------------
7
+ // Input
8
+ // ---------------------------------------------------------------------------
9
+ /** One value to embed: text, or a media asset for hosts that embed images, audio or documents. */
10
+ export const EmbeddingValue = Schema.Union([Schema.String, Media.AssetSchema]);
11
+ export class EmbeddingModel {
12
+ id;
13
+ provider;
14
+ route;
15
+ http;
16
+ /** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
17
+ providerOptions;
18
+ constructor(input) {
19
+ this.id = input.id;
20
+ this.provider = input.provider;
21
+ this.route = input.route;
22
+ this.http = input.http;
23
+ this.providerOptions = input.providerOptions;
24
+ }
25
+ static make(input) {
26
+ return new EmbeddingModel({
27
+ ...input,
28
+ id: ModelID.make(input.id),
29
+ provider: ProviderID.make(input.provider),
30
+ });
31
+ }
32
+ }
33
+ export const EmbeddingModelSchema = Schema.declare((value) => value instanceof EmbeddingModel, { expected: "Embedding.Model" });
34
+ // ---------------------------------------------------------------------------
35
+ // Request and response
36
+ // ---------------------------------------------------------------------------
37
+ const EmbeddingRequestSchema = Schema.Struct({
38
+ model: EmbeddingModelSchema,
39
+ values: Schema.Array(EmbeddingValue).pipe(Schema.refine((x) => x.length > 0, { message: "Embedding values must not be empty" })),
40
+ dimensions: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
41
+ inputType: Schema.optional(Schema.Literals(["query", "document"])),
42
+ providerOptions: Schema.optional(ProviderOptions),
43
+ });
44
+ /** What embedding hosts report; their raw usage stays in the response's `providerMetadata`. */
45
+ export class EmbeddingUsage extends Schema.Class("Embedding.Usage")({
46
+ inputTokens: Schema.optional(Schema.Number),
47
+ }) {
48
+ }
49
+ export class EmbeddingResponse extends Schema.Class("Embedding.Response")({
50
+ /** One vector per value, in value order. */
51
+ embeddings: Schema.Array(Schema.Array(Schema.Number)),
52
+ usage: Schema.optional(EmbeddingUsage),
53
+ providerMetadata: Schema.optional(ProviderMetadata),
54
+ }) {
55
+ }
56
+ // ---------------------------------------------------------------------------
57
+ // Call API
58
+ // ---------------------------------------------------------------------------
59
+ /** Normalize embedding request input into a plain `EmbeddingRequest`; non-string values become `Media.Asset`s. */
60
+ export const request = (input) => ({
61
+ ...input,
62
+ values: input.values.map((value) => (typeof value === "string" ? value : Media.make(value))),
63
+ });
64
+ const validate = Schema.decodeUnknownSync(EmbeddingRequestSchema);
65
+ export function generate(input) {
66
+ return tryRequest(() => {
67
+ const normalized = request(input);
68
+ validate(normalized);
69
+ return normalized;
70
+ }).pipe(Effect.flatMap(EmbeddingClient.generate));
71
+ }
72
+ export const Embedding = {
73
+ request,
74
+ generate,
75
+ };
package/dist/image.d.ts CHANGED
@@ -93,7 +93,6 @@ declare const ImageResponse_base: Schema.Class<ImageResponse, Schema.Struct<{
93
93
  readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
94
94
  }>, {}>;
95
95
  export declare class ImageResponse extends ImageResponse_base {
96
- get image(): Media.Asset;
97
96
  }
98
97
  /** The `index`-th lower-fidelity preview of an image still generating; the `image` event supersedes it. */
99
98
  export declare const ImagePartialEvent: Schema.Struct<{
package/dist/image.js CHANGED
@@ -37,9 +37,6 @@ export class ImageResponse extends Schema.Class("Image.Response")({
37
37
  usage: Schema.optional(MediaUsage),
38
38
  providerMetadata: Schema.optional(ProviderMetadata),
39
39
  }) {
40
- get image() {
41
- return this.images[0];
42
- }
43
40
  }
44
41
  /** The `index`-th lower-fidelity preview of an image still generating; the `image` event supersedes it. */
45
42
  export const ImagePartialEvent = Schema.Struct({
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Effect, Layer, Schema } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
3
  import { type DecisionModel, type DecisionQuestions, type DecisionRequestInput } from "./decision.js";
4
+ import { type EmbeddingModel, type EmbeddingRequestInput } from "./embedding.js";
4
5
  import type { AwaitOptions, Event, Snapshot } from "./generation.js";
5
6
  import { type ImageModel, type ImageRequest, type ImageRequestInput } from "./image.js";
6
7
  import { LLM } from "./llm.js";
@@ -15,8 +16,8 @@ import type { NoExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolOptio
15
16
  import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js";
16
17
  /**
17
18
  * Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
18
- * transcription and decision clients over a request executor; every method runs the corresponding Effect API and rethrows
19
- * `AIError` unchanged. `file` and `write` load `node:fs/promises` on first use, so importing this module does not.
19
+ * transcription, decision and embedding clients over a request executor; every method runs the corresponding Effect API
20
+ * and rethrows `AIError` unchanged. `file` and `write` load `node:fs/promises` on first use, so importing this module does not.
20
21
  */
21
22
  export interface Options {
22
23
  /** Executor layer; defaults to `RequestExecutor.fetchLayer`. Inject a recorder or `RequestExecutor.middleware(fn)` here. */
@@ -136,6 +137,10 @@ export declare const make: (options?: Options) => {
136
137
  request: typeof import("./decision.js").request;
137
138
  generate: <const Model extends DecisionModel, const Questions extends DecisionQuestions>(input: DecisionRequestInput<Model, Questions>, options?: RunOptions) => Promise<import("./decision.js").DecisionResponseFor<Questions>>;
138
139
  };
140
+ embedding: {
141
+ request: typeof import("./embedding.js").request;
142
+ generate: <const Model extends EmbeddingModel>(input: EmbeddingRequestInput<Model>, options?: RunOptions) => Promise<import("./embedding.js").EmbeddingResponse>;
143
+ };
139
144
  /** Experimental: may change without compatibility guarantees. */
140
145
  experimental: {
141
146
  speech: {
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
3
  import { Decision } from "./decision.js";
4
+ import { Embedding } from "./embedding.js";
4
5
  import { Image } from "./image.js";
5
6
  import { LLM } from "./llm.js";
6
7
  import { Media } from "./media.js";
@@ -103,6 +104,10 @@ export const make = (options = {}) => {
103
104
  request: Decision.request,
104
105
  generate: (input, options) => run(Decision.generate(input), options),
105
106
  },
107
+ embedding: {
108
+ request: Embedding.request,
109
+ generate: (input, options) => run(Embedding.generate(input), options),
110
+ },
106
111
  /** Experimental: may change without compatibility guarantees. */
107
112
  experimental: {
108
113
  speech: {
@@ -0,0 +1,34 @@
1
+ import { EmbeddingRoute } from "../route/embedding.js";
2
+ import { type OpenString } from "../schema/index.js";
3
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
4
+ /** `batchEmbedContents` takes at most 100 requests. */
5
+ export declare const MAX_BATCH = 100;
6
+ export type TaskType = OpenString<"RETRIEVAL_QUERY" | "RETRIEVAL_DOCUMENT" | "SEMANTIC_SIMILARITY" | "CLASSIFICATION" | "CLUSTERING" | "QUESTION_ANSWERING" | "FACT_VERIFICATION" | "CODE_RETRIEVAL_QUERY">;
7
+ /**
8
+ * Per-value embedding fields, sent with each value. `taskType` replaces the one `inputType` maps to; Gemini Embedding 2
9
+ * ignores task types and documents task prefixes in the text instead (`task: search result | query: …`).
10
+ */
11
+ export interface OptionsInput {
12
+ readonly [key: string]: unknown;
13
+ readonly taskType?: TaskType;
14
+ readonly title?: string;
15
+ }
16
+ /** Vertex `embedContentConfig` fields; Vertex alone takes `autoTruncate`, `documentOcr` and `audioTrackExtraction`. */
17
+ export interface VertexOptionsInput extends OptionsInput {
18
+ readonly autoTruncate?: boolean;
19
+ readonly documentOcr?: boolean;
20
+ readonly audioTrackExtraction?: boolean;
21
+ }
22
+ /** Gemini API `batchEmbedContents`: one request per value, so every value gets its own vector. */
23
+ export declare const protocol: EmbeddingRoute.Protocol;
24
+ /**
25
+ * Vertex `embedContent`: one content per request, with options under `embedContentConfig`. Routes using it set
26
+ * `maxValues: 1`.
27
+ */
28
+ export declare const vertexProtocol: EmbeddingRoute.Protocol;
29
+ export declare const route: EmbeddingRoute.Route;
30
+ export declare const GoogleEmbedContent: {
31
+ readonly protocol: EmbeddingRoute.Protocol;
32
+ readonly vertexProtocol: EmbeddingRoute.Protocol;
33
+ readonly route: EmbeddingRoute.Route;
34
+ };