Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,7 @@ durable job, so it survives process restarts and can be inspected or cancelled.

```bash
memorix media generate image --prompt "..." --json
memorix media generate image --model MiniMax-H3-Image --prompt "A small blue sailboat" --json
memorix media generate image --prompt "..." --image ./reference.png --json
memorix media generate video --prompt "..." --json
memorix media derive-pdf --asset <asset-id> --attach --json
Expand All @@ -915,7 +916,11 @@ memorix media cancel --job <media-job-id> --json
```

Set `MINIMAX_API_KEY` (or `MINIMAX_CN_API_KEY`) outside Git before using
generation. Image-to-image passes the reference image through MiniMax
generation. Select `MiniMax-H3-Image` or `MiniMax-H3-Image-Highspeed` for text-only
generation in either region. H3 requests allow at least ten minutes and are sent
once because another request can incur a second charge. Partial batches retain
the successful assets and report warnings for the failed images.
Image-to-image passes the reference image through MiniMax
`subject_reference` for the image-01/image-01-live models. `memorix_media` is
the matching single MCP tool in every profile, including `micro`. Its
import/attach/list/show/derive-pdf/derive-audio/status/cancel actions are
Expand Down
13 changes: 7 additions & 6 deletions packages/ai/scripts/generate-image-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { writeFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath, pathToFileURL } from "url";
import { MINIMAX_H3_IMAGE_MODELS, isMiniMaxH3ImageModel } from "../src/minimax-image-models.ts";
import type { ImagesApi, ImagesModel } from "../src/types.ts";

const __filename = fileURLToPath(import.meta.url);
Expand All @@ -11,8 +12,8 @@ const packageRoot = join(__dirname, "..");
const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
const MINIMAX_IMAGE_MODEL_IDS = ["image-01", "image-01-live"] as const;
const MINIMAX_IMAGE_VARIANTS = [
{ provider: "minimax", baseUrl: "https://api.minimax.io/v1/image_generation" },
{ provider: "minimax-cn", baseUrl: "https://api.minimaxi.com/v1/image_generation" },
{ provider: "minimax", baseUrl: "https://api.minimax.io/v1/image_generation", h3Url: "https://api.minimax.io/v1/images/generations" },
{ provider: "minimax-cn", baseUrl: "https://api.minimaxi.com/v1/image_generation", h3Url: "https://api.minimax.cn/v1/images/generations" },
] as const;
const MIN_GENERATED_IMAGE_MODEL_COUNT = 1;
const CATALOG_SHRINK_OVERRIDE_ENV = "MEMORIX_ALLOW_MODEL_CATALOG_SHRINK";
Expand Down Expand Up @@ -84,14 +85,14 @@ async function fetchOpenRouterImageModels(): Promise<ImagesModel<"openrouter-ima
}

function getMiniMaxImageModels(): ImagesModel<"minimax-images">[] {
return MINIMAX_IMAGE_VARIANTS.flatMap(({ provider, baseUrl }) =>
MINIMAX_IMAGE_MODEL_IDS.map((modelId) => ({
return MINIMAX_IMAGE_VARIANTS.flatMap(({ provider, baseUrl, h3Url }) =>
[...MINIMAX_IMAGE_MODEL_IDS, ...MINIMAX_H3_IMAGE_MODELS].map((modelId) => ({
id: modelId,
name: modelId,
api: "minimax-images",
provider,
baseUrl,
input: ["text", "image"],
baseUrl: isMiniMaxH3ImageModel(modelId) ? h3Url : baseUrl,
input: isMiniMaxH3ImageModel(modelId) ? ["text"] : ["text", "image"],
output: ["image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
})),
Expand Down
60 changes: 60 additions & 0 deletions packages/ai/src/image-models.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,36 @@ export const IMAGE_MODELS = {
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
"MiniMax-H3-Image": {
id: "MiniMax-H3-Image",
name: "MiniMax-H3-Image",
api: "minimax-images",
provider: "minimax",
baseUrl: "https://api.minimax.io/v1/images/generations",
input: ["text"],
output: ["image"],
cost: {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
"MiniMax-H3-Image-Highspeed": {
id: "MiniMax-H3-Image-Highspeed",
name: "MiniMax-H3-Image-Highspeed",
api: "minimax-images",
provider: "minimax",
baseUrl: "https://api.minimax.io/v1/images/generations",
input: ["text"],
output: ["image"],
cost: {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
},
Expand Down Expand Up @@ -592,6 +622,36 @@ export const IMAGE_MODELS = {
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
"MiniMax-H3-Image": {
id: "MiniMax-H3-Image",
name: "MiniMax-H3-Image",
api: "minimax-images",
provider: "minimax-cn",
baseUrl: "https://api.minimax.cn/v1/images/generations",
input: ["text"],
output: ["image"],
cost: {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
"MiniMax-H3-Image-Highspeed": {
id: "MiniMax-H3-Image-Highspeed",
name: "MiniMax-H3-Image-Highspeed",
api: "minimax-images",
provider: "minimax-cn",
baseUrl: "https://api.minimax.cn/v1/images/generations",
input: ["text"],
output: ["image"],
cost: {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
}
} satisfies ImagesModel<"minimax-images">,
},
Expand Down
1 change: 1 addition & 0 deletions packages/ai/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { Type } from "typebox";
export * from "./api-registry.ts";
export * from "./env-api-keys.ts";
export * from "./image-models.ts";
export * from "./minimax-image-models.ts";
export * from "./images.ts";
export * from "./images-api-registry.ts";
export * from "./models.ts";
Expand Down
6 changes: 6 additions & 0 deletions packages/ai/src/minimax-image-models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const MINIMAX_H3_IMAGE_MODELS = ["MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed"] as const;
export const MINIMAX_H3_IMAGE_TIMEOUT_MS = 600_000;

export function isMiniMaxH3ImageModel(id: string): boolean {
return MINIMAX_H3_IMAGE_MODELS.some(modelId => modelId === id);
}
56 changes: 56 additions & 0 deletions packages/ai/src/providers/images/minimax-h3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { request } from "node:https";
import { text } from "node:stream/consumers";
import { MINIMAX_H3_IMAGE_TIMEOUT_MS } from "../../minimax-image-models.ts";
import type { MiniMaxImagesOptions } from "./minimax.ts";

export function buildH3Payload(model: string, prompt: string, options: MiniMaxImagesOptions = {}) {
const { width, height, aspectRatio, n, seed, responseFormat, promptOptimizer } = options;
if (seed !== undefined) throw new Error("MiniMax H3 image generation does not support seed");
if (n !== undefined && (!Number.isSafeInteger(n) || n < 1 || n > 10)) {
throw new Error("MiniMax H3 image count must be an integer between 1 and 10");
}

let size: string | undefined;
if (width !== undefined || height !== undefined) {
if (!width || !height || !Number.isSafeInteger(width) || !Number.isSafeInteger(height)
|| width < 1 || height < 1 || width * height < 655360 || width * height > 20000000
|| width > 3 * height || height > 3 * width) {
throw new Error("MiniMax H3 requires both dimensions, 655360 to 20000000 pixels, and a ratio from 1:3 to 3:1");
}
if (aspectRatio !== undefined) throw new Error("MiniMax H3 accepts either explicit dimensions or an aspect ratio");
size = `${width}x${height}`;
}
if (promptOptimizer === false && !size && !aspectRatio) {
throw new Error("MiniMax H3 requires dimensions or an aspect ratio when prompt enhancement is disabled");
}
return {
model, prompt,
...(size ? { size } : {}),
...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),
...(n === undefined ? {} : { n }),
...(responseFormat ? { response_format: responseFormat === "base64" ? "b64_json" : responseFormat } : {}),
...(promptOptimizer === undefined ? {} : { disable_prompt_enhanced: !promptOptimizer }),
};
}

// Node fetch can time out waiting for headers after five minutes. A single HTTPS
// request keeps the full H3 deadline and never follows a redirect or replays the POST.
export function postH3(url: string, body: string, headers: Headers, options: MiniMaxImagesOptions):
Promise<Pick<Response, "status" | "ok" | "headers" | "text">> {
const timeoutMs = options.timeoutMs ?? MINIMAX_H3_IMAGE_TIMEOUT_MS;
if (!Number.isInteger(timeoutMs) || timeoutMs < MINIMAX_H3_IMAGE_TIMEOUT_MS || timeoutMs > 2_147_483_647) {
throw new Error("MiniMax H3 requires a timeout between 600000 and 2147483647 milliseconds");
}
const deadline = AbortSignal.timeout(timeoutMs);
const signal = options.signal ? AbortSignal.any([deadline, options.signal]) : deadline;
return new Promise((resolve, reject) => {
const req = request(url, { method: "POST", headers: Object.fromEntries(headers), agent: false, signal }, res => {
const responseHeaders = new Headers();
for (let i = 0; i < res.rawHeaders.length; i += 2) responseHeaders.append(res.rawHeaders[i], res.rawHeaders[i + 1]);
const status = res.statusCode ?? 0;
resolve({ status, ok: status >= 200 && status < 300, headers: responseHeaders, text: () => text(res) });
});
req.on("error", reject);
req.end(body);
});
}
66 changes: 46 additions & 20 deletions packages/ai/src/providers/images/minimax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type {
ImagesModel,
ImagesOptions,
} from "../../types.ts";
import { isMiniMaxH3ImageModel } from "../../minimax-image-models.ts";
import { buildH3Payload, postH3 } from "./minimax-h3.ts";
import { isIP } from "node:net";
import { headersToRecord } from "../../utils/headers.ts";
import { sanitizeSurrogates } from "../../utils/sanitize-unicode.ts";
Expand Down Expand Up @@ -57,6 +59,12 @@ interface MiniMaxImageGenerationResponse {
};
}

interface H3Response {
request_id?: string;
error?: { message?: string };
data?: Array<{ url?: string; b64_json?: string; error?: { code?: string; message?: string } }>;
}

export const generateImagesMiniMax: ImagesFunction<"minimax-images", MiniMaxImagesOptions> = async (
model: ImagesModel<"minimax-images">,
context: ImagesContext,
Expand All @@ -80,25 +88,39 @@ export const generateImagesMiniMax: ImagesFunction<"minimax-images", MiniMaxImag
throw new Error("Request was aborted");
}

let payload = buildPayload(model, context, options);
const nextPayload = await options?.onPayload?.(payload, model);
if (nextPayload !== undefined) {
payload = nextPayload as MiniMaxImageGenerationRequest;
}

const response = await fetch(model.baseUrl, {
method: "POST",
headers: buildHeaders(apiKey, model.headers, options?.headers),
body: JSON.stringify(payload),
signal: createRequestSignal(options),
});
const h3 = isMiniMaxH3ImageModel(model.id);
const payload = buildPayload(model, context, options);
const replacement = await options?.onPayload?.(payload, model);
const body = JSON.stringify(replacement === undefined ? payload : replacement);
const headers = buildHeaders(apiKey, model.headers, options?.headers);
const response = h3
? await postH3(model.baseUrl, body, headers, options ?? {})
: await fetch(model.baseUrl, { method: "POST", headers, body, signal: createRequestSignal(options) });
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);

const responseText = await response.text();
const responseBody = parseResponseBody(responseText);
if (h3) {
const parsed = parseResponseBody<H3Response>(responseText);
if (!response.ok || parsed.error) {
throw new Error(parsed.error?.message || `MiniMax H3 image generation failed with HTTP ${response.status}`);
}
output.responseId = parsed.request_id;
const warnings: string[] = [];
for (const [index, item] of (parsed.data ?? []).entries()) {
if (item.error) warnings.push(`Image ${index + 1}: ${item.error.message || item.error.code || "generation failed"}`);
else if (item.b64_json) output.output.push(base64ToContent(item.b64_json));
else if (item.url) output.output.push(await imageUrlToContent(item.url, options));
else warnings.push(`Image ${index + 1}: missing image data`);
}
if (!output.output.length) throw new Error(warnings.join("; ") || "MiniMax H3 image generation returned no images");
for (const text of warnings) output.output.push({ type: "text", text });
return output;
}

const responseBody = parseResponseBody<MiniMaxImageGenerationResponse>(responseText);
const statusCode = responseBody.base_resp?.status_code;
if (!response.ok || (statusCode !== undefined && statusCode !== 0)) {
throw new Error(getErrorMessage(response, responseBody));
throw new Error(getErrorMessage(response.status, responseBody));
}

output.responseId = responseBody.id;
Expand All @@ -125,7 +147,7 @@ function buildPayload(
model: ImagesModel<"minimax-images">,
context: ImagesContext,
options?: MiniMaxImagesOptions,
): MiniMaxImageGenerationRequest {
): MiniMaxImageGenerationRequest | ReturnType<typeof buildH3Payload> {
const subjectReference = context.input
.filter((item): item is ImageContent => item.type === "image")
.map((item) => ({
Expand All @@ -141,6 +163,10 @@ function buildPayload(
if (!prompt) {
throw new Error("MiniMax image generation requires a text prompt");
}
if (isMiniMaxH3ImageModel(model.id)) {
if (subjectReference.length) throw new Error("MiniMax H3 image generation accepts text input only");
return buildH3Payload(model.id, prompt, options);
}
if (options?.n !== undefined && (!Number.isSafeInteger(options.n) || options.n < 1 || options.n > MAX_IMAGE_COUNT)) {
throw new Error(`MiniMax image generation n must be an integer between 1 and ${MAX_IMAGE_COUNT}`);
}
Expand Down Expand Up @@ -182,21 +208,21 @@ function createRequestSignal(options?: MiniMaxImagesOptions): AbortSignal | unde
return options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
}

function parseResponseBody(responseText: string): MiniMaxImageGenerationResponse {
if (!responseText) return {};
function parseResponseBody<T extends object>(responseText: string): T {
if (!responseText) return {} as T;
try {
return JSON.parse(responseText) as MiniMaxImageGenerationResponse;
return JSON.parse(responseText) as T;
} catch {
throw new Error("MiniMax image generation returned invalid JSON");
}
}

function getErrorMessage(response: Response, responseBody: MiniMaxImageGenerationResponse): string {
function getErrorMessage(httpStatus: number, responseBody: MiniMaxImageGenerationResponse): string {
const statusMessage = responseBody.base_resp?.status_msg?.trim();
if (statusMessage) return `MiniMax image generation failed: ${statusMessage}`;
const statusCode = responseBody.base_resp?.status_code;
if (statusCode !== undefined) return `MiniMax image generation failed with status code ${statusCode}`;
return `MiniMax image generation failed with HTTP ${response.status}`;
return `MiniMax image generation failed with HTTP ${httpStatus}`;
}

async function imageUrlToContent(imageUrl: string, options?: MiniMaxImagesOptions): Promise<ImageContent> {
Expand Down
Loading
Loading