@aihubmix/ai-sdk-provider
Version:
<div align="center"> <a href="README.md">πΊπΈ English</a> | <a href="README.zh.md">π¨π³ δΈζ</a> | <a href="README.ja.md">π―π΅ ζ₯ζ¬θͺ</a> </div>
497 lines (488 loc) β’ 18.1 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
aihubmix: () => aihubmix,
createAihubmix: () => createAihubmix
});
module.exports = __toCommonJS(index_exports);
// src/aihubmix-provider.ts
var import_openai_compatible = require("@ai-sdk/openai-compatible");
var import_internal = require("@ai-sdk/openai/internal");
var import_internal2 = require("@ai-sdk/anthropic/internal");
var import_internal3 = require("@ai-sdk/google/internal");
var import_provider_utils6 = require("@ai-sdk/provider-utils");
// src/tool/code-interpreter.ts
var import_provider_utils = require("@ai-sdk/provider-utils");
var import_zod = require("zod");
var codeInterpreterInputSchema = import_zod.z.object({
code: import_zod.z.string().nullish(),
containerId: import_zod.z.string()
});
var codeInterpreterOutputSchema = import_zod.z.object({
outputs: import_zod.z.array(
import_zod.z.discriminatedUnion("type", [
import_zod.z.object({ type: import_zod.z.literal("logs"), logs: import_zod.z.string() }),
import_zod.z.object({ type: import_zod.z.literal("image"), url: import_zod.z.string() })
])
).nullish()
});
var codeInterpreterArgsSchema = import_zod.z.object({
container: import_zod.z.union([
import_zod.z.string(),
import_zod.z.object({
fileIds: import_zod.z.array(import_zod.z.string()).optional()
})
]).optional()
});
var codeInterpreterToolFactory = (0, import_provider_utils.createProviderToolFactoryWithOutputSchema)({
id: "aihubmix.code_interpreter",
inputSchema: codeInterpreterInputSchema,
outputSchema: codeInterpreterOutputSchema
});
var codeInterpreter = (args = {}) => {
return codeInterpreterToolFactory(args);
};
// src/tool/file-search.ts
var import_provider_utils2 = require("@ai-sdk/provider-utils");
var import_zod2 = require("zod");
var comparisonFilterSchema = import_zod2.z.object({
key: import_zod2.z.string(),
type: import_zod2.z.enum(["eq", "ne", "gt", "gte", "lt", "lte"]),
value: import_zod2.z.union([import_zod2.z.string(), import_zod2.z.number(), import_zod2.z.boolean()])
});
var compoundFilterSchema = import_zod2.z.object({
type: import_zod2.z.enum(["and", "or"]),
filters: import_zod2.z.array(
import_zod2.z.union([comparisonFilterSchema, import_zod2.z.lazy(() => compoundFilterSchema)])
)
});
var fileSearchArgsSchema = import_zod2.z.object({
vectorStoreIds: import_zod2.z.array(import_zod2.z.string()),
maxNumResults: import_zod2.z.number().optional(),
ranking: import_zod2.z.object({
ranker: import_zod2.z.string().optional(),
scoreThreshold: import_zod2.z.number().optional()
}).optional(),
filters: import_zod2.z.union([comparisonFilterSchema, compoundFilterSchema]).optional()
});
var fileSearchOutputSchema = import_zod2.z.object({
queries: import_zod2.z.array(import_zod2.z.string()),
results: import_zod2.z.array(
import_zod2.z.object({
attributes: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()),
fileId: import_zod2.z.string(),
filename: import_zod2.z.string(),
score: import_zod2.z.number(),
text: import_zod2.z.string()
})
).nullable()
});
var fileSearch = (0, import_provider_utils2.createProviderToolFactoryWithOutputSchema)({
id: "aihubmix.file_search",
inputSchema: import_zod2.z.object({}),
outputSchema: fileSearchOutputSchema
});
// src/tool/image-generation.ts
var import_provider_utils3 = require("@ai-sdk/provider-utils");
var import_zod3 = require("zod");
var imageGenerationArgsSchema = import_zod3.z.object({
background: import_zod3.z.enum(["auto", "opaque", "transparent"]).optional(),
inputFidelity: import_zod3.z.enum(["low", "high"]).optional(),
inputImageMask: import_zod3.z.object({
fileId: import_zod3.z.string().optional(),
imageUrl: import_zod3.z.string().optional()
}).optional(),
model: import_zod3.z.string().optional(),
moderation: import_zod3.z.enum(["auto"]).optional(),
outputCompression: import_zod3.z.number().int().min(0).max(100).optional(),
outputFormat: import_zod3.z.enum(["png", "jpeg", "webp"]).optional(),
quality: import_zod3.z.enum(["auto", "low", "medium", "high"]).optional(),
size: import_zod3.z.enum(["1024x1024", "1024x1536", "1536x1024", "auto"]).optional()
}).strict();
var imageGenerationOutputSchema = import_zod3.z.object({
result: import_zod3.z.string()
});
var imageGenerationToolFactory = (0, import_provider_utils3.createProviderToolFactoryWithOutputSchema)({
id: "aihubmix.image_generation",
inputSchema: import_zod3.z.object({}),
outputSchema: imageGenerationOutputSchema
});
var imageGeneration = (args = {}) => {
return imageGenerationToolFactory(args);
};
// src/tool/web-search.ts
var import_provider_utils4 = require("@ai-sdk/provider-utils");
var import_zod4 = require("zod");
var webSearchArgsSchema = import_zod4.z.object({
filters: import_zod4.z.object({
allowedDomains: import_zod4.z.array(import_zod4.z.string()).optional()
}).optional(),
searchContextSize: import_zod4.z.enum(["low", "medium", "high"]).optional(),
userLocation: import_zod4.z.object({
type: import_zod4.z.literal("approximate"),
country: import_zod4.z.string().optional(),
city: import_zod4.z.string().optional(),
region: import_zod4.z.string().optional(),
timezone: import_zod4.z.string().optional()
}).optional()
});
var webSearchToolFactory = (0, import_provider_utils4.createProviderToolFactory)({
id: "aihubmix.web_search",
inputSchema: import_zod4.z.object({
action: import_zod4.z.discriminatedUnion("type", [
import_zod4.z.object({
type: import_zod4.z.literal("search"),
query: import_zod4.z.string().nullish()
}),
import_zod4.z.object({
type: import_zod4.z.literal("open_page"),
url: import_zod4.z.string()
}),
import_zod4.z.object({
type: import_zod4.z.literal("find"),
url: import_zod4.z.string(),
pattern: import_zod4.z.string()
})
]).nullish()
})
});
var webSearch = (args = {}) => {
return webSearchToolFactory(args);
};
// src/tool/web-search-preview.ts
var import_provider_utils5 = require("@ai-sdk/provider-utils");
var import_zod5 = require("zod");
var webSearchPreviewArgsSchema = import_zod5.z.object({
/**
* Search context size to use for the web search.
* - high: Most comprehensive context, highest cost, slower response
* - medium: Balanced context, cost, and latency (default)
* - low: Least context, lowest cost, fastest response
*/
searchContextSize: import_zod5.z.enum(["low", "medium", "high"]).optional(),
/**
* User location information to provide geographically relevant search results.
*/
userLocation: import_zod5.z.object({
/**
* Type of location (always 'approximate')
*/
type: import_zod5.z.literal("approximate"),
/**
* Two-letter ISO country code (e.g., 'US', 'GB')
*/
country: import_zod5.z.string().optional(),
/**
* City name (free text, e.g., 'Minneapolis')
*/
city: import_zod5.z.string().optional(),
/**
* Region name (free text, e.g., 'Minnesota')
*/
region: import_zod5.z.string().optional(),
/**
* IANA timezone (e.g., 'America/Chicago')
*/
timezone: import_zod5.z.string().optional()
}).optional()
});
var webSearchPreview = (0, import_provider_utils5.createProviderToolFactory)({
id: "aihubmix.web_search_preview",
inputSchema: import_zod5.z.object({
action: import_zod5.z.discriminatedUnion("type", [
import_zod5.z.object({
type: import_zod5.z.literal("search"),
query: import_zod5.z.string().nullish()
}),
import_zod5.z.object({
type: import_zod5.z.literal("open_page"),
url: import_zod5.z.string()
}),
import_zod5.z.object({
type: import_zod5.z.literal("find"),
url: import_zod5.z.string(),
pattern: import_zod5.z.string()
})
]).nullish()
})
});
// src/aihubmix-tools.ts
var aihubmixTools = {
/**
* The Code Interpreter tool allows models to write and run Python code in a
* sandboxed environment to solve complex problems in domains like data analysis,
* coding, and math.
*
* @param container - The container to use for the code interpreter.
*
* Must have name `code_interpreter`.
*/
codeInterpreter,
/**
* File search is a tool available in the Responses API. It enables models to
* retrieve information in a knowledge base of previously uploaded files through
* semantic and keyword search.
*
* Must have name `file_search`.
*
* @param vectorStoreIds - The vector store IDs to use for the file search.
* @param maxNumResults - The maximum number of results to return.
* @param ranking - The ranking options to use for the file search.
* @param filters - The filters to use for the file search.
*/
fileSearch,
/**
* The image generation tool allows you to generate images using a text prompt,
* and optionally image inputs. It leverages the GPT Image model,
* and automatically optimizes text inputs for improved performance.
*
* Must have name `image_generation`.
*
* @param size - Image dimensions (e.g., 1024x1024, 1024x1536)
* @param quality - Rendering quality (e.g. low, medium, high)
* @param format - File output format
* @param compression - Compression level (0-100%) for JPEG and WebP formats
* @param background - Transparent or opaque
*/
imageGeneration,
/**
* Web search allows models to access up-to-date information from the internet
* and provide answers with sourced citations.
*
* Must have name `web_search_preview`.
*
* @param searchContextSize - The search context size to use for the web search.
* @param userLocation - The user location to use for the web search.
*
* @deprecated Use `webSearch` instead.
*/
webSearchPreview,
/**
* Web search allows models to access up-to-date information from the internet
* and provide answers with sourced citations.
*
* Must have name `web_search`.
*
* @param filters - The filters to use for the web search.
* @param searchContextSize - The search context size to use for the web search.
* @param userLocation - The user location to use for the web search.
*/
webSearch
};
// src/aihubmix-provider.ts
var AihubmixTranscriptionModel = class extends import_internal.OpenAITranscriptionModel {
async doGenerate(options) {
if (options.mediaType) {
const mimeTypeMap = {
"audio/mpeg": "mp3",
"audio/mp3": "mp3",
"audio/wav": "wav",
"audio/flac": "flac",
"audio/m4a": "m4a",
"audio/mp4": "mp4",
"audio/ogg": "ogg",
"audio/webm": "webm",
"audio/oga": "oga",
"audio/mpga": "mpga"
};
const extension = mimeTypeMap[options.mediaType];
if (extension) {
const originalGetArgs = this.getArgs;
this.getArgs = async function(args) {
const result = await originalGetArgs.call(this, args);
if (result.formData) {
const fileEntry = result.formData.get("file");
if (fileEntry && typeof fileEntry === "object" && "name" in fileEntry) {
try {
const newFile = new File([fileEntry], `audio.${extension}`, {
type: options.mediaType
});
result.formData.set("file", newFile);
} catch (error) {
console.log("Failed to create new File object:", error);
if (fileEntry && typeof fileEntry === "object" && "arrayBuffer" in fileEntry) {
try {
const arrayBuffer = await fileEntry.arrayBuffer();
const newFile = new File([arrayBuffer], `audio.${extension}`, {
type: options.mediaType
});
result.formData.set("file", newFile);
console.log("Created new file from arrayBuffer with name:", `audio.${extension}`);
} catch (bufferError) {
console.log("Failed to create file from arrayBuffer:", bufferError);
}
}
}
}
}
return result;
};
}
}
return super.doGenerate(options);
}
};
function transformRequestBody(body) {
if (body.tools && Array.isArray(body.tools) && body.tools.length === 0 && body.tool_choice) {
const { tool_choice, ...rest } = body;
return rest;
}
return body;
}
function createAihubmix(options = {}) {
const getHeaders = () => ({
Authorization: `Bearer ${(0, import_provider_utils6.loadApiKey)({
apiKey: options.apiKey,
environmentVariableName: "AIHUBMIX_API_KEY",
description: "Aihubmix"
})}`,
"APP-Code": "WHVL9885",
"Content-Type": "application/json"
});
const getTranscriptionHeaders = () => ({
Authorization: `Bearer ${(0, import_provider_utils6.loadApiKey)({
apiKey: options.apiKey,
environmentVariableName: "AIHUBMIX_API_KEY",
description: "Aihubmix"
})}`,
"APP-Code": "WHVL9885"
});
const url = ({ path, modelId }) => {
const baseURL = "https://aihubmix.com/v1";
return `${baseURL}${path}`;
};
const createChatModel = (deploymentName, settings = {}) => {
const headers = getHeaders();
if (deploymentName.startsWith("claude-")) {
const { Authorization, ...restHeaders } = headers;
return new import_internal2.AnthropicMessagesLanguageModel(deploymentName, {
provider: "aihubmix.chat",
baseURL: url({ path: "", modelId: deploymentName }),
headers: {
...restHeaders,
"x-api-key": Authorization.split(" ")[1]
},
supportedUrls: () => ({
"image/*": [/^https?:\/\/.*$/]
})
});
}
if ((deploymentName.startsWith("gemini") || deploymentName.startsWith("imagen")) && !deploymentName.endsWith("-nothink") && !deploymentName.endsWith("-search")) {
const { Authorization, ...restHeaders } = headers;
return new import_internal3.GoogleGenerativeAILanguageModel(
deploymentName,
{
provider: "aihubmix.chat",
baseURL: "https://aihubmix.com/gemini/v1beta",
headers: {
...restHeaders,
"x-goog-api-key": Authorization.split(" ")[1]
},
generateId: () => `aihubmix-${Date.now()}`,
supportedUrls: () => ({})
}
);
}
return new import_openai_compatible.OpenAICompatibleChatLanguageModel(deploymentName, {
provider: "aihubmix.chat",
url,
headers: getHeaders,
fetch: options.fetch,
includeUsage: true,
supportsStructuredOutputs: true,
transformRequestBody
});
};
const createCompletionModel = (modelId, settings = {}) => new import_openai_compatible.OpenAICompatibleCompletionLanguageModel(modelId, {
provider: "aihubmix.completion",
url,
headers: getHeaders,
fetch: options.fetch,
includeUsage: true
});
const createEmbeddingModel = (modelId, settings = {}) => {
return new import_openai_compatible.OpenAICompatibleEmbeddingModel(modelId, {
provider: "aihubmix.embeddings",
url,
headers: getHeaders,
fetch: options.fetch
});
};
const createResponsesModel = (modelId) => new import_internal.OpenAIResponsesLanguageModel(modelId, {
provider: "aihubmix.responses",
url,
headers: getHeaders
});
const createImageModel = (modelId, settings = {}) => {
return new import_openai_compatible.OpenAICompatibleImageModel(modelId, {
provider: "aihubmix.image",
url,
headers: getHeaders,
fetch: options.fetch
});
};
const createTranscriptionModel = (modelId) => new AihubmixTranscriptionModel(modelId, {
provider: "aihubmix.transcription",
url,
headers: getTranscriptionHeaders,
fetch: options.fetch
});
const createSpeechModel = (modelId) => new import_internal.OpenAISpeechModel(modelId, {
provider: "aihubmix.speech",
url,
headers: getHeaders,
fetch: options.fetch
});
const providerFn = function(deploymentId, settings) {
if (new.target) {
throw new Error(
"The Aihubmix model function cannot be called with the new keyword."
);
}
return createChatModel(deploymentId, settings);
};
const provider = Object.assign(providerFn, {
specificationVersion: "v3",
languageModel: createChatModel,
chat: createChatModel,
completion: createCompletionModel,
responses: createResponsesModel,
embedding: createEmbeddingModel,
embeddingModel: createEmbeddingModel,
textEmbedding: createEmbeddingModel,
textEmbeddingModel: createEmbeddingModel,
image: createImageModel,
imageModel: createImageModel,
transcription: createTranscriptionModel,
transcriptionModel: createTranscriptionModel,
speech: createSpeechModel,
speechModel: createSpeechModel,
tools: aihubmixTools
});
return provider;
}
var aihubmix = createAihubmix();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
aihubmix,
createAihubmix
});
//# sourceMappingURL=index.js.map