@providerprotocol/ai 0.0.18 → 0.0.20

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 (39) hide show
  1. package/README.md +364 -111
  2. package/dist/anthropic/index.d.ts +1 -1
  3. package/dist/anthropic/index.js +6 -6
  4. package/dist/chunk-P5IRTEM5.js +120 -0
  5. package/dist/chunk-P5IRTEM5.js.map +1 -0
  6. package/dist/{chunk-5FEAOEXV.js → chunk-U3FZWV4U.js} +53 -102
  7. package/dist/chunk-U3FZWV4U.js.map +1 -0
  8. package/dist/chunk-WAKD3OO5.js +224 -0
  9. package/dist/chunk-WAKD3OO5.js.map +1 -0
  10. package/dist/content-DEl3z_W2.d.ts +276 -0
  11. package/dist/google/index.d.ts +3 -1
  12. package/dist/google/index.js +123 -7
  13. package/dist/google/index.js.map +1 -1
  14. package/dist/http/index.d.ts +2 -2
  15. package/dist/http/index.js +4 -3
  16. package/dist/image-Dhq-Yuq4.d.ts +456 -0
  17. package/dist/index.d.ts +55 -163
  18. package/dist/index.js +81 -213
  19. package/dist/index.js.map +1 -1
  20. package/dist/ollama/index.d.ts +1 -1
  21. package/dist/ollama/index.js +6 -6
  22. package/dist/openai/index.d.ts +47 -20
  23. package/dist/openai/index.js +310 -7
  24. package/dist/openai/index.js.map +1 -1
  25. package/dist/openrouter/index.d.ts +1 -1
  26. package/dist/openrouter/index.js +6 -6
  27. package/dist/{provider-D5MO3-pS.d.ts → provider-BBMBZuGn.d.ts} +11 -11
  28. package/dist/proxy/index.d.ts +310 -86
  29. package/dist/proxy/index.js +33 -59
  30. package/dist/proxy/index.js.map +1 -1
  31. package/dist/{retry-DZ4Sqmxp.d.ts → retry-DR7YRJDz.d.ts} +1 -1
  32. package/dist/{stream-BjyVzBxV.d.ts → stream-DRHy6q1a.d.ts} +2 -275
  33. package/dist/xai/index.d.ts +29 -1
  34. package/dist/xai/index.js +119 -7
  35. package/dist/xai/index.js.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunk-5FEAOEXV.js.map +0 -1
  38. package/dist/chunk-DZQHVGNV.js +0 -71
  39. package/dist/chunk-DZQHVGNV.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,8 +1,12 @@
1
- import { M as Message, T as Turn, U as UserContent, A as AssistantContent, a as MessageType, b as MessageJSON, c as Tool, d as ToolUseStrategy, J as JSONSchema, C as ContentBlock, S as StreamResult, e as AssistantMessage, f as TokenUsage, g as StreamEvent, I as ImageSource, h as ImageBlock } from './stream-BjyVzBxV.js';
2
- export { w as AfterCallResult, l as AudioBlock, v as BeforeCallResult, B as BinaryBlock, P as EventDelta, i as JSONSchemaProperty, j as JSONSchemaPropertyType, G as MessageMetadata, H as MessageOptions, O as StreamEventType, k as TextBlock, r as ToolCall, x as ToolExecution, u as ToolMetadata, s as ToolResult, z as ToolResultMessage, y as UserMessage, V as VideoBlock, N as aggregateUsage, Z as contentBlockStart, _ as contentBlockStop, Q as createStreamResult, K as createTurn, L as emptyUsage, E as isAssistantMessage, o as isAudioBlock, q as isBinaryBlock, n as isImageBlock, m as isTextBlock, F as isToolResultMessage, D as isUserMessage, p as isVideoBlock, X as messageStart, Y as messageStop, t as text, R as textDelta, W as toolCallDelta } from './stream-BjyVzBxV.js';
3
- import { P as ProviderConfig, L as LLMProvider, E as EmbeddingInput, a as EmbeddingUsage, B as BoundEmbeddingModel, b as LLMHandler$1, c as EmbeddingHandler, I as ImageHandler, d as Provider } from './provider-D5MO3-pS.js';
4
- export { i as BoundImageModel, g as EmbeddingProvider, j as EmbeddingRequest, k as EmbeddingResponse, l as EmbeddingVector, e as ErrorCode, h as ImageProvider, K as KeyStrategy, M as Modality, f as ModelReference, R as RetryStrategy, U as UPPError } from './provider-D5MO3-pS.js';
5
- export { D as DynamicKey, E as ExponentialBackoff, L as LinearBackoff, N as NoRetry, a as RetryAfterStrategy, R as RoundRobinKeys, T as TokenBucket, W as WeightedKeys } from './retry-DZ4Sqmxp.js';
1
+ import { M as Message, T as Turn, a as MessageType, b as MessageJSON, c as Tool, d as ToolUseStrategy, J as JSONSchema, S as StreamResult, A as AssistantMessage, e as TokenUsage, f as StreamEvent } from './stream-DRHy6q1a.js';
2
+ export { l as AfterCallResult, B as BeforeCallResult, E as EventDelta, g as JSONSchemaProperty, h as JSONSchemaPropertyType, r as MessageMetadata, s as MessageOptions, w as StreamEventType, i as ToolCall, m as ToolExecution, k as ToolMetadata, j as ToolResult, n as ToolResultMessage, U as UserMessage, v as aggregateUsage, F as contentBlockStart, G as contentBlockStop, x as createStreamResult, t as createTurn, u as emptyUsage, p as isAssistantMessage, q as isToolResultMessage, o as isUserMessage, C as messageStart, D as messageStop, y as textDelta, z as toolCallDelta } from './stream-DRHy6q1a.js';
3
+ import { U as UserContent, A as AssistantContent, C as ContentBlock } from './content-DEl3z_W2.js';
4
+ export { a as AudioBlock, B as BinaryBlock, I as ImageBlock, b as ImageSource, T as TextBlock, V as VideoBlock, d as isAudioBlock, f as isBinaryBlock, c as isImageBlock, i as isTextBlock, e as isVideoBlock, t as text } from './content-DEl3z_W2.js';
5
+ import { P as ProviderConfig, L as LLMProvider, E as EmbeddingInput, a as EmbeddingUsage, B as BoundEmbeddingModel, b as LLMHandler$1, c as EmbeddingHandler, I as ImageHandler, d as Provider } from './provider-BBMBZuGn.js';
6
+ export { g as EmbeddingProvider, i as EmbeddingRequest, j as EmbeddingResponse, k as EmbeddingVector, e as ErrorCode, h as ImageProvider, K as KeyStrategy, M as Modality, f as ModelReference, R as RetryStrategy, U as UPPError } from './provider-BBMBZuGn.js';
7
+ import { I as ImageOptions, a as ImageInstance } from './image-Dhq-Yuq4.js';
8
+ export { B as BoundImageModel, G as GeneratedImage, b as Image, i as ImageCapabilities, d as ImageEditInput, k as ImageEditRequest, n as ImageHandler, c as ImageInput, o as ImageModelInput, m as ImageProviderStreamResult, j as ImageRequest, l as ImageResponse, f as ImageResult, g as ImageStreamEvent, h as ImageStreamResult, e as ImageUsage } from './image-Dhq-Yuq4.js';
9
+ export { D as DynamicKey, E as ExponentialBackoff, L as LinearBackoff, N as NoRetry, a as RetryAfterStrategy, R as RoundRobinKeys, T as TokenBucket, W as WeightedKeys } from './retry-DR7YRJDz.js';
6
10
 
7
11
  /**
8
12
  * @fileoverview Thread class for managing conversation history.
@@ -737,6 +741,43 @@ interface EmbeddingInstance<TParams = unknown> {
737
741
  */
738
742
  declare function embedding<TParams = unknown>(options: EmbeddingOptions<TParams>): EmbeddingInstance<TParams>;
739
743
 
744
+ /**
745
+ * @fileoverview Image generation instance factory for the Universal Provider Protocol.
746
+ *
747
+ * This module provides the core functionality for creating image generation instances,
748
+ * including support for text-to-image generation, streaming, and image editing.
749
+ *
750
+ * @module core/image
751
+ */
752
+
753
+ /**
754
+ * Creates an image generation instance configured with the specified options.
755
+ *
756
+ * This is the primary factory function for creating image generation instances.
757
+ * It validates provider capabilities, binds the model, and returns an instance
758
+ * with `generate`, `stream`, and `edit` methods.
759
+ *
760
+ * @typeParam TParams - Provider-specific parameter type for model configuration
761
+ * @param options - Configuration options for the image instance
762
+ * @returns A configured image instance ready for generation
763
+ * @throws {UPPError} When the provider does not support the image modality
764
+ *
765
+ * @example
766
+ * ```typescript
767
+ * import { image } from 'upp';
768
+ * import { openai } from 'upp/providers/openai';
769
+ *
770
+ * const dalle = image({
771
+ * model: openai('dall-e-3'),
772
+ * params: { size: '1024x1024', quality: 'hd' }
773
+ * });
774
+ *
775
+ * const result = await dalle.generate('A sunset over mountains');
776
+ * console.log(result.images.length);
777
+ * ```
778
+ */
779
+ declare function image<TParams = unknown>(options: ImageOptions<TParams>): ImageInstance<TParams>;
780
+
740
781
  /**
741
782
  * @fileoverview Base provider interface and factory for the Universal Provider Protocol.
742
783
  *
@@ -811,159 +852,6 @@ interface CreateProviderOptions {
811
852
  */
812
853
  declare function createProvider<TOptions = unknown>(options: CreateProviderOptions): Provider<TOptions>;
813
854
 
814
- /**
815
- * @fileoverview Image content handling for the Universal Provider Protocol.
816
- *
817
- * Provides a unified Image class for working with images across different sources
818
- * (file paths, URLs, raw bytes, base64). Supports conversion between formats and
819
- * integration with UPP message content blocks.
820
- *
821
- * @module core/image
822
- */
823
-
824
- /**
825
- * Represents an image that can be used in UPP messages.
826
- *
827
- * Images can be created from various sources (files, URLs, bytes, base64) and
828
- * converted to different formats as needed by providers. The class provides
829
- * a unified interface regardless of the underlying source type.
830
- *
831
- * @example
832
- * ```typescript
833
- * // Load from file
834
- * const fileImage = await Image.fromPath('./photo.jpg');
835
- *
836
- * // Reference by URL
837
- * const urlImage = Image.fromUrl('https://example.com/image.png');
838
- *
839
- * // From raw bytes
840
- * const bytesImage = Image.fromBytes(uint8Array, 'image/png');
841
- *
842
- * // Use in a message
843
- * const message = new UserMessage([image.toBlock()]);
844
- * ```
845
- */
846
- declare class Image {
847
- /** The underlying image source (bytes, base64, or URL) */
848
- readonly source: ImageSource;
849
- /** MIME type of the image (e.g., 'image/jpeg', 'image/png') */
850
- readonly mimeType: string;
851
- /** Image width in pixels, if known */
852
- readonly width?: number;
853
- /** Image height in pixels, if known */
854
- readonly height?: number;
855
- private constructor();
856
- /**
857
- * Whether this image has data loaded in memory.
858
- *
859
- * Returns `false` for URL-sourced images that reference external resources.
860
- * These must be fetched before their data can be accessed.
861
- */
862
- get hasData(): boolean;
863
- /**
864
- * Converts the image to a base64-encoded string.
865
- *
866
- * @returns The image data as a base64 string
867
- * @throws {Error} When the source is a URL (data must be fetched first)
868
- */
869
- toBase64(): string;
870
- /**
871
- * Converts the image to a data URL suitable for embedding in HTML or CSS.
872
- *
873
- * @returns A data URL in the format `data:{mimeType};base64,{data}`
874
- * @throws {Error} When the source is a URL (data must be fetched first)
875
- */
876
- toDataUrl(): string;
877
- /**
878
- * Gets the image data as raw bytes.
879
- *
880
- * @returns The image data as a Uint8Array
881
- * @throws {Error} When the source is a URL (data must be fetched first)
882
- */
883
- toBytes(): Uint8Array;
884
- /**
885
- * Gets the URL for URL-sourced images.
886
- *
887
- * @returns The image URL
888
- * @throws {Error} When the source is not a URL
889
- */
890
- toUrl(): string;
891
- /**
892
- * Converts this Image to an ImageBlock for use in UPP messages.
893
- *
894
- * @returns An ImageBlock that can be included in message content arrays
895
- */
896
- toBlock(): ImageBlock;
897
- /**
898
- * Creates an Image by reading a file from disk.
899
- *
900
- * The file is read into memory as bytes. MIME type is automatically
901
- * detected from the file extension.
902
- *
903
- * @param path - Path to the image file
904
- * @returns Promise resolving to an Image with the file contents
905
- *
906
- * @example
907
- * ```typescript
908
- * const image = await Image.fromPath('./photos/vacation.jpg');
909
- * ```
910
- */
911
- static fromPath(path: string): Promise<Image>;
912
- /**
913
- * Creates an Image from a URL reference.
914
- *
915
- * The URL is stored as a reference and not fetched. Providers will handle
916
- * URL-to-data conversion if needed. MIME type is detected from the URL
917
- * path if not provided.
918
- *
919
- * @param url - URL pointing to the image
920
- * @param mimeType - Optional MIME type override
921
- * @returns An Image referencing the URL
922
- *
923
- * @example
924
- * ```typescript
925
- * const image = Image.fromUrl('https://example.com/logo.png');
926
- * ```
927
- */
928
- static fromUrl(url: string, mimeType?: string): Image;
929
- /**
930
- * Creates an Image from raw byte data.
931
- *
932
- * @param data - The image data as a Uint8Array
933
- * @param mimeType - The MIME type of the image
934
- * @returns An Image containing the byte data
935
- *
936
- * @example
937
- * ```typescript
938
- * const image = Image.fromBytes(pngData, 'image/png');
939
- * ```
940
- */
941
- static fromBytes(data: Uint8Array, mimeType: string): Image;
942
- /**
943
- * Creates an Image from a base64-encoded string.
944
- *
945
- * @param base64 - The base64-encoded image data (without data URL prefix)
946
- * @param mimeType - The MIME type of the image
947
- * @returns An Image containing the base64 data
948
- *
949
- * @example
950
- * ```typescript
951
- * const image = Image.fromBase64(base64String, 'image/jpeg');
952
- * ```
953
- */
954
- static fromBase64(base64: string, mimeType: string): Image;
955
- /**
956
- * Creates an Image from an existing ImageBlock.
957
- *
958
- * Useful for converting content blocks received from providers back
959
- * into Image instances for further processing.
960
- *
961
- * @param block - An ImageBlock from message content
962
- * @returns An Image with the block's source and metadata
963
- */
964
- static fromBlock(block: ImageBlock): Image;
965
- }
966
-
967
855
  /**
968
856
  * @fileoverview Unified Provider Protocol (UPP) - A unified interface for AI model inference
969
857
  *
@@ -971,6 +859,12 @@ declare class Image {
971
859
  * Anthropic, OpenAI, Google, Ollama, OpenRouter, and xAI. The library handles provider-specific
972
860
  * transformations, streaming, tool execution, and error handling.
973
861
  *
862
+ * @module @providerprotocol/ai
863
+ * @packageDocumentation
864
+ */
865
+ /**
866
+ * LLM instance factory for creating model-bound inference functions.
867
+ *
974
868
  * @example Basic usage
975
869
  * ```typescript
976
870
  * import { llm, anthropic } from '@providerprotocol/ai';
@@ -992,11 +886,7 @@ declare class Image {
992
886
  * }
993
887
  * }
994
888
  * ```
995
- *
996
- * @module @providerprotocol/ai
997
- * @packageDocumentation
998
889
  */
999
- /** LLM instance factory for creating model-bound inference functions */
1000
890
 
1001
891
  /**
1002
892
  * UPP namespace object providing alternative import style.
@@ -1016,6 +906,8 @@ declare const ai: {
1016
906
  llm: typeof llm;
1017
907
  /** Embedding instance factory */
1018
908
  embedding: typeof embedding;
909
+ /** Image generation instance factory */
910
+ image: typeof image;
1019
911
  };
1020
912
 
1021
- export { AssistantContent, AssistantMessage, BoundEmbeddingModel, type BoundLLMModel, ContentBlock, type EmbedOptions, type Embedding, EmbeddingHandler, EmbeddingInput, type EmbeddingInstance, type EmbeddingModelInput, type EmbeddingOptions, type EmbeddingProgress, type EmbeddingResult, type EmbeddingStream, EmbeddingUsage, Image, ImageBlock, ImageHandler, ImageSource, type InferenceInput, JSONSchema, type LLMCapabilities, type LLMHandler, type LLMInstance, type LLMOptions, LLMProvider, type LLMRequest, type LLMResponse, type LLMStreamResult, Message, MessageJSON, MessageType, Provider, ProviderConfig, StreamEvent, StreamResult, Thread, type ThreadJSON, TokenUsage, Tool, ToolUseStrategy, Turn, UserContent, ai, createProvider, embedding, llm };
913
+ export { AssistantContent, AssistantMessage, BoundEmbeddingModel, type BoundLLMModel, ContentBlock, type EmbedOptions, type Embedding, EmbeddingHandler, EmbeddingInput, type EmbeddingInstance, type EmbeddingModelInput, type EmbeddingOptions, type EmbeddingProgress, type EmbeddingResult, type EmbeddingStream, EmbeddingUsage, ImageInstance, ImageOptions, type InferenceInput, JSONSchema, type LLMCapabilities, type LLMHandler, type LLMInstance, type LLMOptions, LLMProvider, type LLMRequest, type LLMResponse, type LLMStreamResult, Message, MessageJSON, MessageType, Provider, ProviderConfig, StreamEvent, StreamResult, Thread, type ThreadJSON, TokenUsage, Tool, ToolUseStrategy, Turn, UserContent, ai, createProvider, embedding, image, llm };
package/dist/index.js CHANGED
@@ -6,6 +6,9 @@ import {
6
6
  import {
7
7
  createProvider
8
8
  } from "./chunk-MSR5P65T.js";
9
+ import {
10
+ Image
11
+ } from "./chunk-WAKD3OO5.js";
9
12
  import {
10
13
  AssistantMessage,
11
14
  Message,
@@ -28,10 +31,10 @@ import {
28
31
  DynamicKey,
29
32
  RoundRobinKeys,
30
33
  WeightedKeys
31
- } from "./chunk-5FEAOEXV.js";
34
+ } from "./chunk-P5IRTEM5.js";
32
35
  import {
33
36
  UPPError
34
- } from "./chunk-DZQHVGNV.js";
37
+ } from "./chunk-U3FZWV4U.js";
35
38
 
36
39
  // src/types/stream.ts
37
40
  function createStreamResult(generator, turnPromise, abortController) {
@@ -679,223 +682,85 @@ function createChunkedStream(model, inputs, params, config, options) {
679
682
  }
680
683
 
681
684
  // src/core/image.ts
682
- var Image = class _Image {
683
- /** The underlying image source (bytes, base64, or URL) */
684
- source;
685
- /** MIME type of the image (e.g., 'image/jpeg', 'image/png') */
686
- mimeType;
687
- /** Image width in pixels, if known */
688
- width;
689
- /** Image height in pixels, if known */
690
- height;
691
- constructor(source, mimeType, width, height) {
692
- this.source = source;
693
- this.mimeType = mimeType;
694
- this.width = width;
695
- this.height = height;
696
- }
697
- /**
698
- * Whether this image has data loaded in memory.
699
- *
700
- * Returns `false` for URL-sourced images that reference external resources.
701
- * These must be fetched before their data can be accessed.
702
- */
703
- get hasData() {
704
- return this.source.type !== "url";
705
- }
706
- /**
707
- * Converts the image to a base64-encoded string.
708
- *
709
- * @returns The image data as a base64 string
710
- * @throws {Error} When the source is a URL (data must be fetched first)
711
- */
712
- toBase64() {
713
- if (this.source.type === "base64") {
714
- return this.source.data;
715
- }
716
- if (this.source.type === "bytes") {
717
- return btoa(
718
- Array.from(this.source.data).map((b) => String.fromCharCode(b)).join("")
719
- );
720
- }
721
- throw new Error("Cannot convert URL image to base64. Fetch the image first.");
722
- }
723
- /**
724
- * Converts the image to a data URL suitable for embedding in HTML or CSS.
725
- *
726
- * @returns A data URL in the format `data:{mimeType};base64,{data}`
727
- * @throws {Error} When the source is a URL (data must be fetched first)
728
- */
729
- toDataUrl() {
730
- const base64 = this.toBase64();
731
- return `data:${this.mimeType};base64,${base64}`;
732
- }
733
- /**
734
- * Gets the image data as raw bytes.
735
- *
736
- * @returns The image data as a Uint8Array
737
- * @throws {Error} When the source is a URL (data must be fetched first)
738
- */
739
- toBytes() {
740
- if (this.source.type === "bytes") {
741
- return this.source.data;
742
- }
743
- if (this.source.type === "base64") {
744
- const binaryString = atob(this.source.data);
745
- const bytes = new Uint8Array(binaryString.length);
746
- for (let i = 0; i < binaryString.length; i++) {
747
- bytes[i] = binaryString.charCodeAt(i);
748
- }
749
- return bytes;
750
- }
751
- throw new Error("Cannot get bytes from URL image. Fetch the image first.");
685
+ function image(options) {
686
+ const { model: modelRef, config = {}, params } = options;
687
+ const provider = modelRef.provider;
688
+ if (!provider.modalities.image) {
689
+ throw new UPPError(
690
+ `Provider '${provider.name}' does not support image modality`,
691
+ "INVALID_REQUEST",
692
+ provider.name,
693
+ "image"
694
+ );
752
695
  }
753
- /**
754
- * Gets the URL for URL-sourced images.
755
- *
756
- * @returns The image URL
757
- * @throws {Error} When the source is not a URL
758
- */
759
- toUrl() {
760
- if (this.source.type === "url") {
761
- return this.source.url;
696
+ const imageHandler = provider.modalities.image;
697
+ const boundModel = imageHandler.bind(modelRef.modelId);
698
+ const capabilities = boundModel.capabilities;
699
+ const instance = {
700
+ model: boundModel,
701
+ params,
702
+ capabilities,
703
+ async generate(input) {
704
+ const prompt = normalizeInput(input);
705
+ const response = await boundModel.generate({
706
+ prompt,
707
+ params,
708
+ config
709
+ });
710
+ return {
711
+ images: response.images,
712
+ metadata: response.metadata,
713
+ usage: response.usage
714
+ };
762
715
  }
763
- throw new Error("This image does not have a URL source.");
764
- }
765
- /**
766
- * Converts this Image to an ImageBlock for use in UPP messages.
767
- *
768
- * @returns An ImageBlock that can be included in message content arrays
769
- */
770
- toBlock() {
771
- return {
772
- type: "image",
773
- source: this.source,
774
- mimeType: this.mimeType,
775
- width: this.width,
776
- height: this.height
716
+ };
717
+ if (capabilities.streaming && boundModel.stream) {
718
+ const boundModelWithStream = boundModel;
719
+ instance.stream = function(input) {
720
+ const prompt = normalizeInput(input);
721
+ const abortController = new AbortController();
722
+ const providerStream = boundModelWithStream.stream({
723
+ prompt,
724
+ params,
725
+ config,
726
+ signal: abortController.signal
727
+ });
728
+ const resultPromise = providerStream.response.then((response) => ({
729
+ images: response.images,
730
+ metadata: response.metadata,
731
+ usage: response.usage
732
+ }));
733
+ return {
734
+ [Symbol.asyncIterator]: () => providerStream[Symbol.asyncIterator](),
735
+ result: resultPromise,
736
+ abort: () => abortController.abort()
737
+ };
777
738
  };
778
739
  }
779
- /**
780
- * Creates an Image by reading a file from disk.
781
- *
782
- * The file is read into memory as bytes. MIME type is automatically
783
- * detected from the file extension.
784
- *
785
- * @param path - Path to the image file
786
- * @returns Promise resolving to an Image with the file contents
787
- *
788
- * @example
789
- * ```typescript
790
- * const image = await Image.fromPath('./photos/vacation.jpg');
791
- * ```
792
- */
793
- static async fromPath(path) {
794
- const { readFile } = await import("fs/promises");
795
- const data = await readFile(path);
796
- const mimeType = detectMimeType(path);
797
- return new _Image(
798
- { type: "bytes", data: new Uint8Array(data) },
799
- mimeType
800
- );
801
- }
802
- /**
803
- * Creates an Image from a URL reference.
804
- *
805
- * The URL is stored as a reference and not fetched. Providers will handle
806
- * URL-to-data conversion if needed. MIME type is detected from the URL
807
- * path if not provided.
808
- *
809
- * @param url - URL pointing to the image
810
- * @param mimeType - Optional MIME type override
811
- * @returns An Image referencing the URL
812
- *
813
- * @example
814
- * ```typescript
815
- * const image = Image.fromUrl('https://example.com/logo.png');
816
- * ```
817
- */
818
- static fromUrl(url, mimeType) {
819
- const detected = mimeType || detectMimeTypeFromUrl(url);
820
- return new _Image({ type: "url", url }, detected);
821
- }
822
- /**
823
- * Creates an Image from raw byte data.
824
- *
825
- * @param data - The image data as a Uint8Array
826
- * @param mimeType - The MIME type of the image
827
- * @returns An Image containing the byte data
828
- *
829
- * @example
830
- * ```typescript
831
- * const image = Image.fromBytes(pngData, 'image/png');
832
- * ```
833
- */
834
- static fromBytes(data, mimeType) {
835
- return new _Image({ type: "bytes", data }, mimeType);
836
- }
837
- /**
838
- * Creates an Image from a base64-encoded string.
839
- *
840
- * @param base64 - The base64-encoded image data (without data URL prefix)
841
- * @param mimeType - The MIME type of the image
842
- * @returns An Image containing the base64 data
843
- *
844
- * @example
845
- * ```typescript
846
- * const image = Image.fromBase64(base64String, 'image/jpeg');
847
- * ```
848
- */
849
- static fromBase64(base64, mimeType) {
850
- return new _Image({ type: "base64", data: base64 }, mimeType);
851
- }
852
- /**
853
- * Creates an Image from an existing ImageBlock.
854
- *
855
- * Useful for converting content blocks received from providers back
856
- * into Image instances for further processing.
857
- *
858
- * @param block - An ImageBlock from message content
859
- * @returns An Image with the block's source and metadata
860
- */
861
- static fromBlock(block) {
862
- return new _Image(
863
- block.source,
864
- block.mimeType,
865
- block.width,
866
- block.height
867
- );
868
- }
869
- };
870
- function detectMimeType(path) {
871
- const ext = path.split(".").pop()?.toLowerCase();
872
- switch (ext) {
873
- case "jpg":
874
- case "jpeg":
875
- return "image/jpeg";
876
- case "png":
877
- return "image/png";
878
- case "gif":
879
- return "image/gif";
880
- case "webp":
881
- return "image/webp";
882
- case "svg":
883
- return "image/svg+xml";
884
- case "bmp":
885
- return "image/bmp";
886
- case "ico":
887
- return "image/x-icon";
888
- default:
889
- return "application/octet-stream";
740
+ if (capabilities.edit && boundModel.edit) {
741
+ const boundModelWithEdit = boundModel;
742
+ instance.edit = async function(input) {
743
+ const response = await boundModelWithEdit.edit({
744
+ image: input.image,
745
+ mask: input.mask,
746
+ prompt: input.prompt,
747
+ params,
748
+ config
749
+ });
750
+ return {
751
+ images: response.images,
752
+ metadata: response.metadata,
753
+ usage: response.usage
754
+ };
755
+ };
890
756
  }
757
+ return instance;
891
758
  }
892
- function detectMimeTypeFromUrl(url) {
893
- try {
894
- const pathname = new URL(url).pathname;
895
- return detectMimeType(pathname);
896
- } catch {
897
- return "application/octet-stream";
759
+ function normalizeInput(input) {
760
+ if (typeof input === "string") {
761
+ return input;
898
762
  }
763
+ return input.prompt;
899
764
  }
900
765
 
901
766
  // src/types/content.ts
@@ -1176,7 +1041,9 @@ var ai = {
1176
1041
  /** LLM instance factory */
1177
1042
  llm,
1178
1043
  /** Embedding instance factory */
1179
- embedding
1044
+ embedding,
1045
+ /** Image generation instance factory */
1046
+ image
1180
1047
  };
1181
1048
  export {
1182
1049
  AssistantMessage,
@@ -1203,6 +1070,7 @@ export {
1203
1070
  createTurn,
1204
1071
  embedding,
1205
1072
  emptyUsage,
1073
+ image,
1206
1074
  isAssistantMessage,
1207
1075
  isAudioBlock,
1208
1076
  isBinaryBlock,