@bastani/pi-ai 0.9.74-alpha.1 → 0.9.75-alpha.1

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 (81) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +3 -1
  3. package/dist/api/anthropic-messages.d.ts.map +1 -1
  4. package/dist/api/anthropic-messages.js +21 -7
  5. package/dist/api/anthropic-messages.js.map +1 -1
  6. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  7. package/dist/api/bedrock-converse-stream.js +4 -2
  8. package/dist/api/bedrock-converse-stream.js.map +1 -1
  9. package/dist/api/constrained-sampling.d.ts +0 -2
  10. package/dist/api/constrained-sampling.d.ts.map +1 -1
  11. package/dist/api/constrained-sampling.js +0 -13
  12. package/dist/api/constrained-sampling.js.map +1 -1
  13. package/dist/api/openai-completions.d.ts.map +1 -1
  14. package/dist/api/openai-completions.js +9 -5
  15. package/dist/api/openai-completions.js.map +1 -1
  16. package/dist/api/openai-images-options.d.ts +18 -5
  17. package/dist/api/openai-images-options.d.ts.map +1 -1
  18. package/dist/api/openai-images-options.js +9 -3
  19. package/dist/api/openai-images-options.js.map +1 -1
  20. package/dist/api/openai-images.d.ts.map +1 -1
  21. package/dist/api/openai-images.js +121 -19
  22. package/dist/api/openai-images.js.map +1 -1
  23. package/dist/api/openai-responses.d.ts.map +1 -1
  24. package/dist/api/openai-responses.js +10 -3
  25. package/dist/api/openai-responses.js.map +1 -1
  26. package/dist/api/strict-tool-limits.d.ts +13 -0
  27. package/dist/api/strict-tool-limits.d.ts.map +1 -0
  28. package/dist/api/strict-tool-limits.js +50 -0
  29. package/dist/api/strict-tool-limits.js.map +1 -0
  30. package/dist/auth/types.d.ts +7 -0
  31. package/dist/auth/types.d.ts.map +1 -1
  32. package/dist/auth/types.js.map +1 -1
  33. package/dist/cache-warming.d.ts +53 -0
  34. package/dist/cache-warming.d.ts.map +1 -0
  35. package/dist/cache-warming.js +82 -0
  36. package/dist/cache-warming.js.map +1 -0
  37. package/dist/image-generation-error.d.ts +10 -3
  38. package/dist/image-generation-error.d.ts.map +1 -1
  39. package/dist/image-generation-error.js +3 -2
  40. package/dist/image-generation-error.js.map +1 -1
  41. package/dist/index.d.ts +3 -1
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +3 -1
  44. package/dist/index.js.map +1 -1
  45. package/dist/models.d.ts +15 -6
  46. package/dist/models.d.ts.map +1 -1
  47. package/dist/models.js +22 -7
  48. package/dist/models.js.map +1 -1
  49. package/dist/providers/data/.manifest.json +1 -1
  50. package/dist/providers/data/amazon-bedrock.json +1 -1
  51. package/dist/providers/data/anthropic.json +1 -1
  52. package/dist/providers/data/azure.json +1 -1
  53. package/dist/providers/data/google.json +1 -1
  54. package/dist/providers/data/meta.json +1 -1
  55. package/dist/providers/data/opencode-go.json +1 -1
  56. package/dist/providers/data/opencode.json +1 -1
  57. package/dist/providers/data/openrouter.json +1 -1
  58. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  59. package/dist/providers/github-copilot-errors.d.ts +17 -5
  60. package/dist/providers/github-copilot-errors.d.ts.map +1 -1
  61. package/dist/providers/github-copilot-errors.js +55 -11
  62. package/dist/providers/github-copilot-errors.js.map +1 -1
  63. package/dist/providers/github-copilot-stream-attempt.d.ts +27 -0
  64. package/dist/providers/github-copilot-stream-attempt.d.ts.map +1 -0
  65. package/dist/providers/github-copilot-stream-attempt.js +45 -0
  66. package/dist/providers/github-copilot-stream-attempt.js.map +1 -0
  67. package/dist/providers/github-copilot.d.ts +10 -2
  68. package/dist/providers/github-copilot.d.ts.map +1 -1
  69. package/dist/providers/github-copilot.js +62 -36
  70. package/dist/providers/github-copilot.js.map +1 -1
  71. package/dist/types.d.ts +2 -0
  72. package/dist/types.d.ts.map +1 -1
  73. package/dist/types.js.map +1 -1
  74. package/dist/utils/stream-deadline.d.ts +6 -2
  75. package/dist/utils/stream-deadline.d.ts.map +1 -1
  76. package/dist/utils/stream-deadline.js +12 -3
  77. package/dist/utils/stream-deadline.js.map +1 -1
  78. package/dist/utils/version.d.ts +1 -1
  79. package/dist/utils/version.js +1 -1
  80. package/dist/utils/version.js.map +1 -1
  81. package/package.json +3 -3
@@ -2,9 +2,8 @@ import type { ImageEditParamsNonStreaming } from "openai/resources/images";
2
2
  import type { ImageApi, ImageModel, ImagesInputContent, ImagesInputImage, ImagesOptions } from "../types.ts";
3
3
  /**
4
4
  * Bounds the OpenAI Images API accepts for GPT Image 2.6 request fields. Requests outside them fail
5
- * before anything is sent. The image generation guide documents 2-64 GIF frames and the API
6
- * reference documents 2-16. A live request with 17 frames was rejected ("Use an integer from 2 to
7
- * 16", #4332), so the API reference is right and the maximum is 16.
5
+ * before anything is sent. The image generation guide and the API reference both document 2-16 GIF
6
+ * frames, and a live request with 17 frames was rejected ("Use an integer from 2 to 16", #4332).
8
7
  */
9
8
  export declare const OPENAI_IMAGES_LIMITS: {
10
9
  readonly gifFrameCount: {
@@ -21,10 +20,21 @@ export declare const OPENAI_IMAGES_LIMITS: {
21
20
  };
22
21
  readonly safetyIdentifierMaxLength: 128;
23
22
  };
23
+ /**
24
+ * The model SVG output retries with when the API answers that `svg.model` is required and the
25
+ * request carried no `svg`. OpenAI's documentation names no SVG authoring model and no default:
26
+ * the API reference says only that `svg.model` is required when SVG model selection is enabled
27
+ * for the account. `gpt-6.1-sol` is a value observed to work (#4615), not a documented default.
28
+ */
29
+ export declare const DEFAULT_SVG_AUTHOR_MODEL = "gpt-6.1-sol";
24
30
  export type OpenAIImagesOutputFormat = "png" | "jpeg" | "webp" | "svg" | "gif";
25
31
  /** The model that writes the SVG for `outputFormat: "svg"`, and its reasoning effort. */
26
32
  export interface OpenAIImagesSvgOptions {
27
- /** Required by the API when SVG model selection is enabled for the account. */
33
+ /**
34
+ * Required by the API when SVG model selection is enabled for the account, and rejected when it is
35
+ * not. Leave `svg` out to let SVG output recover: when the API answers that `svg.model` is
36
+ * required, the request is retried once with {@link DEFAULT_SVG_AUTHOR_MODEL}.
37
+ */
28
38
  model: string;
29
39
  reasoning?: {
30
40
  effort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
@@ -53,7 +63,10 @@ export interface OpenAIImagesOptions extends ImagesOptions {
53
63
  outputFormat?: OpenAIImagesOutputFormat;
54
64
  /**
55
65
  * Selects the model that authors the SVG. Needs `outputFormat: "svg"`; the API requires `svg.model`
56
- * when SVG model selection is enabled for the account and rejects the field otherwise.
66
+ * when SVG model selection is enabled for the account and rejects the field otherwise. Without
67
+ * `svg`, a request the API refuses for a missing `svg.model` is retried once with
68
+ * {@link DEFAULT_SVG_AUTHOR_MODEL}, and that retry is sent again without `svg` if the API rejects
69
+ * the field as unsupported. A `svg` you set is always sent as given and never retried or replaced.
57
70
  */
58
71
  svg?: OpenAIImagesSvgOptions;
59
72
  /** 0-100, for `jpeg` and `webp` output only. */
@@ -1 +1 @@
1
- {"version":3,"file":"openai-images-options.d.ts","sourceRoot":"","sources":["../../src/api/openai-images-options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAE3E,OAAO,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE7G;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB;aAChC,aAAa;iBAAI,GAAG,EAAE,CAAC;iBAAE,GAAG,EAAE,EAAE;;aAChC,kBAAkB;iBAAI,GAAG,EAAE,EAAE;iBAAE,GAAG,EAAE,IAAI;;aACxC,iBAAiB;iBAAI,GAAG,EAAE,CAAC;iBAAE,GAAG,EAAE,GAAG;;aACrC,yBAAyB,EAAE,GAAG;CACrB,CAAC;AAEX,MAAM,MAAM,wBAAwB,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,KAAK,CAAC;AAE/E,yFAAyF;AACzF,MAAM,WAAW,sBAAsB;IACtC,+EAA+E;IAC/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gBAAgB,EAAE,CAAC;IAC3B,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,IAAI,CAAC,EAAE,gBAAgB,CAAC;CACxB;AAED,2FAA2F;AAC3F,wBAAgB,oBAAoB,CACnC,KAAK,EAAE,UAAU,CAAC,QAAQ,CAAC,EAC3B,KAAK,EAAE,SAAS,kBAAkB,EAAE,GAClC,sBAAsB,CA+BxB"}
@@ -1,9 +1,8 @@
1
1
  import { ImageGenerationConfigError } from "../image-generation-error.js";
2
2
  /**
3
3
  * Bounds the OpenAI Images API accepts for GPT Image 2.6 request fields. Requests outside them fail
4
- * before anything is sent. The image generation guide documents 2-64 GIF frames and the API
5
- * reference documents 2-16. A live request with 17 frames was rejected ("Use an integer from 2 to
6
- * 16", #4332), so the API reference is right and the maximum is 16.
4
+ * before anything is sent. The image generation guide and the API reference both document 2-16 GIF
5
+ * frames, and a live request with 17 frames was rejected ("Use an integer from 2 to 16", #4332).
7
6
  */
8
7
  export const OPENAI_IMAGES_LIMITS = {
9
8
  gifFrameCount: { min: 2, max: 16 },
@@ -11,6 +10,13 @@ export const OPENAI_IMAGES_LIMITS = {
11
10
  outputCompression: { min: 0, max: 100 },
12
11
  safetyIdentifierMaxLength: 128,
13
12
  };
13
+ /**
14
+ * The model SVG output retries with when the API answers that `svg.model` is required and the
15
+ * request carried no `svg`. OpenAI's documentation names no SVG authoring model and no default:
16
+ * the API reference says only that `svg.model` is required when SVG model selection is enabled
17
+ * for the account. `gpt-6.1-sol` is a value observed to work (#4615), not a documented default.
18
+ */
19
+ export const DEFAULT_SVG_AUTHOR_MODEL = "gpt-6.1-sol";
14
20
  function fail(model, field, reason, detail, hint, related) {
15
21
  throw new ImageGenerationConfigError({ model: model.id, field, reason, related, detail, hint });
16
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"openai-images-options.js","sourceRoot":"","sources":["../../src/api/openai-images-options.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAoC,MAAM,8BAA8B,CA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AK,CAAC,CAAC,CAAC,EAAE,CAAC;AACvD,CAAC","sourcesContent":["import type { ImageEditParamsNonStreaming } from \"openai/resources/images\";\nimport { ImageGenerationConfigError, type ImageGenerationConfigReason } from \"../image-generation-error.ts\";\nimport type { ImageApi, ImageModel, ImagesInputContent, ImagesInputImage, ImagesOptions } from \"../types.ts\";\n\n/**\n * Bounds the OpenAI Images API accepts for GPT Image 2.6 request fields. Requests outside them fail\n * before anything is sent. The image generation guide documents 2-64 GIF frames and the API\n * reference documents 2-16. A live request with 17 frames was rejected (\"Use an integer from 2 to\n * 16\", #4332), so the API reference is right and the maximum is 16.\n */\nexport const OPENAI_IMAGES_LIMITS = {\n\tgifFrameCount: { min: 2, max: 16 },\n\tgifFrameDurationMs: { min: 20, max: 2000 },\n\toutputCompression: { min: 0, max: 100 },\n\tsafetyIdentifierMaxLength: 128,\n} as const;\n\nexport type OpenAIImagesOutputFormat = \"png\" | \"jpeg\" | \"webp\" | \"svg\" | \"gif\";\n\n/** The model that writes the SVG for `outputFormat: \"svg\"`, and its reasoning effort. */\nexport interface OpenAIImagesSvgOptions {\n\t/** Required by the API when SVG model selection is enabled for the account. */\n\tmodel: string;\n\treasoning?: { effort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" };\n}\n\n/**\n * Request options for OpenAI's Images API. Each field is sent only when set.\n *\n * Image blocks in the context go to `/images/edits`: the first image without a `role` is the base\n * image and every other image without a `role` is a reference. An image block with `role: \"markup\"`\n * is sent as the `markup` field and one with `role: \"mask\"` as the `mask` field; both apply to the\n * first image, and they cannot be combined.\n */\nexport interface OpenAIImagesOptions extends ImagesOptions {\n\t/** `auto`, a listed size, or a custom `WIDTHxHEIGHT` where the model supports one. */\n\tsize?: \"auto\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | (string & {});\n\tquality?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | \"auto\";\n\t/** Number of images to generate. SVG output requires 1. */\n\tn?: number;\n\t/** `transparent` needs a PNG or WebP output format. */\n\tbackground?: \"transparent\" | \"opaque\" | \"auto\";\n\t/**\n\t * `svg` and `gif` are generation-only and need a model that supports them (GPT Image 2.6).\n\t * `svg` returns UTF-8 XML as `image/svg+xml`; `gif` returns an animation as `image/gif`.\n\t */\n\toutputFormat?: OpenAIImagesOutputFormat;\n\t/**\n\t * Selects the model that authors the SVG. Needs `outputFormat: \"svg\"`; the API requires `svg.model`\n\t * when SVG model selection is enabled for the account and rejects the field otherwise.\n\t */\n\tsvg?: OpenAIImagesSvgOptions;\n\t/** 0-100, for `jpeg` and `webp` output only. */\n\toutputCompression?: number;\n\t/** GIF frames, an integer within {@link OPENAI_IMAGES_LIMITS}. The API defaults to 9. Needs `outputFormat: \"gif\"`. */\n\tframeCount?: number;\n\t/** Milliseconds per GIF frame, an integer within {@link OPENAI_IMAGES_LIMITS}; the API rounds to 10 ms and defaults to 200. Needs `outputFormat: \"gif\"`. */\n\tframeDurationMs?: number;\n\t/** How much the model plans before rendering. GPT Image 2.6 only; the API defaults to `high`. */\n\tcomplexity?: \"low\" | \"medium\" | \"high\";\n\tmoderation?: \"auto\" | \"low\";\n\t/** A stable, privacy-preserving end-user identifier of at most 128 characters; sent as `safety_identifier`. */\n\tsafetyIdentifier?: string;\n}\n\n/** The fields of an Images API request this provider validates. Upload fields are opaque here. */\nexport interface OpenAIImagesWireParams {\n\tmodel: string;\n\tprompt: string;\n\tsize?: string;\n\tquality?: string;\n\tn?: number;\n\tbackground?: string;\n\toutput_format?: string;\n\toutput_compression?: number;\n\tframe_count?: number;\n\tframe_duration_ms?: number;\n\tcomplexity?: string;\n\tmoderation?: string;\n\tsafety_identifier?: string;\n\tsvg?: OpenAIImagesSvgOptions;\n\tstream?: boolean;\n\tpartial_images?: number;\n\timage?: ImageEditParamsNonStreaming[\"image\"];\n\tmarkup?: object;\n\tmask?: object;\n}\n\nfunction fail(\n\tmodel: ImageModel<ImageApi>,\n\tfield: string,\n\treason: ImageGenerationConfigReason,\n\tdetail: string,\n\thint: string,\n\trelated?: string,\n): never {\n\tthrow new ImageGenerationConfigError({ model: model.id, field, reason, related, detail, hint });\n}\n\nfunction checkIntegerRange(\n\tmodel: ImageModel<ImageApi>,\n\tfield: string,\n\tvalue: number | undefined,\n\trange: { min: number; max: number },\n): void {\n\tif (value === undefined) return;\n\tif (Number.isInteger(value) && value >= range.min && value <= range.max) return;\n\tfail(\n\t\tmodel,\n\t\tfield,\n\t\t\"out-of-range\",\n\t\t`${field} must be an integer from ${range.min} to ${range.max}`,\n\t\t`Set ${field} to an integer from ${range.min} to ${range.max}.`,\n\t);\n}\n\n/**\n * Check a request against the Images API rules before it is sent, and throw an\n * {@link ImageGenerationConfigError} naming the first offending option. Runs on the request as it\n * will be sent, so it also covers a request an `onPayload` hook replaced.\n */\nexport function validateOpenAIImagesRequest(model: ImageModel<ImageApi>, params: OpenAIImagesWireParams): void {\n\tconst format = params.output_format;\n\tconst isEdit = params.image !== undefined;\n\tconst isGif = format === \"gif\";\n\tconst isSvg = format === \"svg\";\n\n\tcheckIntegerRange(model, \"frameCount\", params.frame_count, OPENAI_IMAGES_LIMITS.gifFrameCount);\n\tcheckIntegerRange(model, \"frameDurationMs\", params.frame_duration_ms, OPENAI_IMAGES_LIMITS.gifFrameDurationMs);\n\tcheckIntegerRange(model, \"outputCompression\", params.output_compression, OPENAI_IMAGES_LIMITS.outputCompression);\n\tif (\n\t\tparams.safety_identifier !== undefined &&\n\t\tparams.safety_identifier.length > OPENAI_IMAGES_LIMITS.safetyIdentifierMaxLength\n\t) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"safetyIdentifier\",\n\t\t\t\"out-of-range\",\n\t\t\t`safetyIdentifier must be at most ${OPENAI_IMAGES_LIMITS.safetyIdentifierMaxLength} characters`,\n\t\t\t\"Hash the user name or email address and send the digest.\",\n\t\t);\n\t}\n\n\tfor (const [field, value] of [\n\t\t[\"frameCount\", params.frame_count],\n\t\t[\"frameDurationMs\", params.frame_duration_ms],\n\t] as const) {\n\t\tif (value !== undefined && !isGif) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\tfield,\n\t\t\t\t\"requires-option\",\n\t\t\t\t`${field} applies to animated GIF output only`,\n\t\t\t\t'Set outputFormat to \"gif\" or remove the option.',\n\t\t\t\t\"outputFormat\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (params.svg !== undefined && !isSvg) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"svg\",\n\t\t\t\"requires-option\",\n\t\t\t\"svg applies to SVG output only\",\n\t\t\t'Set outputFormat to \"svg\" or remove the option.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif ((isGif || isSvg) && isEdit) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"outputFormat\",\n\t\t\t\"generation-only\",\n\t\t\t`${format} output is available on generations only, not on edits`,\n\t\t\t\"Remove the input images, or choose png, jpeg or webp.\",\n\t\t\t\"image\",\n\t\t);\n\t}\n\tif (isSvg && params.n !== undefined && params.n !== 1) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"n\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"svg output requires n to be 1\",\n\t\t\t\"Set n to 1 or remove it.\",\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif ((isGif || isSvg) && (params.stream === true || params.partial_images !== undefined)) {\n\t\tconst field = params.stream === true ? \"stream\" : \"partialImages\";\n\t\tfail(\n\t\t\tmodel,\n\t\t\tfield,\n\t\t\t\"conflicts-with-option\",\n\t\t\t`${format} output does not support streaming or partial images`,\n\t\t\t`Remove ${field} from the request.`,\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif (params.background === \"transparent\" && format !== undefined && format !== \"png\" && format !== \"webp\") {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"background\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"transparent backgrounds require png or webp output\",\n\t\t\t'Set outputFormat to \"png\" or \"webp\", or remove the transparent background.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif (params.output_compression !== undefined && format !== \"jpeg\" && format !== \"webp\") {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"outputCompression\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"outputCompression applies to jpeg and webp output only\",\n\t\t\t'Set outputFormat to \"jpeg\" or \"webp\", or remove outputCompression.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tconst hasBaseImage = Array.isArray(params.image) ? params.image.length > 0 : params.image != null;\n\tfor (const role of [\"markup\", \"mask\"] as const) {\n\t\tif (params[role] !== undefined && !hasBaseImage) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"requires-base-image\",\n\t\t\t\t`an image with role \"${role}\" needs a base image to apply to`,\n\t\t\t\t\"Add an image without a role before it; the first image is the base.\",\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t}\n\tif (params.markup !== undefined && params.mask !== undefined) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"markup\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"a markup image cannot be combined with a mask image\",\n\t\t\t'Remove the image with role \"markup\" or the one with role \"mask\".',\n\t\t\t\"mask\",\n\t\t);\n\t}\n\n\tconst requireFeature = (\n\t\tfield: string,\n\t\tused: boolean,\n\t\tfeature: keyof NonNullable<ImageModel<ImageApi>[\"capabilities\"]>,\n\t): void => {\n\t\tif (!used || model.capabilities?.[feature] === true) return;\n\t\tfail(\n\t\t\tmodel,\n\t\t\tfield,\n\t\t\t\"unsupported-by-model\",\n\t\t\t`${model.id} does not support ${field}`,\n\t\t\t\"Use a GPT Image 2.6 model (gpt-image-2.6-sunburst or gpt-image-2.6-flare).\",\n\t\t);\n\t};\n\trequireFeature(\"complexity\", params.complexity !== undefined, \"complexity\");\n\trequireFeature(\"outputFormat\", isGif, \"gif\");\n\trequireFeature(\"outputFormat\", isSvg, \"svg\");\n\trequireFeature(\"markup\", params.markup !== undefined, \"markup\");\n}\n\nexport interface PartitionedInputImages {\n\t/** Images without a role in order: the first is the base image and the rest are references. */\n\timages: ImagesInputImage[];\n\tmarkup?: ImagesInputImage;\n\tmask?: ImagesInputImage;\n}\n\n/** Split the image blocks of a request by role, rejecting roles the API cannot express. */\nexport function partitionInputImages(\n\tmodel: ImageModel<ImageApi>,\n\tinput: readonly ImagesInputContent[],\n): PartitionedInputImages {\n\tconst blocks = input.filter((item): item is ImagesInputImage => item.type === \"image\");\n\tconst images = blocks.filter((block) => block.role === undefined);\n\tconst markups = blocks.filter((block) => block.role === \"markup\");\n\tconst masks = blocks.filter((block) => block.role === \"mask\");\n\tfor (const [role, found] of [\n\t\t[\"markup\", markups],\n\t\t[\"mask\", masks],\n\t] as const) {\n\t\tif (found.length > 1) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"duplicate-role\",\n\t\t\t\t`at most one image can have role \"${role}\"`,\n\t\t\t\t`Keep one image with role \"${role}\".`,\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t\tif (found.length === 1 && images.length === 0) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"requires-base-image\",\n\t\t\t\t`an image with role \"${role}\" needs a base image to apply to`,\n\t\t\t\t\"Add an image without a role before it; the first image is the base.\",\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t}\n\treturn { images, markup: markups[0], mask: masks[0] };\n}\n"]}
1
+ {"version":3,"file":"openai-images-options.js","sourceRoot":"","sources":["../../src/api/openai-images-options.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,0BAA0B,EAAoC,MAAM,8BAA8B,CAAC;AAG5G;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IACnC,aAAa,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IAClC,kBAAkB,EAAE,EAAE,GAAG,EAAE,EAAE,EAA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type ImageGenerationConfigReason } from \"../image-generation-error.ts\";\nimport type { ImageApi, ImageModel, ImagesInputContent, ImagesInputImage, ImagesOptions } from \"../types.ts\";\n\n/**\n * Bounds the OpenAI Images API accepts for GPT Image 2.6 request fields. Requests outside them fail\n * before anything is sent. The image generation guide and the API reference both document 2-16 GIF\n * frames, and a live request with 17 frames was rejected (\"Use an integer from 2 to 16\", #4332).\n */\nexport const OPENAI_IMAGES_LIMITS = {\n\tgifFrameCount: { min: 2, max: 16 },\n\tgifFrameDurationMs: { min: 20, max: 2000 },\n\toutputCompression: { min: 0, max: 100 },\n\tsafetyIdentifierMaxLength: 128,\n} as const;\n\n/**\n * The model SVG output retries with when the API answers that `svg.model` is required and the\n * request carried no `svg`. OpenAI's documentation names no SVG authoring model and no default:\n * the API reference says only that `svg.model` is required when SVG model selection is enabled\n * for the account. `gpt-6.1-sol` is a value observed to work (#4615), not a documented default.\n */\nexport const DEFAULT_SVG_AUTHOR_MODEL = \"gpt-6.1-sol\";\n\nexport type OpenAIImagesOutputFormat = \"png\" | \"jpeg\" | \"webp\" | \"svg\" | \"gif\";\n\n/** The model that writes the SVG for `outputFormat: \"svg\"`, and its reasoning effort. */\nexport interface OpenAIImagesSvgOptions {\n\t/**\n\t * Required by the API when SVG model selection is enabled for the account, and rejected when it is\n\t * not. Leave `svg` out to let SVG output recover: when the API answers that `svg.model` is\n\t * required, the request is retried once with {@link DEFAULT_SVG_AUTHOR_MODEL}.\n\t */\n\tmodel: string;\n\treasoning?: { effort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" };\n}\n\n/**\n * Request options for OpenAI's Images API. Each field is sent only when set.\n *\n * Image blocks in the context go to `/images/edits`: the first image without a `role` is the base\n * image and every other image without a `role` is a reference. An image block with `role: \"markup\"`\n * is sent as the `markup` field and one with `role: \"mask\"` as the `mask` field; both apply to the\n * first image, and they cannot be combined.\n */\nexport interface OpenAIImagesOptions extends ImagesOptions {\n\t/** `auto`, a listed size, or a custom `WIDTHxHEIGHT` where the model supports one. */\n\tsize?: \"auto\" | \"1024x1024\" | \"1536x1024\" | \"1024x1536\" | (string & {});\n\tquality?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" | \"auto\";\n\t/** Number of images to generate. SVG output requires 1. */\n\tn?: number;\n\t/** `transparent` needs a PNG or WebP output format. */\n\tbackground?: \"transparent\" | \"opaque\" | \"auto\";\n\t/**\n\t * `svg` and `gif` are generation-only and need a model that supports them (GPT Image 2.6).\n\t * `svg` returns UTF-8 XML as `image/svg+xml`; `gif` returns an animation as `image/gif`.\n\t */\n\toutputFormat?: OpenAIImagesOutputFormat;\n\t/**\n\t * Selects the model that authors the SVG. Needs `outputFormat: \"svg\"`; the API requires `svg.model`\n\t * when SVG model selection is enabled for the account and rejects the field otherwise. Without\n\t * `svg`, a request the API refuses for a missing `svg.model` is retried once with\n\t * {@link DEFAULT_SVG_AUTHOR_MODEL}, and that retry is sent again without `svg` if the API rejects\n\t * the field as unsupported. A `svg` you set is always sent as given and never retried or replaced.\n\t */\n\tsvg?: OpenAIImagesSvgOptions;\n\t/** 0-100, for `jpeg` and `webp` output only. */\n\toutputCompression?: number;\n\t/** GIF frames, an integer within {@link OPENAI_IMAGES_LIMITS}. The API defaults to 9. Needs `outputFormat: \"gif\"`. */\n\tframeCount?: number;\n\t/** Milliseconds per GIF frame, an integer within {@link OPENAI_IMAGES_LIMITS}; the API rounds to 10 ms and defaults to 200. Needs `outputFormat: \"gif\"`. */\n\tframeDurationMs?: number;\n\t/** How much the model plans before rendering. GPT Image 2.6 only; the API defaults to `high`. */\n\tcomplexity?: \"low\" | \"medium\" | \"high\";\n\tmoderation?: \"auto\" | \"low\";\n\t/** A stable, privacy-preserving end-user identifier of at most 128 characters; sent as `safety_identifier`. */\n\tsafetyIdentifier?: string;\n}\n\n/** The fields of an Images API request this provider validates. Upload fields are opaque here. */\nexport interface OpenAIImagesWireParams {\n\tmodel: string;\n\tprompt: string;\n\tsize?: string;\n\tquality?: string;\n\tn?: number;\n\tbackground?: string;\n\toutput_format?: string;\n\toutput_compression?: number;\n\tframe_count?: number;\n\tframe_duration_ms?: number;\n\tcomplexity?: string;\n\tmoderation?: string;\n\tsafety_identifier?: string;\n\tsvg?: OpenAIImagesSvgOptions;\n\tstream?: boolean;\n\tpartial_images?: number;\n\timage?: ImageEditParamsNonStreaming[\"image\"];\n\tmarkup?: object;\n\tmask?: object;\n}\n\nfunction fail(\n\tmodel: ImageModel<ImageApi>,\n\tfield: string,\n\treason: ImageGenerationConfigReason,\n\tdetail: string,\n\thint: string,\n\trelated?: string,\n): never {\n\tthrow new ImageGenerationConfigError({ model: model.id, field, reason, related, detail, hint });\n}\n\nfunction checkIntegerRange(\n\tmodel: ImageModel<ImageApi>,\n\tfield: string,\n\tvalue: number | undefined,\n\trange: { min: number; max: number },\n): void {\n\tif (value === undefined) return;\n\tif (Number.isInteger(value) && value >= range.min && value <= range.max) return;\n\tfail(\n\t\tmodel,\n\t\tfield,\n\t\t\"out-of-range\",\n\t\t`${field} must be an integer from ${range.min} to ${range.max}`,\n\t\t`Set ${field} to an integer from ${range.min} to ${range.max}.`,\n\t);\n}\n\n/**\n * Check a request against the Images API rules before it is sent, and throw an\n * {@link ImageGenerationConfigError} naming the first offending option. Runs on the request as it\n * will be sent, so it also covers a request an `onPayload` hook replaced.\n */\nexport function validateOpenAIImagesRequest(model: ImageModel<ImageApi>, params: OpenAIImagesWireParams): void {\n\tconst format = params.output_format;\n\tconst isEdit = params.image !== undefined;\n\tconst isGif = format === \"gif\";\n\tconst isSvg = format === \"svg\";\n\n\tcheckIntegerRange(model, \"frameCount\", params.frame_count, OPENAI_IMAGES_LIMITS.gifFrameCount);\n\tcheckIntegerRange(model, \"frameDurationMs\", params.frame_duration_ms, OPENAI_IMAGES_LIMITS.gifFrameDurationMs);\n\tcheckIntegerRange(model, \"outputCompression\", params.output_compression, OPENAI_IMAGES_LIMITS.outputCompression);\n\tif (\n\t\tparams.safety_identifier !== undefined &&\n\t\tparams.safety_identifier.length > OPENAI_IMAGES_LIMITS.safetyIdentifierMaxLength\n\t) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"safetyIdentifier\",\n\t\t\t\"out-of-range\",\n\t\t\t`safetyIdentifier must be at most ${OPENAI_IMAGES_LIMITS.safetyIdentifierMaxLength} characters`,\n\t\t\t\"Hash the user name or email address and send the digest.\",\n\t\t);\n\t}\n\n\tfor (const [field, value] of [\n\t\t[\"frameCount\", params.frame_count],\n\t\t[\"frameDurationMs\", params.frame_duration_ms],\n\t] as const) {\n\t\tif (value !== undefined && !isGif) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\tfield,\n\t\t\t\t\"requires-option\",\n\t\t\t\t`${field} applies to animated GIF output only`,\n\t\t\t\t'Set outputFormat to \"gif\" or remove the option.',\n\t\t\t\t\"outputFormat\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (params.svg !== undefined && !isSvg) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"svg\",\n\t\t\t\"requires-option\",\n\t\t\t\"svg applies to SVG output only\",\n\t\t\t'Set outputFormat to \"svg\" or remove the option.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif ((isGif || isSvg) && isEdit) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"outputFormat\",\n\t\t\t\"generation-only\",\n\t\t\t`${format} output is available on generations only, not on edits`,\n\t\t\t\"Remove the input images, or choose png, jpeg or webp.\",\n\t\t\t\"image\",\n\t\t);\n\t}\n\tif (isSvg && params.n !== undefined && params.n !== 1) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"n\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"svg output requires n to be 1\",\n\t\t\t\"Set n to 1 or remove it.\",\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif ((isGif || isSvg) && (params.stream === true || params.partial_images !== undefined)) {\n\t\tconst field = params.stream === true ? \"stream\" : \"partialImages\";\n\t\tfail(\n\t\t\tmodel,\n\t\t\tfield,\n\t\t\t\"conflicts-with-option\",\n\t\t\t`${format} output does not support streaming or partial images`,\n\t\t\t`Remove ${field} from the request.`,\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif (params.background === \"transparent\" && format !== undefined && format !== \"png\" && format !== \"webp\") {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"background\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"transparent backgrounds require png or webp output\",\n\t\t\t'Set outputFormat to \"png\" or \"webp\", or remove the transparent background.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tif (params.output_compression !== undefined && format !== \"jpeg\" && format !== \"webp\") {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"outputCompression\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"outputCompression applies to jpeg and webp output only\",\n\t\t\t'Set outputFormat to \"jpeg\" or \"webp\", or remove outputCompression.',\n\t\t\t\"outputFormat\",\n\t\t);\n\t}\n\tconst hasBaseImage = Array.isArray(params.image) ? params.image.length > 0 : params.image != null;\n\tfor (const role of [\"markup\", \"mask\"] as const) {\n\t\tif (params[role] !== undefined && !hasBaseImage) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"requires-base-image\",\n\t\t\t\t`an image with role \"${role}\" needs a base image to apply to`,\n\t\t\t\t\"Add an image without a role before it; the first image is the base.\",\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t}\n\tif (params.markup !== undefined && params.mask !== undefined) {\n\t\tfail(\n\t\t\tmodel,\n\t\t\t\"markup\",\n\t\t\t\"conflicts-with-option\",\n\t\t\t\"a markup image cannot be combined with a mask image\",\n\t\t\t'Remove the image with role \"markup\" or the one with role \"mask\".',\n\t\t\t\"mask\",\n\t\t);\n\t}\n\n\tconst requireFeature = (\n\t\tfield: string,\n\t\tused: boolean,\n\t\tfeature: keyof NonNullable<ImageModel<ImageApi>[\"capabilities\"]>,\n\t): void => {\n\t\tif (!used || model.capabilities?.[feature] === true) return;\n\t\tfail(\n\t\t\tmodel,\n\t\t\tfield,\n\t\t\t\"unsupported-by-model\",\n\t\t\t`${model.id} does not support ${field}`,\n\t\t\t\"Use a GPT Image 2.6 model (gpt-image-2.6-sunburst or gpt-image-2.6-flare).\",\n\t\t);\n\t};\n\trequireFeature(\"complexity\", params.complexity !== undefined, \"complexity\");\n\trequireFeature(\"outputFormat\", isGif, \"gif\");\n\trequireFeature(\"outputFormat\", isSvg, \"svg\");\n\trequireFeature(\"markup\", params.markup !== undefined, \"markup\");\n}\n\nexport interface PartitionedInputImages {\n\t/** Images without a role in order: the first is the base image and the rest are references. */\n\timages: ImagesInputImage[];\n\tmarkup?: ImagesInputImage;\n\tmask?: ImagesInputImage;\n}\n\n/** Split the image blocks of a request by role, rejecting roles the API cannot express. */\nexport function partitionInputImages(\n\tmodel: ImageModel<ImageApi>,\n\tinput: readonly ImagesInputContent[],\n): PartitionedInputImages {\n\tconst blocks = input.filter((item): item is ImagesInputImage => item.type === \"image\");\n\tconst images = blocks.filter((block) => block.role === undefined);\n\tconst markups = blocks.filter((block) => block.role === \"markup\");\n\tconst masks = blocks.filter((block) => block.role === \"mask\");\n\tfor (const [role, found] of [\n\t\t[\"markup\", markups],\n\t\t[\"mask\", masks],\n\t] as const) {\n\t\tif (found.length > 1) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"duplicate-role\",\n\t\t\t\t`at most one image can have role \"${role}\"`,\n\t\t\t\t`Keep one image with role \"${role}\".`,\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t\tif (found.length === 1 && images.length === 0) {\n\t\t\tfail(\n\t\t\t\tmodel,\n\t\t\t\t\"input\",\n\t\t\t\t\"requires-base-image\",\n\t\t\t\t`an image with role \"${role}\" needs a base image to apply to`,\n\t\t\t\t\"Add an image without a role before it; the first image is the base.\",\n\t\t\t\trole,\n\t\t\t);\n\t\t}\n\t}\n\treturn { images, markup: markups[0], mask: masks[0] };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-images.d.ts","sourceRoot":"","sources":["../../src/api/openai-images.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAMX,cAAc,EAGd,MAAM,aAAa,CAAC;AAKrB,OAAO,EACN,KAAK,mBAAmB,EAIxB,MAAM,4BAA4B,CAAC;AAEpC,YAAY,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AA4BxH;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,cAAc,CAAC,mBAAmB,CAkE9D,CAAC"}
1
+ {"version":3,"file":"openai-images.d.ts","sourceRoot":"","sources":["../../src/api/openai-images.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAMX,cAAc,EAGd,MAAM,aAAa,CAAC;AAKrB,OAAO,EAEN,KAAK,mBAAmB,EAIxB,MAAM,4BAA4B,CAAC;AAEpC,YAAY,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AA4BxH;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,cAAc,CAAC,mBAAmB,CAgF9D,CAAC"}
@@ -1,11 +1,11 @@
1
1
  import OpenAI, { APIConnectionError, APIConnectionTimeoutError, APIError, APIUserAbortError, toFile, } from "openai";
2
- import { findImageGenerationError, ImageGenerationApiError, ImageGenerationQuotaError, ImageGenerationRateLimitError, ImageGenerationServerError, ImageGenerationTimeoutError, ImageGenerationUserError, ImageModerationBlockedError, } from "../image-generation-error.js";
2
+ import { findImageGenerationError, ImageGenerationApiError, ImageGenerationConfigError, ImageGenerationQuotaError, ImageGenerationRateLimitError, ImageGenerationServerError, ImageGenerationTimeoutError, ImageGenerationUserError, ImageModerationBlockedError, isImageGenerationConfigError, } from "../image-generation-error.js";
3
3
  import { calculateCost } from "../models.js";
4
4
  import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
5
5
  import { headersToRecord, providerHeadersToRecord } from "../utils/headers.js";
6
6
  import { retryProviderRequest } from "../utils/provider-retry.js";
7
7
  import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
8
- import { partitionInputImages, validateOpenAIImagesRequest, } from "./openai-images-options.js";
8
+ import { DEFAULT_SVG_AUTHOR_MODEL, partitionInputImages, validateOpenAIImagesRequest, } from "./openai-images-options.js";
9
9
  const OUTPUT_FORMAT_MIME_TYPES = {
10
10
  png: "image/png",
11
11
  jpeg: "image/jpeg",
@@ -42,7 +42,11 @@ export const generateImages = async (model, context, options) => {
42
42
  stopReason: "stop",
43
43
  timestamp: Date.now(),
44
44
  };
45
- const startedAt = Date.now();
45
+ const state = {
46
+ modelId: model.id,
47
+ timeoutMs: options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
48
+ startedAt: Date.now(),
49
+ };
46
50
  try {
47
51
  if (!options?.apiKey) {
48
52
  throw new Error(`No API key for provider: ${model.provider}`);
@@ -56,22 +60,30 @@ export const generateImages = async (model, context, options) => {
56
60
  validateOpenAIImagesRequest(model, params);
57
61
  const requestOptions = {
58
62
  ...(options?.signal ? { signal: options.signal } : {}),
59
- ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
63
+ timeout: state.timeoutMs,
60
64
  maxRetries: 0,
61
65
  };
62
- const { data: response, response: rawResponse } = await retryProviderRequest(() => params.image !== undefined
63
- ? client.images.edit(params, requestOptions).withResponse()
64
- : client.images.generate(params, requestOptions).withResponse(), {
65
- maxRetries: options?.maxRetries,
66
- maxRetryDelayMs: options?.maxRetryDelayMs,
67
- signal: options?.signal,
68
- noRetry: (error) => classifyImageApiError(error)?.retryable === false,
69
- });
66
+ const send = async (body, svgModelDefaulted) => {
67
+ state.svgModelDefaulted = svgModelDefaulted;
68
+ const { data, response } = await retryProviderRequest(() => body.image !== undefined
69
+ ? client.images.edit(body, requestOptions).withResponse()
70
+ : client.images.generate(body, requestOptions).withResponse(), {
71
+ maxRetries: options.maxRetries,
72
+ maxRetryDelayMs: options.maxRetryDelayMs,
73
+ signal: options.signal,
74
+ noRetry: (error) => classifyImageApiError(error, state)?.retryable === false,
75
+ });
76
+ return { params: body, data, response };
77
+ };
78
+ const { params: sentParams, data: response, response: rawResponse, } = await sendWithSvgRecovery(send, params, state, options.signal);
70
79
  await options?.onResponse?.({ status: rawResponse.status, headers: headersToRecord(rawResponse.headers) }, model);
71
80
  if (response.usage) {
72
81
  output.usage = parseUsage(response.usage, model);
73
82
  }
74
- const mimeType = OUTPUT_FORMAT_MIME_TYPES[response.output_format ?? params.output_format ?? "png"] ?? "image/png";
83
+ const svgModel = svgAuthoringModel(response) ?? sentParams.svg?.model;
84
+ if (svgModel !== undefined)
85
+ output.svgModel = svgModel;
86
+ const mimeType = OUTPUT_FORMAT_MIME_TYPES[response.output_format ?? sentParams.output_format ?? "png"] ?? "image/png";
75
87
  for (const image of response.data ?? []) {
76
88
  if (!image.b64_json)
77
89
  continue;
@@ -84,14 +96,49 @@ export const generateImages = async (model, context, options) => {
84
96
  output.stopReason = aborted ? "aborted" : "error";
85
97
  output.errorMessage = formatProviderError(normalizeProviderError(error));
86
98
  if (!aborted) {
87
- const typed = findImageGenerationError(error) ??
88
- classifyImageApiError(error, { timeoutMs: options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, startedAt });
99
+ const typed = findImageGenerationError(error) ?? classifyImageApiError(error, state);
89
100
  if (typed)
90
101
  output.error = typed.toData();
91
102
  }
92
103
  return output;
93
104
  }
94
105
  };
106
+ /**
107
+ * Send a request, and for SVG output without a caller `svg` recover from two API answers: a
108
+ * missing `svg.model` retries once with {@link DEFAULT_SVG_AUTHOR_MODEL}, and an `svg` the API
109
+ * then rejects as unsupported retries once more without it. At most three requests are sent. An
110
+ * `svg` the caller or an `onPayload` hook set is never replaced or dropped.
111
+ */
112
+ async function sendWithSvgRecovery(send, params, state, signal) {
113
+ const recoverable = params.output_format === "svg" && params.svg === undefined;
114
+ try {
115
+ return await send(params, false);
116
+ }
117
+ catch (error) {
118
+ if (!recoverable || svgRejection(error, state) !== "required-by-api")
119
+ throw error;
120
+ }
121
+ signal?.throwIfAborted();
122
+ try {
123
+ return await send({ ...params, svg: { model: DEFAULT_SVG_AUTHOR_MODEL } }, true);
124
+ }
125
+ catch (error) {
126
+ if (svgRejection(error, state) !== "unsupported-by-api")
127
+ throw error;
128
+ }
129
+ signal?.throwIfAborted();
130
+ return send(params, false);
131
+ }
132
+ /** Why the API rejected the `svg` option, for the only failures that become a config error. */
133
+ function svgRejection(error, state) {
134
+ const typed = classifyImageApiError(error, state);
135
+ return isImageGenerationConfigError(typed) ? typed.reason : undefined;
136
+ }
137
+ /** The authoring model the API names in `svg_usage`, which the SDK's response type does not declare. */
138
+ function svgAuthoringModel(response) {
139
+ const reported = response.svg_usage?.model;
140
+ return typeof reported === "string" && reported !== "" ? reported : undefined;
141
+ }
95
142
  /** Provider types, codes, request IDs and moderation categories are short identifiers. */
96
143
  const SAFE_TOKEN = /^[A-Za-z0-9][A-Za-z0-9_./:-]{0,127}$/;
97
144
  function safeToken(value) {
@@ -120,16 +167,15 @@ function safeCause(sdkError, summary) {
120
167
  return cause;
121
168
  }
122
169
  /** Translate an OpenAI SDK failure, also when wrapped in a retry-delay error, into the typed family. */
123
- function classifyImageApiError(error, timing) {
170
+ function classifyImageApiError(error, state) {
124
171
  const cause = error instanceof Error ? error.cause : undefined;
125
172
  const sdkError = [error, cause].find((candidate) => candidate instanceof APIError);
126
173
  if (!sdkError || sdkError instanceof APIUserAbortError)
127
174
  return undefined;
128
175
  if (sdkError instanceof APIConnectionTimeoutError) {
129
- const timeoutMs = timing?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
130
176
  return new ImageGenerationTimeoutError({
131
- timeoutMs,
132
- elapsedMs: timing ? Date.now() - timing.startedAt : timeoutMs,
177
+ timeoutMs: state.timeoutMs,
178
+ elapsedMs: Date.now() - state.startedAt,
133
179
  cause: safeCause(sdkError, "no HTTP response, the request timed out"),
134
180
  });
135
181
  }
@@ -153,6 +199,9 @@ function classifyImageApiError(error, timing) {
153
199
  }
154
200
  return new ImageGenerationUserError(init);
155
201
  }
202
+ const svgFailure = classifySvgFailure(sdkError.param, status, apiCode, state, init);
203
+ if (svgFailure)
204
+ return svgFailure;
156
205
  if (apiCode === "insufficient_quota" || apiType === "insufficient_quota") {
157
206
  return new ImageGenerationQuotaError(init);
158
207
  }
@@ -162,6 +211,59 @@ function classifyImageApiError(error, timing) {
162
211
  return new ImageGenerationServerError(init);
163
212
  return new ImageGenerationApiError({ ...init, retryable: status === undefined || status === 408 || status === 409 });
164
213
  }
214
+ const SVG_FIELDS = ["svg", "svg.model"];
215
+ const SVG_REJECTION_STATUSES = [400, 404, 422];
216
+ const SVG_UNSUPPORTED_CODES = ["unsupported_parameter", "unknown_parameter"];
217
+ function isSvgField(param) {
218
+ return SVG_FIELDS.some((field) => field === param);
219
+ }
220
+ function svgRejectionReason(param, apiCode) {
221
+ if (param === "svg.model" && apiCode === "missing_required_parameter")
222
+ return "required-by-api";
223
+ if (SVG_UNSUPPORTED_CODES.includes(apiCode))
224
+ return "unsupported-by-api";
225
+ return param === "svg.model" ? "rejected-by-api" : undefined;
226
+ }
227
+ /**
228
+ * Translate the API's rejection of the `svg` option into an `invalid-option` error naming the
229
+ * field, found by the response's `param` and `code`, never by its message.
230
+ */
231
+ function classifySvgFailure(param, status, apiCode, state, init) {
232
+ if (!isSvgField(param) || !SVG_REJECTION_STATUSES.includes(status))
233
+ return undefined;
234
+ const reason = svgRejectionReason(param, apiCode);
235
+ if (reason === undefined)
236
+ return undefined;
237
+ const text = describeSvgRejection(param, reason, state);
238
+ return new ImageGenerationConfigError({
239
+ model: state.modelId,
240
+ field: param,
241
+ reason,
242
+ detail: `${text.detail} (${init.detail})`,
243
+ hint: text.hint,
244
+ cause: init.cause,
245
+ });
246
+ }
247
+ function describeSvgRejection(field, reason, state) {
248
+ if (reason === "required-by-api") {
249
+ return {
250
+ detail: "the API requires svg.model for SVG output on this account",
251
+ hint: `Set svg.model to an SVG authoring model your account can use, for example svg: { model: "${DEFAULT_SVG_AUTHOR_MODEL}" }.`,
252
+ };
253
+ }
254
+ if (reason === "unsupported-by-api") {
255
+ return {
256
+ detail: `the API does not accept ${field} on this account`,
257
+ hint: "Remove svg from the request: this account does not take an SVG authoring model.",
258
+ };
259
+ }
260
+ return {
261
+ detail: state.svgModelDefaulted
262
+ ? `the API rejected ${DEFAULT_SVG_AUTHOR_MODEL}, the default SVG authoring model the request was retried with`
263
+ : "the API rejected svg.model",
264
+ hint: "Set svg.model to an SVG authoring model your account can use.",
265
+ };
266
+ }
165
267
  function createClient(model, apiKey, optionsHeaders, fetch) {
166
268
  return new OpenAI({
167
269
  apiKey,
@@ -1 +1 @@
1
- {"version":3,"file":"openai-images.js","sourceRoot":"","sources":["../../src/api/openai-images.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EACd,kBAAkB,EAClB,yBAAyB,EACzB,QAAQ,EACR,iBAAiB,EACjB,MAAM,GAEN,MAAM,QAAQ,CAAC;AAEhB,OAAO,EACN,wBAAwB,EACxB,uBAAuB,EAEvB,yBAAyB,EACzB,6BAA6B,EAC7B,0BAA0B,EAC1B,2BAA2B,EAC3B,wBAAwB,EACxB,2BAA2B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAGN,oBAAoB,EACpB,2BAA2B,GAC3B,MAAM,4BAA4B,CAAC;AAIpC,MAAM,wBAAwB,GAA2B;IACxD,GAAG,EAAE,WAAW;I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E,CAAC;QACb,WAAW,EAAE,QAAQ,CAAC,YAAY,IAAI,KAAK,GAAG,MAAM;QACpD,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;KACpE,CAAC;IACF,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import OpenAI, {\n\tAPIConnectionError,\n\tAPIConnectionTimeoutError,\n\tAPIError,\n\tAPIUserAbortError,\n\ttoFile,\n\ttype Uploadable,\n} from \"openai\";\nimport type { ImageEditParamsNonStreaming, ImageGenerateParamsNonStreaming, ImagesResponse } from \"openai/resources\";\nimport {\n\tfindImageGenerationError,\n\tImageGenerationApiError,\n\ttype ImageGenerationError,\n\tImageGenerationQuotaError,\n\tImageGenerationRateLimitError,\n\tImageGenerationServerError,\n\tImageGenerationTimeoutError,\n\tImageGenerationUserError,\n\tImageModerationBlockedError,\n} from \"../image-generation-error.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAssistantImages,\n\tImageApi,\n\tImageContent,\n\tImageModel,\n\tImagesContext,\n\tImagesFunction,\n\tProviderHeaders,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\ttype OpenAIImagesOptions,\n\ttype OpenAIImagesWireParams,\n\tpartitionInputImages,\n\tvalidateOpenAIImagesRequest,\n} from \"./openai-images-options.ts\";\n\nexport type { OpenAIImagesOptions, OpenAIImagesOutputFormat, OpenAIImagesSvgOptions } from \"./openai-images-options.ts\";\n\nconst OUTPUT_FORMAT_MIME_TYPES: Record<string, string> = {\n\tpng: \"image/png\",\n\tjpeg: \"image/jpeg\",\n\twebp: \"image/webp\",\n\tgif: \"image/gif\",\n\tsvg: \"image/svg+xml\",\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 600_000;\n\n/** Request options and the API fields they are sent as. */\nconst OPTION_WIRE_FIELDS = [\n\t[\"size\", \"size\"],\n\t[\"quality\", \"quality\"],\n\t[\"n\", \"n\"],\n\t[\"background\", \"background\"],\n\t[\"outputFormat\", \"output_format\"],\n\t[\"svg\", \"svg\"],\n\t[\"outputCompression\", \"output_compression\"],\n\t[\"frameCount\", \"frame_count\"],\n\t[\"frameDurationMs\", \"frame_duration_ms\"],\n\t[\"complexity\", \"complexity\"],\n\t[\"moderation\", \"moderation\"],\n\t[\"safetyIdentifier\", \"safety_identifier\"],\n] as const satisfies readonly (readonly [keyof OpenAIImagesOptions, keyof OpenAIImagesWireParams])[];\n\n/**\n * Image generation over OpenAI's Images API: `/images/generations` for text-only\n * input and `/images/edits` when the context includes image blocks.\n */\nexport const generateImages: ImagesFunction<OpenAIImagesOptions> = async (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: OpenAIImagesOptions,\n) => {\n\tconst output: AssistantImages = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\toutput: [],\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tconst startedAt = Date.now();\n\n\ttry {\n\t\tif (!options?.apiKey) {\n\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t}\n\t\tconst client = createClient(model, options.apiKey, options.headers, options.fetch);\n\t\tlet params = await buildParams(model, context, options);\n\t\tvalidateOpenAIImagesRequest(model, params);\n\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\tif (nextParams !== undefined) params = nextParams as OpenAIImagesWireParams;\n\t\tvalidateOpenAIImagesRequest(model, params);\n\t\tconst requestOptions = {\n\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\tmaxRetries: 0,\n\t\t};\n\t\tconst { data: response, response: rawResponse } = await retryProviderRequest(\n\t\t\t() =>\n\t\t\t\tparams.image !== undefined\n\t\t\t\t\t? client.images.edit(params as ImageEditParamsNonStreaming, requestOptions).withResponse()\n\t\t\t\t\t: client.images.generate(params as ImageGenerateParamsNonStreaming, requestOptions).withResponse(),\n\t\t\t{\n\t\t\t\tmaxRetries: options?.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs,\n\t\t\t\tsignal: options?.signal,\n\t\t\t\tnoRetry: (error) => classifyImageApiError(error)?.retryable === false,\n\t\t\t},\n\t\t);\n\t\tawait options?.onResponse?.({ status: rawResponse.status, headers: headersToRecord(rawResponse.headers) }, model);\n\n\t\tif (response.usage) {\n\t\t\toutput.usage = parseUsage(response.usage, model);\n\t\t}\n\t\tconst mimeType = OUTPUT_FORMAT_MIME_TYPES[response.output_format ?? params.output_format ?? \"png\"] ?? \"image/png\";\n\t\tfor (const image of response.data ?? []) {\n\t\t\tif (!image.b64_json) continue;\n\t\t\toutput.output.push({ type: \"image\", mimeType, data: image.b64_json } satisfies ImageContent);\n\t\t}\n\n\t\treturn output;\n\t} catch (error) {\n\t\tconst aborted = options?.signal?.aborted === true;\n\t\toutput.stopReason = aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\tif (!aborted) {\n\t\t\tconst typed =\n\t\t\t\tfindImageGenerationError(error) ??\n\t\t\t\tclassifyImageApiError(error, { timeoutMs: options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, startedAt });\n\t\t\tif (typed) output.error = typed.toData();\n\t\t}\n\t\treturn output;\n\t}\n};\n\ninterface ImageErrorTiming {\n\ttimeoutMs: number;\n\tstartedAt: number;\n}\n\n/** Provider types, codes, request IDs and moderation categories are short identifiers. */\nconst SAFE_TOKEN = /^[A-Za-z0-9][A-Za-z0-9_./:-]{0,127}$/;\n\nfunction safeToken(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && SAFE_TOKEN.test(value) ? value : undefined;\n}\n\n/**\n * The provider's error message can quote the prompt, so typed errors carry only the HTTP status and\n * identifier-shaped fields, and a cause rebuilt from them instead of the SDK error.\n */\nfunction safeSummary(status: number | undefined, apiType?: string, apiCode?: string, requestId?: string): string {\n\treturn [\n\t\tstatus === undefined ? \"no HTTP response\" : `HTTP ${status}`,\n\t\t...(apiType ? [`type ${apiType}`] : []),\n\t\t...(apiCode ? [`code ${apiCode}`] : []),\n\t\t...(requestId ? [`request ${requestId}`] : []),\n\t].join(\", \");\n}\n\nfunction safeCause(sdkError: APIError, summary: string): Error {\n\tconst cause = new Error(summary);\n\tcause.name =\n\t\tsdkError instanceof APIConnectionTimeoutError\n\t\t\t? \"APIConnectionTimeoutError\"\n\t\t\t: sdkError instanceof APIConnectionError\n\t\t\t\t? \"APIConnectionError\"\n\t\t\t\t: \"APIError\";\n\treturn cause;\n}\n\n/** Translate an OpenAI SDK failure, also when wrapped in a retry-delay error, into the typed family. */\nfunction classifyImageApiError(error: unknown, timing?: ImageErrorTiming): ImageGenerationError | undefined {\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst sdkError = [error, cause].find((candidate): candidate is APIError => candidate instanceof APIError);\n\tif (!sdkError || sdkError instanceof APIUserAbortError) return undefined;\n\tif (sdkError instanceof APIConnectionTimeoutError) {\n\t\tconst timeoutMs = timing?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n\t\treturn new ImageGenerationTimeoutError({\n\t\t\ttimeoutMs,\n\t\t\telapsedMs: timing ? Date.now() - timing.startedAt : timeoutMs,\n\t\t\tcause: safeCause(sdkError, \"no HTTP response, the request timed out\"),\n\t\t});\n\t}\n\n\tconst status = sdkError.status;\n\tconst apiType = safeToken(sdkError.type);\n\tconst apiCode = safeToken(sdkError.code);\n\tconst requestId = safeToken(sdkError.requestID);\n\tconst detail = safeSummary(status, apiType, apiCode, requestId);\n\tconst init = { detail, status, apiCode, apiType, requestId, cause: safeCause(sdkError, detail) };\n\tif (apiType === \"image_generation_user_error\") {\n\t\tif (apiCode === \"moderation_blocked\") {\n\t\t\tconst details = (sdkError.error as ImageApiErrorBody).moderation_details;\n\t\t\tconst stage = details?.moderation_stage;\n\t\t\treturn new ImageModerationBlockedError({\n\t\t\t\t...init,\n\t\t\t\tmoderationStage: stage === \"input\" || stage === \"output\" || stage === \"unknown\" ? stage : undefined,\n\t\t\t\tcategories: Array.isArray(details?.categories)\n\t\t\t\t\t? details.categories.filter((category): category is string => safeToken(category) !== undefined)\n\t\t\t\t\t: [],\n\t\t\t});\n\t\t}\n\t\treturn new ImageGenerationUserError(init);\n\t}\n\tif (apiCode === \"insufficient_quota\" || apiType === \"insufficient_quota\") {\n\t\treturn new ImageGenerationQuotaError(init);\n\t}\n\tif (status === 429) return new ImageGenerationRateLimitError(init);\n\tif ((status ?? 0) >= 500) return new ImageGenerationServerError(init);\n\treturn new ImageGenerationApiError({ ...init, retryable: status === undefined || status === 408 || status === 409 });\n}\n\ninterface ImageApiErrorBody {\n\tmoderation_details?: { moderation_stage?: string; categories?: unknown[] };\n}\n\nfunction createClient(\n\tmodel: ImageModel<ImageApi>,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n): OpenAI {\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders: providerHeadersToRecord({ ...model.headers, ...optionsHeaders }),\n\t});\n}\n\nasync function buildParams(\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions: OpenAIImagesOptions,\n): Promise<OpenAIImagesWireParams> {\n\tconst prompt = context.input\n\t\t.flatMap((item) => (item.type === \"text\" ? [sanitizeSurrogates(item.text)] : []))\n\t\t.join(\"\\n\\n\");\n\tconst params: OpenAIImagesWireParams = {\n\t\tmodel: model.id,\n\t\tprompt,\n\t\t...Object.fromEntries(\n\t\t\tOPTION_WIRE_FIELDS.flatMap(([option, field]) =>\n\t\t\t\toptions[option] === undefined ? [] : [[field, options[option]]],\n\t\t\t),\n\t\t),\n\t};\n\n\tconst { images, markup, mask } = partitionInputImages(model, context.input);\n\tif (images.length === 0) return params;\n\treturn {\n\t\t...params,\n\t\timage: await Promise.all(images.map((image, index) => toUpload(image, `image-${index + 1}`))),\n\t\t...(markup ? { markup: await toUpload(markup, \"markup\") } : {}),\n\t\t...(mask ? { mask: await toUpload(mask, \"mask\") } : {}),\n\t};\n}\n\nfunction toUpload(image: ImageContent, name: string): Promise<Uploadable> {\n\treturn toFile(base64ToBytes(image.data), `${name}.${image.mimeType.split(\"/\")[1] ?? \"png\"}`, {\n\t\ttype: image.mimeType,\n\t});\n}\n\nfunction base64ToBytes(data: string): Uint8Array<ArrayBuffer> {\n\treturn Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nfunction parseUsage(rawUsage: ImagesResponse.Usage, model: ImageModel<ImageApi>): Usage {\n\tconst input = rawUsage.input_tokens || 0;\n\tconst output = rawUsage.output_tokens || 0;\n\tconst usage: Usage = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: rawUsage.total_tokens || input + output,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tcalculateCost(model, usage);\n\treturn usage;\n}\n"]}
1
+ {"version":3,"file":"openai-images.js","sourceRoot":"","sources":["../../src/api/openai-images.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EACd,kBAAkB,EAClB,yBAAyB,EACzB,QAAQ,EACR,iBAAiB,EACjB,MAAM,GAEN,MAAM,QAAQ,CAAC;AAEhB,OAAO,EACN,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,EAG1B,yBAAyB,EACzB,6BAA6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AC,EAAE,GAAG,IAAI,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,EAAE;QAC5F,IAAI,EAAE,KAAK,CAAC,QAAQ;KACpB,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,IAAY;IAClC,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,UAAU,CAAC,QAA8B,EAAE,KAA2B;IAC9E,MAAM,KAAK,GAAG,QAAQ,CAAC,YAAY,IAAI,CAAC,CAAC;IACzC,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,IAAI,CAAC,CAAC;IAC3C,MAAM,KAAK,GAAU;QACpB,KAAK;QACL,MAAM;QACN,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,QAAQ,CAAC,YAAY,IAAI,KAAK,GAAG,MAAM;QACpD,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;KACpE,CAAC;IACF,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["import OpenAI, {\n\tAPIConnectionError,\n\tAPIConnectionTimeoutError,\n\tAPIError,\n\tAPIUserAbortError,\n\ttoFile,\n\ttype Uploadable,\n} from \"openai\";\nimport type { ImageEditParamsNonStreaming, ImageGenerateParamsNonStreaming, ImagesResponse } from \"openai/resources\";\nimport {\n\tfindImageGenerationError,\n\tImageGenerationApiError,\n\tImageGenerationConfigError,\n\ttype ImageGenerationConfigReason,\n\ttype ImageGenerationError,\n\tImageGenerationQuotaError,\n\tImageGenerationRateLimitError,\n\tImageGenerationServerError,\n\tImageGenerationTimeoutError,\n\tImageGenerationUserError,\n\tImageModerationBlockedError,\n\tisImageGenerationConfigError,\n} from \"../image-generation-error.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tAssistantImages,\n\tImageApi,\n\tImageContent,\n\tImageModel,\n\tImagesContext,\n\tImagesFunction,\n\tProviderHeaders,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\tDEFAULT_SVG_AUTHOR_MODEL,\n\ttype OpenAIImagesOptions,\n\ttype OpenAIImagesWireParams,\n\tpartitionInputImages,\n\tvalidateOpenAIImagesRequest,\n} from \"./openai-images-options.ts\";\n\nexport type { OpenAIImagesOptions, OpenAIImagesOutputFormat, OpenAIImagesSvgOptions } from \"./openai-images-options.ts\";\n\nconst OUTPUT_FORMAT_MIME_TYPES: Record<string, string> = {\n\tpng: \"image/png\",\n\tjpeg: \"image/jpeg\",\n\twebp: \"image/webp\",\n\tgif: \"image/gif\",\n\tsvg: \"image/svg+xml\",\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 600_000;\n\n/** Request options and the API fields they are sent as. */\nconst OPTION_WIRE_FIELDS = [\n\t[\"size\", \"size\"],\n\t[\"quality\", \"quality\"],\n\t[\"n\", \"n\"],\n\t[\"background\", \"background\"],\n\t[\"outputFormat\", \"output_format\"],\n\t[\"svg\", \"svg\"],\n\t[\"outputCompression\", \"output_compression\"],\n\t[\"frameCount\", \"frame_count\"],\n\t[\"frameDurationMs\", \"frame_duration_ms\"],\n\t[\"complexity\", \"complexity\"],\n\t[\"moderation\", \"moderation\"],\n\t[\"safetyIdentifier\", \"safety_identifier\"],\n] as const satisfies readonly (readonly [keyof OpenAIImagesOptions, keyof OpenAIImagesWireParams])[];\n\n/**\n * Image generation over OpenAI's Images API: `/images/generations` for text-only\n * input and `/images/edits` when the context includes image blocks.\n */\nexport const generateImages: ImagesFunction<OpenAIImagesOptions> = async (\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions?: OpenAIImagesOptions,\n) => {\n\tconst output: AssistantImages = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\toutput: [],\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\tconst state: ImageRequestState = {\n\t\tmodelId: model.id,\n\t\ttimeoutMs: options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n\t\tstartedAt: Date.now(),\n\t};\n\n\ttry {\n\t\tif (!options?.apiKey) {\n\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t}\n\t\tconst client = createClient(model, options.apiKey, options.headers, options.fetch);\n\t\tlet params = await buildParams(model, context, options);\n\t\tvalidateOpenAIImagesRequest(model, params);\n\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\tif (nextParams !== undefined) params = nextParams as OpenAIImagesWireParams;\n\t\tvalidateOpenAIImagesRequest(model, params);\n\t\tconst requestOptions = {\n\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\ttimeout: state.timeoutMs,\n\t\t\tmaxRetries: 0,\n\t\t};\n\t\tconst send = async (body: OpenAIImagesWireParams, svgModelDefaulted: boolean): Promise<SentRequest> => {\n\t\t\tstate.svgModelDefaulted = svgModelDefaulted;\n\t\t\tconst { data, response } = await retryProviderRequest(\n\t\t\t\t() =>\n\t\t\t\t\tbody.image !== undefined\n\t\t\t\t\t\t? client.images.edit(body as ImageEditParamsNonStreaming, requestOptions).withResponse()\n\t\t\t\t\t\t: client.images.generate(body as ImageGenerateParamsNonStreaming, requestOptions).withResponse(),\n\t\t\t\t{\n\t\t\t\t\tmaxRetries: options.maxRetries,\n\t\t\t\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\tnoRetry: (error) => classifyImageApiError(error, state)?.retryable === false,\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { params: body, data, response };\n\t\t};\n\t\tconst {\n\t\t\tparams: sentParams,\n\t\t\tdata: response,\n\t\t\tresponse: rawResponse,\n\t\t} = await sendWithSvgRecovery(send, params, state, options.signal);\n\t\tawait options?.onResponse?.({ status: rawResponse.status, headers: headersToRecord(rawResponse.headers) }, model);\n\n\t\tif (response.usage) {\n\t\t\toutput.usage = parseUsage(response.usage, model);\n\t\t}\n\t\tconst svgModel = svgAuthoringModel(response) ?? sentParams.svg?.model;\n\t\tif (svgModel !== undefined) output.svgModel = svgModel;\n\t\tconst mimeType =\n\t\t\tOUTPUT_FORMAT_MIME_TYPES[response.output_format ?? sentParams.output_format ?? \"png\"] ?? \"image/png\";\n\t\tfor (const image of response.data ?? []) {\n\t\t\tif (!image.b64_json) continue;\n\t\t\toutput.output.push({ type: \"image\", mimeType, data: image.b64_json } satisfies ImageContent);\n\t\t}\n\n\t\treturn output;\n\t} catch (error) {\n\t\tconst aborted = options?.signal?.aborted === true;\n\t\toutput.stopReason = aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\tif (!aborted) {\n\t\t\tconst typed = findImageGenerationError(error) ?? classifyImageApiError(error, state);\n\t\t\tif (typed) output.error = typed.toData();\n\t\t}\n\t\treturn output;\n\t}\n};\n\n/** What classifying a failure of one `generateImages()` call needs to know about the call. */\ninterface ImageRequestState {\n\tmodelId: string;\n\ttimeoutMs: number;\n\tstartedAt: number;\n\t/** True while the request in flight carries the default `svg` that recovery added. */\n\tsvgModelDefaulted?: boolean;\n}\n\ninterface SentRequest {\n\tparams: OpenAIImagesWireParams;\n\tdata: ImagesResponse;\n\tresponse: Response;\n}\n\ntype SendImageRequest = (params: OpenAIImagesWireParams, svgModelDefaulted: boolean) => Promise<SentRequest>;\n\n/**\n * Send a request, and for SVG output without a caller `svg` recover from two API answers: a\n * missing `svg.model` retries once with {@link DEFAULT_SVG_AUTHOR_MODEL}, and an `svg` the API\n * then rejects as unsupported retries once more without it. At most three requests are sent. An\n * `svg` the caller or an `onPayload` hook set is never replaced or dropped.\n */\nasync function sendWithSvgRecovery(\n\tsend: SendImageRequest,\n\tparams: OpenAIImagesWireParams,\n\tstate: ImageRequestState,\n\tsignal: AbortSignal | undefined,\n): Promise<SentRequest> {\n\tconst recoverable = params.output_format === \"svg\" && params.svg === undefined;\n\ttry {\n\t\treturn await send(params, false);\n\t} catch (error) {\n\t\tif (!recoverable || svgRejection(error, state) !== \"required-by-api\") throw error;\n\t}\n\tsignal?.throwIfAborted();\n\ttry {\n\t\treturn await send({ ...params, svg: { model: DEFAULT_SVG_AUTHOR_MODEL } }, true);\n\t} catch (error) {\n\t\tif (svgRejection(error, state) !== \"unsupported-by-api\") throw error;\n\t}\n\tsignal?.throwIfAborted();\n\treturn send(params, false);\n}\n\n/** Why the API rejected the `svg` option, for the only failures that become a config error. */\nfunction svgRejection(error: unknown, state: ImageRequestState): ImageGenerationConfigReason | undefined {\n\tconst typed = classifyImageApiError(error, state);\n\treturn isImageGenerationConfigError(typed) ? typed.reason : undefined;\n}\n\n/** The authoring model the API names in `svg_usage`, which the SDK's response type does not declare. */\nfunction svgAuthoringModel(response: ImagesResponse): string | undefined {\n\tconst reported = (response as ImagesResponse & { svg_usage?: { model?: unknown } }).svg_usage?.model;\n\treturn typeof reported === \"string\" && reported !== \"\" ? reported : undefined;\n}\n\n/** Provider types, codes, request IDs and moderation categories are short identifiers. */\nconst SAFE_TOKEN = /^[A-Za-z0-9][A-Za-z0-9_./:-]{0,127}$/;\n\nfunction safeToken(value: unknown): string | undefined {\n\treturn typeof value === \"string\" && SAFE_TOKEN.test(value) ? value : undefined;\n}\n\n/**\n * The provider's error message can quote the prompt, so typed errors carry only the HTTP status and\n * identifier-shaped fields, and a cause rebuilt from them instead of the SDK error.\n */\nfunction safeSummary(status: number | undefined, apiType?: string, apiCode?: string, requestId?: string): string {\n\treturn [\n\t\tstatus === undefined ? \"no HTTP response\" : `HTTP ${status}`,\n\t\t...(apiType ? [`type ${apiType}`] : []),\n\t\t...(apiCode ? [`code ${apiCode}`] : []),\n\t\t...(requestId ? [`request ${requestId}`] : []),\n\t].join(\", \");\n}\n\nfunction safeCause(sdkError: APIError, summary: string): Error {\n\tconst cause = new Error(summary);\n\tcause.name =\n\t\tsdkError instanceof APIConnectionTimeoutError\n\t\t\t? \"APIConnectionTimeoutError\"\n\t\t\t: sdkError instanceof APIConnectionError\n\t\t\t\t? \"APIConnectionError\"\n\t\t\t\t: \"APIError\";\n\treturn cause;\n}\n\n/** Translate an OpenAI SDK failure, also when wrapped in a retry-delay error, into the typed family. */\nfunction classifyImageApiError(error: unknown, state: ImageRequestState): ImageGenerationError | undefined {\n\tconst cause = error instanceof Error ? error.cause : undefined;\n\tconst sdkError = [error, cause].find((candidate): candidate is APIError => candidate instanceof APIError);\n\tif (!sdkError || sdkError instanceof APIUserAbortError) return undefined;\n\tif (sdkError instanceof APIConnectionTimeoutError) {\n\t\treturn new ImageGenerationTimeoutError({\n\t\t\ttimeoutMs: state.timeoutMs,\n\t\t\telapsedMs: Date.now() - state.startedAt,\n\t\t\tcause: safeCause(sdkError, \"no HTTP response, the request timed out\"),\n\t\t});\n\t}\n\n\tconst status = sdkError.status;\n\tconst apiType = safeToken(sdkError.type);\n\tconst apiCode = safeToken(sdkError.code);\n\tconst requestId = safeToken(sdkError.requestID);\n\tconst detail = safeSummary(status, apiType, apiCode, requestId);\n\tconst init = { detail, status, apiCode, apiType, requestId, cause: safeCause(sdkError, detail) };\n\tif (apiType === \"image_generation_user_error\") {\n\t\tif (apiCode === \"moderation_blocked\") {\n\t\t\tconst details = (sdkError.error as ImageApiErrorBody).moderation_details;\n\t\t\tconst stage = details?.moderation_stage;\n\t\t\treturn new ImageModerationBlockedError({\n\t\t\t\t...init,\n\t\t\t\tmoderationStage: stage === \"input\" || stage === \"output\" || stage === \"unknown\" ? stage : undefined,\n\t\t\t\tcategories: Array.isArray(details?.categories)\n\t\t\t\t\t? details.categories.filter((category): category is string => safeToken(category) !== undefined)\n\t\t\t\t\t: [],\n\t\t\t});\n\t\t}\n\t\treturn new ImageGenerationUserError(init);\n\t}\n\tconst svgFailure = classifySvgFailure(sdkError.param, status, apiCode, state, init);\n\tif (svgFailure) return svgFailure;\n\tif (apiCode === \"insufficient_quota\" || apiType === \"insufficient_quota\") {\n\t\treturn new ImageGenerationQuotaError(init);\n\t}\n\tif (status === 429) return new ImageGenerationRateLimitError(init);\n\tif ((status ?? 0) >= 500) return new ImageGenerationServerError(init);\n\treturn new ImageGenerationApiError({ ...init, retryable: status === undefined || status === 408 || status === 409 });\n}\n\nconst SVG_FIELDS = [\"svg\", \"svg.model\"] as const;\nconst SVG_REJECTION_STATUSES: readonly (number | undefined)[] = [400, 404, 422];\nconst SVG_UNSUPPORTED_CODES: readonly (string | undefined)[] = [\"unsupported_parameter\", \"unknown_parameter\"];\n\nfunction isSvgField(param: unknown): param is (typeof SVG_FIELDS)[number] {\n\treturn SVG_FIELDS.some((field) => field === param);\n}\n\nfunction svgRejectionReason(\n\tparam: (typeof SVG_FIELDS)[number],\n\tapiCode: string | undefined,\n): ImageGenerationConfigReason | undefined {\n\tif (param === \"svg.model\" && apiCode === \"missing_required_parameter\") return \"required-by-api\";\n\tif (SVG_UNSUPPORTED_CODES.includes(apiCode)) return \"unsupported-by-api\";\n\treturn param === \"svg.model\" ? \"rejected-by-api\" : undefined;\n}\n\n/**\n * Translate the API's rejection of the `svg` option into an `invalid-option` error naming the\n * field, found by the response's `param` and `code`, never by its message.\n */\nfunction classifySvgFailure(\n\tparam: string | null | undefined,\n\tstatus: number | undefined,\n\tapiCode: string | undefined,\n\tstate: ImageRequestState,\n\tinit: { detail: string; cause: Error },\n): ImageGenerationConfigError | undefined {\n\tif (!isSvgField(param) || !SVG_REJECTION_STATUSES.includes(status)) return undefined;\n\tconst reason = svgRejectionReason(param, apiCode);\n\tif (reason === undefined) return undefined;\n\tconst text = describeSvgRejection(param, reason, state);\n\treturn new ImageGenerationConfigError({\n\t\tmodel: state.modelId,\n\t\tfield: param,\n\t\treason,\n\t\tdetail: `${text.detail} (${init.detail})`,\n\t\thint: text.hint,\n\t\tcause: init.cause,\n\t});\n}\n\nfunction describeSvgRejection(\n\tfield: string,\n\treason: ImageGenerationConfigReason,\n\tstate: ImageRequestState,\n): { detail: string; hint: string } {\n\tif (reason === \"required-by-api\") {\n\t\treturn {\n\t\t\tdetail: \"the API requires svg.model for SVG output on this account\",\n\t\t\thint: `Set svg.model to an SVG authoring model your account can use, for example svg: { model: \"${DEFAULT_SVG_AUTHOR_MODEL}\" }.`,\n\t\t};\n\t}\n\tif (reason === \"unsupported-by-api\") {\n\t\treturn {\n\t\t\tdetail: `the API does not accept ${field} on this account`,\n\t\t\thint: \"Remove svg from the request: this account does not take an SVG authoring model.\",\n\t\t};\n\t}\n\treturn {\n\t\tdetail: state.svgModelDefaulted\n\t\t\t? `the API rejected ${DEFAULT_SVG_AUTHOR_MODEL}, the default SVG authoring model the request was retried with`\n\t\t\t: \"the API rejected svg.model\",\n\t\thint: \"Set svg.model to an SVG authoring model your account can use.\",\n\t};\n}\n\ninterface ImageApiErrorBody {\n\tmoderation_details?: { moderation_stage?: string; categories?: unknown[] };\n}\n\nfunction createClient(\n\tmodel: ImageModel<ImageApi>,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n\tfetch?: typeof globalThis.fetch,\n): OpenAI {\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tfetch,\n\t\tdefaultHeaders: providerHeadersToRecord({ ...model.headers, ...optionsHeaders }),\n\t});\n}\n\nasync function buildParams(\n\tmodel: ImageModel<ImageApi>,\n\tcontext: ImagesContext,\n\toptions: OpenAIImagesOptions,\n): Promise<OpenAIImagesWireParams> {\n\tconst prompt = context.input\n\t\t.flatMap((item) => (item.type === \"text\" ? [sanitizeSurrogates(item.text)] : []))\n\t\t.join(\"\\n\\n\");\n\tconst params: OpenAIImagesWireParams = {\n\t\tmodel: model.id,\n\t\tprompt,\n\t\t...Object.fromEntries(\n\t\t\tOPTION_WIRE_FIELDS.flatMap(([option, field]) =>\n\t\t\t\toptions[option] === undefined ? [] : [[field, options[option]]],\n\t\t\t),\n\t\t),\n\t};\n\n\tconst { images, markup, mask } = partitionInputImages(model, context.input);\n\tif (images.length === 0) return params;\n\treturn {\n\t\t...params,\n\t\timage: await Promise.all(images.map((image, index) => toUpload(image, `image-${index + 1}`))),\n\t\t...(markup ? { markup: await toUpload(markup, \"markup\") } : {}),\n\t\t...(mask ? { mask: await toUpload(mask, \"mask\") } : {}),\n\t};\n}\n\nfunction toUpload(image: ImageContent, name: string): Promise<Uploadable> {\n\treturn toFile(base64ToBytes(image.data), `${name}.${image.mimeType.split(\"/\")[1] ?? \"png\"}`, {\n\t\ttype: image.mimeType,\n\t});\n}\n\nfunction base64ToBytes(data: string): Uint8Array<ArrayBuffer> {\n\treturn Uint8Array.from(atob(data), (char) => char.charCodeAt(0));\n}\n\nfunction parseUsage(rawUsage: ImagesResponse.Usage, model: ImageModel<ImageApi>): Usage {\n\tconst input = rawUsage.input_tokens || 0;\n\tconst output = rawUsage.output_tokens || 0;\n\tconst usage: Usage = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: rawUsage.total_tokens || input + output,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tcalculateCost(model, usage);\n\treturn usage;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,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AC;CAC1D;AAED;;GAEG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CAqK7E,CAAC;AAuDF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkBhF,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { clampThinkingLevel } from "../models.js";
2
2
  import { githubCopilotEmptyResponse, recordGitHubCopilotFailure } from "../providers/github-copilot-errors.js";
3
+ import { GitHubCopilotStreamAttempt } from "../providers/github-copilot-stream-attempt.js";
3
4
  import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
4
5
  import { AssistantMessageEventStream } from "../utils/event-stream.js";
5
6
  import { headersToRecord } from "../utils/headers.js";
@@ -136,6 +137,7 @@ export const stream = (model, context, options) => {
136
137
  timestamp: Date.now(),
137
138
  };
138
139
  const streamDeadline = createStreamDeadline(options?.streamDeadlineMs, options?.signal);
140
+ const streamAttempt = new GitHubCopilotStreamAttempt();
139
141
  let startEmitted = false;
140
142
  try {
141
143
  const thinkingOffFallback = options?.reasoningEffort || options?.reasoningSummary
@@ -163,7 +165,11 @@ export const stream = (model, context, options) => {
163
165
  ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
164
166
  maxRetries: 0,
165
167
  };
166
- const sendRequest = (requestParams) => retryProviderRequest(() => client.responses.create(requestParams, requestOptions).withResponse(), {
168
+ const createRequest = (requestParams) => {
169
+ streamAttempt.begin();
170
+ return client.responses.create(requestParams, requestOptions).withResponse();
171
+ };
172
+ const sendRequest = (requestParams) => retryProviderRequest(() => createRequest(requestParams), {
167
173
  maxRetries: options?.maxRetries,
168
174
  maxRetryDelayMs: options?.maxRetryDelayMs,
169
175
  signal: streamDeadline.signal,
@@ -178,7 +184,8 @@ export const stream = (model, context, options) => {
178
184
  startEmitted = true;
179
185
  stream.push({ type: "start", partial: output });
180
186
  }
181
- return readResponsePreamble(withStreamDeadline(data, streamDeadline.deadlineMs, streamDeadline.abort));
187
+ streamAttempt.respond(response.headers);
188
+ return readResponsePreamble(streamAttempt.observe(withStreamDeadline(data, streamDeadline.deadlineMs, streamDeadline.abort)));
182
189
  };
183
190
  let requestedServiceTier = resolveOpenAIRequestServiceTier(model, options?.serviceTier);
184
191
  let openaiStream;
@@ -233,7 +240,7 @@ export const stream = (model, context, options) => {
233
240
  output.errorMessage = errorMessage;
234
241
  }
235
242
  if (model.provider === "github-copilot")
236
- recordGitHubCopilotFailure(output, error, startEmitted);
243
+ recordGitHubCopilotFailure(output, error, streamAttempt.snapshot());
237
244
  stream.push({ type: "error", reason: output.stopReason, error: output });
238
245
  stream.end();
239
246
  }