@intlayer/ai 8.7.12 → 8.7.14
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.
- package/README.md +27 -1
- package/dist/cjs/aiSdk.cjs.map +1 -1
- package/dist/cjs/auditDictionaryMetadata/index.cjs +1 -4
- package/dist/cjs/auditDictionaryMetadata/index.cjs.map +1 -1
- package/dist/cjs/customQuery.cjs +2 -1
- package/dist/cjs/customQuery.cjs.map +1 -1
- package/dist/cjs/translateJSON/index.cjs +2 -6
- package/dist/cjs/translateJSON/index.cjs.map +1 -1
- package/dist/esm/aiSdk.mjs.map +1 -1
- package/dist/esm/auditDictionaryMetadata/index.mjs +1 -4
- package/dist/esm/auditDictionaryMetadata/index.mjs.map +1 -1
- package/dist/esm/customQuery.mjs +2 -1
- package/dist/esm/customQuery.mjs.map +1 -1
- package/dist/esm/translateJSON/index.mjs +2 -6
- package/dist/esm/translateJSON/index.mjs.map +1 -1
- package/dist/types/aiSdk.d.ts +3 -2
- package/dist/types/aiSdk.d.ts.map +1 -1
- package/dist/types/customQuery.d.ts +3 -0
- package/dist/types/customQuery.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/package.json +32 -32
package/README.md
CHANGED
|
@@ -190,7 +190,22 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
|
|
|
190
190
|
<li><a href="https://intlayer.org/doc/environment/vite-and-react" rel=''>Vite + React</a></li>
|
|
191
191
|
<li><a href="https://intlayer.org/doc/environment/vite-and-react" rel=''>Vite + React using Compiler</a></li>
|
|
192
192
|
<li><a href="https://intlayer.org/doc/environment/vite-and-react/compiler" rel=''>React-router-v7</a></li>
|
|
193
|
-
<li><a href="https://intlayer.org/doc/environment/
|
|
193
|
+
<li><a href="https://intlayer.org/doc/environment/tanstack-start" rel=''>Tanstack start</a>
|
|
194
|
+
<ul>
|
|
195
|
+
<li><a href="https://intlayer.org/doc/environment/tanstack-start/solid" rel=''>Solid</a></li>
|
|
196
|
+
</ul>
|
|
197
|
+
</li>
|
|
198
|
+
<li><a href="https://intlayer.org/doc/environment/astro" rel=''>Astro</a>
|
|
199
|
+
<ul>
|
|
200
|
+
<li><a href="https://intlayer.org/doc/environment/astro/react" rel=''>React</a></li>
|
|
201
|
+
<li><a href="https://intlayer.org/doc/environment/astro/vue" rel=''>Vue</a></li>
|
|
202
|
+
<li><a href="https://intlayer.org/doc/environment/astro/svelte" rel=''>Svelte</a></li>
|
|
203
|
+
<li><a href="https://intlayer.org/doc/environment/astro/solid" rel=''>Solid</a></li>
|
|
204
|
+
<li><a href="https://intlayer.org/doc/environment/astro/vanilla" rel=''>Vanilla JS</a></li>
|
|
205
|
+
<li><a href="https://intlayer.org/doc/environment/astro/lit" rel=''>Lit</a></li>
|
|
206
|
+
</ul>
|
|
207
|
+
</li>
|
|
208
|
+
|
|
194
209
|
<li><a href="https://intlayer.org/doc/environment/react-native-and-expo" rel=''>React Native</a></li>
|
|
195
210
|
<li><a href="https://intlayer.org/doc/environment/vite-and-svelte" rel=''>Vite + Svelte</a></li>
|
|
196
211
|
<li><a href="https://intlayer.org/doc/environment/sveltekit" rel=''>SvelteKit</a></li>
|
|
@@ -212,6 +227,17 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
|
|
|
212
227
|
</ul>
|
|
213
228
|
</details>
|
|
214
229
|
|
|
230
|
+
<details>
|
|
231
|
+
<summary style="font-size:16px; font-weight:bold;">📊 Benchmark</summary>
|
|
232
|
+
<ul>
|
|
233
|
+
<li><a href="https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/benchmark/nextjs.md" rel=''>Next.js</a></li>
|
|
234
|
+
<li><a href="https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/benchmark/tanstack.md" rel=''>TanStack Start</a></li>
|
|
235
|
+
<li><a href="https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/benchmark/vue.md" rel=''>Vue</a></li>
|
|
236
|
+
<li><a href="https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/benchmark/solid.md" rel=''>Solid</a></li>
|
|
237
|
+
<li><a href="https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/benchmark/svelte.md" rel=''>Svelte</a></li>
|
|
238
|
+
</ul>
|
|
239
|
+
</details>
|
|
240
|
+
|
|
215
241
|
<details>
|
|
216
242
|
<summary style="font-size:16px; font-weight:bold;">📰 Blog</summary>
|
|
217
243
|
<ul>
|
package/dist/cjs/aiSdk.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aiSdk.cjs","names":["AiProviders","x","ANSIColors"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5-20251001';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\n\nexport type Messages = (\n | SystemModelMessage\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (isUserProvidedKey || provider === AiProviders.OLLAMA) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n ...defaultOptions,\n ...projectOptions,\n ...userOptions,\n } as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (!apiKey && aiOptions.provider !== AiProviders.OLLAMA) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;;;;AAwCA,MAAM,mBAAmBA,mCAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AA+IpC,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;AACH,KAAI,WAAW,SAAS,SAAS,CAC/B,QAAO,WAAW,UAAU;AAG9B,KAAI,WAAW,SAAS,SAAS,IAAI,WAAW,OAC9C,QAAO,WAAW;AAGpB,KAAI,WAAW,SAAS,kBAAkB,IAAI,gBAC5C,QAAO,WAAW,UAAU;AAI9B,KAAI,WAAW,SAAS,eAAe,IAAI,gBACzC,QAAO,WAAW,UAAU;;AAMhC,MAAM,gBACJ,UACA,mBACA,cACU;AAEV,KAAI,qBAAqB,aAAaA,mCAAY,QAAQ;AACxD,MAAI,UACF,QAAO;AAIT,SAAO;;AAKT,QAAO;;AAGT,MAAM,mBAAmB,OACvB,WACA,WACG;CACH,MAAM,aAAa,OAAU,gBAAoC;AAC/D,MAAI;AACF,UAAQ,MAAM,OAAO;UACf;AACN,uCACE,GAAGC,0BAAE,sDAAyB,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AwB3D,MAAa,mBAAmB,OAC9B,aACsD;AACtD,KAAI;AACF,6BAAqB;GACnB,GAAG;GACH,UAAU,CACR;IACE,MAAM;IACN,SAAS;IACV,CACF;GACD,iBAAiB;GAClB,CAAC;AACF,SAAO,EAAE,aAAa,MAAM;UACrB,OAAO;AACd,SAAO;GAAE,aAAa;GAAO,OAAQ,MAAgB;GAAS;;;;;;;;;;AAWlE,MAAa,cAAc,OACzB,SACA,kBAA2B,UACL;CACtB,MAAM,EACJ,aACA,gBACA,gBACA,aAAa,CAAC,kBAAkB,KAC9B;CAEJ,MAAM,YAAY;EAChB,UAAU;EACV,GAAG;EACH,GAAG;EACH,GAAG;EACJ;CAED,MAAM,SAAS,UAAU,YAAY,WAAW,gBAAgB;AAGhE,KAAI,CAAC,UAAU,UAAU,aAAaA,mCAAY,OAChD,OAAM,IAAI,MAAM,eAAe,UAAU,SAAS,aAAa;AAKjE,QAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,OAAO;EAI7D,aAAa,UAAU;EACvB,mBAAmB,UAAU;EAC9B"}
|
|
1
|
+
{"version":3,"file":"aiSdk.cjs","names":["AiProviders","x","ANSIColors"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5-20251001';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (isUserProvidedKey || provider === AiProviders.OLLAMA) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n ...defaultOptions,\n ...projectOptions,\n ...userOptions,\n } as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (!apiKey && aiOptions.provider !== AiProviders.OLLAMA) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;;;;AAwCA,MAAM,mBAAmBA,mCAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AAoJpC,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;AACH,KAAI,WAAW,SAAS,SAAS,CAC/B,QAAO,WAAW,UAAU;AAG9B,KAAI,WAAW,SAAS,SAAS,IAAI,WAAW,OAC9C,QAAO,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EJ,MAAM,EAAE,wBAAwB,MAAM,WAEpC,yBAAyB;AAQ3B,UANgB,oBAAoB;IAClC,aAAa;IACb;IACA,GAAG;IACJ,CAEa,CAAC,cAAwB;;EAGzC,KAAKA,mCAAY,YAAY;GAC3B,MAAM,EACJ,UACA,OACA,aACA,oBACA,mBACA,QAAQ,SACR,SAAS,UACT,GAAG,iBACD;GAEJ,MAAM,EAAE,qBACN,MAAM,WACJ,qBACD;AAQH,UANmB,iBAAiB;IAClC;IACA;IACA,GAAG;IACJ,CAEgB,CAAC,cAAwB;;EAG5C,QACE,OAAM,IAAI,MAAM,YAAY,SAAS,gBAAgB;;;;;;;;;AAwB3D,MAAa,mBAAmB,OAC9B,aACsD;AACtD,KAAI;AACF,6BAAqB;GACnB,GAAG;GACH,UAAU,CACR;IACE,MAAM;IACN,SAAS;IACV,CACF;GACD,iBAAiB;GAClB,CAAC;AACF,SAAO,EAAE,aAAa,MAAM;UACrB,OAAO;AACd,SAAO;GAAE,aAAa;GAAO,OAAQ,MAAgB;GAAS;;;;;;;;;;AAWlE,MAAa,cAAc,OACzB,SACA,kBAA2B,UACL;CACtB,MAAM,EACJ,aACA,gBACA,gBACA,aAAa,CAAC,kBAAkB,KAC9B;CAEJ,MAAM,YAAY;EAChB,UAAU;EACV,GAAG;EACH,GAAG;EACH,GAAG;EACJ;CAED,MAAM,SAAS,UAAU,YAAY,WAAW,gBAAgB;AAGhE,KAAI,CAAC,UAAU,UAAU,aAAaA,mCAAY,OAChD,OAAM,IAAI,MAAM,eAAe,UAAU,SAAS,aAAa;AAKjE,QAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,OAAO;EAI7D,aAAa,UAAU;EACvB,mBAAmB,UAAU;EAC9B"}
|
|
@@ -25,11 +25,8 @@ const auditDictionaryMetadata = async ({ fileContent, tags, aiConfig, applicatio
|
|
|
25
25
|
description: zod.z.string(),
|
|
26
26
|
tags: zod.z.array(zod.z.string())
|
|
27
27
|
}) }),
|
|
28
|
+
system: prompt,
|
|
28
29
|
messages: [
|
|
29
|
-
{
|
|
30
|
-
role: "system",
|
|
31
|
-
content: prompt
|
|
32
|
-
},
|
|
33
30
|
{
|
|
34
31
|
role: "user",
|
|
35
32
|
content: EXAMPLE_REQUEST
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["readAsset","Output","z"],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n messages: [\n { role: '
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["readAsset","Output","z"],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n system: prompt,\n messages: [\n { role: 'user', content: EXAMPLE_REQUEST },\n { role: 'assistant', content: EXAMPLE_RESPONSE },\n {\n role: 'user',\n content: fileContent,\n },\n ],\n });\n\n return {\n fileContent: output,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;AA0BA,MAAa,mBAA8B,EAE1C;;;;;;AAOD,MAAa,0BAA0B,OAAO,EAC5C,aACA,MACA,UACA,yBAGG;CACH,MAAM,kBAAkBA,+BAAU,cAAc;CAChD,MAAM,kBAAkBA,+BAAU,uBAAuB;CACzD,MAAM,mBAAmBA,+BAAU,wBAAwB;CAG3D,MAAM,SAAS,gBAAgB,QAC7B,0BACA,sBAAsB,GACvB,CAAC,QACA,YACA,OACI,KAAK,UACH,KACG,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,cAAc,CACzD,KAAK,OAAO,EACf,MACA,EACD,GACD,GACL;CAED,MAAM,EAAE,mBAAmB,GAAG,iBAAiB;CAC/C,MAAM,EAAE,QAAQ,eAAe,GAAG,kBAAkB;CAGpD,MAAM,EAAE,QAAQ,UAAU,2BAAmB;EAC3C,GAAG;EACH,QAAQC,UAAO,OAAO,EACpB,QAAQC,MAAE,OAAO;GACf,OAAOA,MAAE,QAAQ;GACjB,aAAaA,MAAE,QAAQ;GACvB,MAAMA,MAAE,MAAMA,MAAE,QAAQ,CAAC;GAC1B,CAAC,EACH,CAAC;EACF,QAAQ;EACR,UAAU;GACR;IAAE,MAAM;IAAQ,SAAS;IAAiB;GAC1C;IAAE,MAAM;IAAa,SAAS;IAAkB;GAChD;IACE,MAAM;IACN,SAAS;IACV;GACF;EACF,CAAC;AAEF,QAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;EAClC"}
|
package/dist/cjs/customQuery.cjs
CHANGED
|
@@ -9,9 +9,10 @@ const aiDefaultOptions = { model: "gpt-4o-mini" };
|
|
|
9
9
|
* The prompt includes details about the project's locales, file paths of content declarations,
|
|
10
10
|
* and requests for identifying issues or inconsistencies.
|
|
11
11
|
*/
|
|
12
|
-
const customQuery = async ({ messages, aiConfig }) => {
|
|
12
|
+
const customQuery = async ({ messages, system, aiConfig }) => {
|
|
13
13
|
const { text: newContent, usage } = await (0, ai.generateText)({
|
|
14
14
|
...aiConfig,
|
|
15
|
+
system,
|
|
15
16
|
messages
|
|
16
17
|
});
|
|
17
18
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customQuery.cjs","names":[],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"customQuery.cjs","names":[],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText, type SystemModelMessage } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n system?: string | SystemModelMessage | SystemModelMessage[];\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n system,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n system,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;AAcA,MAAa,mBAA8B,EACzC,OAAO,eAER;;;;;;AAOD,MAAa,cAAc,OAAO,EAChC,UACA,QACA,eACoE;CAEpE,MAAM,EAAE,MAAM,YAAY,UAAU,2BAAmB;EACrD,GAAG;EACH;EACA;EACD,CAAC;AAEF,QAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;EAClC"}
|
|
@@ -78,10 +78,8 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
|
|
|
78
78
|
if (isToon) {
|
|
79
79
|
const { text, usage } = await (0, ai.generateText)({
|
|
80
80
|
...aiConfig,
|
|
81
|
+
system: prompt,
|
|
81
82
|
messages: [{
|
|
82
|
-
role: "system",
|
|
83
|
-
content: prompt
|
|
84
|
-
}, {
|
|
85
83
|
role: "user",
|
|
86
84
|
content: [
|
|
87
85
|
`# Translation Request`,
|
|
@@ -103,10 +101,8 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
|
|
|
103
101
|
const { text, usage } = await (0, ai.generateText)({
|
|
104
102
|
...validAiConfig,
|
|
105
103
|
output: useStrictOutput ? ai.Output.object({ schema }) : void 0,
|
|
104
|
+
system: prompt,
|
|
106
105
|
messages: [{
|
|
107
|
-
role: "system",
|
|
108
|
-
content: prompt
|
|
109
|
-
}, {
|
|
110
106
|
role: "user",
|
|
111
107
|
content: [
|
|
112
108
|
`# Translation Request`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["AIProvider","DEFAULT_LOCALE","z","readAsset","Output","extractJson"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,mCAAW;CACrB,OAAO;CACR;;;;;;;AAQD,MAAM,wBAAwB,WAC5B,GAAG,OAAO,mDAAkB,QAAQC,8CAAe;;;;;;;;AASrD,MAAM,yBAAyB,SAAwB;AACrD,KAAI,CAAC,QAAQ,KAAK,WAAW,EAC3B,QAAO;AAIT,QAAO;;EAEP,KAAK,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,cAAc,CAAC,KAAK,OAAO;;AAG7E,MAAM,uBAAuB,SAAwC;AACnE,KAAI,SAAS,WACX,QAAO;AAGT,QAAO;;AAGT,MAAM,aAAa,YAA+B;AAEhD,KAAI,OAAO,YAAY,SACrB,QAAOC,MAAE,QAAQ;AAInB,KAAI,OAAO,YAAY,SACrB,QAAOA,MAAE,QAAQ;AAEnB,KAAI,OAAO,YAAY,UACrB,QAAOA,MAAE,SAAS;AAIpB,KAAI,MAAM,QAAQ,QAAQ,EAAE;AAE1B,MAAI,QAAQ,WAAW,EACrB,QAAOA,MAAE,MAAMA,MAAE,QAAQ,CAAC;AAG5B,SAAOA,MAAE,MAAM,UAAU,QAAQ,GAAG,CAAC;;AAIvC,KAAI,OAAO,YAAY,YAAY,YAAY,MAAM;EACnD,MAAM,QAAsC,EAAE;AAC9C,OAAK,MAAM,OAAO,QAChB,OAAM,OAAO,UAAU,QAAQ,KAAK;AAEtC,SAAOA,MAAE,OAAO,MAAM;;AAIxB,QAAOA,MAAE,Q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mC,CAKZ;GACxB,WAAW,OAAO,eAAe;GAClC;;CAOH,MAAM,kBAJY,UAAU,iBAIK,IAAI;CAGrC,MAAM,EAAE,MAAM,UAAU,2BAAmB;EACzC,GAAG;EAGH,QAAQ,kBAAkBC,UAAO,OAAO,EAAE,QAAQ,CAAC,GAAG;EACtD,UAAU,CACR;GAAE,MAAM;GAAU,SAAS;GAAQ,EACnC;GACE,MAAM;GACN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACD,CAAC,KAAK,KAAK;GACb,CACF;EACF,CAAC;CAGF,MAAM,gBAAgBC,sCAAY,KAAK;AAGvC,QAAO;EACL,aAHuB,OAAO,MAAM,cAGP;EAC7B,WAAW,OAAO,eAAe;EAClC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["AIProvider","DEFAULT_LOCALE","z","readAsset","Output","extractJson"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,mCAAW;CACrB,OAAO;CACR;;;;;;;AAQD,MAAM,wBAAwB,WAC5B,GAAG,OAAO,mDAAkB,QAAQC,8CAAe;;;;;;;;AASrD,MAAM,yBAAyB,SAAwB;AACrD,KAAI,CAAC,QAAQ,KAAK,WAAW,EAC3B,QAAO;AAIT,QAAO;;EAEP,KAAK,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,cAAc,CAAC,KAAK,OAAO;;AAG7E,MAAM,uBAAuB,SAAwC;AACnE,KAAI,SAAS,WACX,QAAO;AAGT,QAAO;;AAGT,MAAM,aAAa,YA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AoB,sBAAsB,CAClD,QAAQ,2BAA2B,iBAAiB,CACpD,QAAQ,6BAA6B,yBAAyB,GAAG,CACjE,QAAQ,0BAA0B,sBAAsB,GAAG,CAC3D,QAAQ,wBAAwB,sBAAsB,QAAQ,EAAE,CAAC,CAAC,CAClE,QAAQ,wBAAwB,oBAAoB,KAAK,CAAC;AAE7D,KAAI,QAAQ;EACV,MAAM,EAAE,MAAM,UAAU,2BAAmB;GACzC,GAAG;GACH,QAAQ;GACR,UAAU,CACR;IACE,MAAM;IACN,SAAS;KACP;KACA;KACA,eAAe;KACf,aAAa;KACb;KACA;KACA;KACD,CAAC,KAAK,KAAK;IACb,CACF;GACF,CAAC;AAWF,SAAO;GACL,2CATkB,KACjB,QAAQ,qCAAqC,KAAK,CAClD,MAEmC,CAKZ;GACxB,WAAW,OAAO,eAAe;GAClC;;CAOH,MAAM,kBAJY,UAAU,iBAIK,IAAI;CAGrC,MAAM,EAAE,MAAM,UAAU,2BAAmB;EACzC,GAAG;EAGH,QAAQ,kBAAkBC,UAAO,OAAO,EAAE,QAAQ,CAAC,GAAG;EACtD,QAAQ;EACR,UAAU,CACR;GACE,MAAM;GACN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACD,CAAC,KAAK,KAAK;GACb,CACF;EACF,CAAC;CAGF,MAAM,gBAAgBC,sCAAY,KAAK;AAGvC,QAAO;EACL,aAHuB,OAAO,MAAM,cAGP;EAC7B,WAAW,OAAO,eAAe;EAClC"}
|
package/dist/esm/aiSdk.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aiSdk.mjs","names":["generateTextFn"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5-20251001';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\n\nexport type Messages = (\n | SystemModelMessage\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (isUserProvidedKey || provider === AiProviders.OLLAMA) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n ...defaultOptions,\n ...projectOptions,\n ...userOptions,\n } as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (!apiKey && aiOptions.provider !== AiProviders.OLLAMA) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n data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OAAO,MAHmB,iBAAiB,WAAW,OAAO;EAI7D,aAAa,UAAU;EACvB,mBAAmB,UAAU;EAC9B"}
|
|
1
|
+
{"version":3,"file":"aiSdk.mjs","names":["generateTextFn"],"sources":["../../src/aiSdk.ts"],"sourcesContent":["import type { AlibabaProvider, createAlibaba } from '@ai-sdk/alibaba';\nimport type {\n AmazonBedrockProvider,\n createAmazonBedrock,\n} from '@ai-sdk/amazon-bedrock';\nimport type { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic';\nimport type { createDeepSeek, DeepSeekProvider } from '@ai-sdk/deepseek';\nimport type { createFireworks, FireworksProvider } from '@ai-sdk/fireworks';\nimport type {\n createGoogleGenerativeAI,\n GoogleGenerativeAIProvider,\n} from '@ai-sdk/google';\nimport type {\n createVertex,\n GoogleVertexProvider as VertexProvider,\n} from '@ai-sdk/google-vertex';\nimport type { createGroq, GroqProvider } from '@ai-sdk/groq';\nimport type {\n createHuggingFace,\n HuggingFaceProvider,\n} from '@ai-sdk/huggingface';\nimport type { createMistral, MistralProvider } from '@ai-sdk/mistral';\nimport type { createOpenAI, OpenAIProvider } from '@ai-sdk/openai';\nimport type { createTogetherAI, TogetherAIProvider } from '@ai-sdk/togetherai';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, logger, x } from '@intlayer/config/logger';\nimport { AiProviders } from '@intlayer/types/config';\nimport type {\n createOpenRouter,\n OpenRouterProvider,\n} from '@openrouter/ai-sdk-provider';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport { generateText as generateTextFn } from 'ai';\n\nconst DEFAULT_PROVIDER = AiProviders.ANTHROPIC;\nconst DEFAULT_MODEL = 'claude-haiku-4-5-20251001';\nconst DEFAULT_API_KEY = process.env.ANTHROPIC_API_KEY;\n\nexport { AiProviders as AIProvider };\n\ntype AnthropicModel = Parameters<AnthropicProvider>[0];\ntype DeepSeekModel = Parameters<DeepSeekProvider>[0];\ntype MistralModel = Parameters<MistralProvider>[0];\ntype OpenAIModel = Parameters<OpenAIProvider>[0];\ntype OpenRouterModel = Parameters<OpenRouterProvider>[0];\ntype GoogleModel = Parameters<GoogleGenerativeAIProvider>[0];\ntype VertexModel = Parameters<VertexProvider>[0];\ntype AlibabaModel = Parameters<AlibabaProvider>[0];\ntype AmazonBedrockModel = Parameters<AmazonBedrockProvider>[0];\ntype FireworksModel = Parameters<FireworksProvider>[0];\ntype GroqModel = Parameters<GroqProvider>[0];\ntype HuggingFaceModel = Parameters<HuggingFaceProvider>[0];\ntype TogetherAIModel = Parameters<TogetherAIProvider>[0];\n\nexport type OpenAIProviderOptions = Parameters<typeof createOpenAI>[0];\nexport type AnthropicProviderOptions = Parameters<typeof createAnthropic>[0];\nexport type MistralProviderOptions = Parameters<typeof createMistral>[0];\nexport type DeepSeekProviderOptions = Parameters<typeof createDeepSeek>[0];\nexport type GoogleProviderOptions = Parameters<\n typeof createGoogleGenerativeAI\n>[0];\nexport type VertexProviderOptions = Parameters<typeof createVertex>[0];\nexport type OpenRouterProviderOptions = Parameters<typeof createOpenRouter>[0];\nexport type AlibabaProviderOptions = Parameters<typeof createAlibaba>[0];\nexport type FireworksProviderOptions = Parameters<typeof createFireworks>[0];\nexport type GroqProviderOptions = Parameters<typeof createGroq>[0];\nexport type HuggingFaceProviderOptions = Parameters<\n typeof createHuggingFace\n>[0];\nexport type AmazonBedrockProviderOptions = Parameters<\n typeof createAmazonBedrock\n>[0];\nexport type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];\n\nexport type SystemMessage =\n | string\n | SystemModelMessage\n | SystemModelMessage[]\n | undefined;\n\nexport type Messages = (\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | OpenRouterModel\n | GoogleModel\n | VertexModel\n | AlibabaModel\n | AmazonBedrockModel\n | FireworksModel\n | GroqModel\n | HuggingFaceModel\n | TogetherAIModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\n\nexport type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'none';\n\n/**\n * Common options for all AI providers\n */\ntype CommonAIOptions = {\n model?: Model;\n temperature?: number;\n baseURL?: string;\n apiKey?: string;\n applicationContext?: string;\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIOptions = (\n | ({\n provider: AiProviders.OPENAI | `${AiProviders.OPENAI}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.ANTHROPIC | `${AiProviders.ANTHROPIC}`;\n } & AnthropicProviderOptions)\n | ({\n provider: AiProviders.MISTRAL | `${AiProviders.MISTRAL}`;\n } & MistralProviderOptions)\n | ({\n provider: AiProviders.DEEPSEEK | `${AiProviders.DEEPSEEK}`;\n } & DeepSeekProviderOptions)\n | ({\n provider: AiProviders.GEMINI | `${AiProviders.GEMINI}`;\n } & GoogleProviderOptions)\n | ({\n provider:\n | AiProviders.GOOGLEGENERATIVEAI\n | `${AiProviders.GOOGLEGENERATIVEAI}`;\n } & GoogleProviderOptions)\n | ({\n provider: AiProviders.OLLAMA | `${AiProviders.OLLAMA}`;\n } & OpenAIProviderOptions)\n | ({\n provider: AiProviders.OPENROUTER | `${AiProviders.OPENROUTER}`;\n } & OpenRouterProviderOptions)\n | ({\n provider: AiProviders.ALIBABA | `${AiProviders.ALIBABA}`;\n } & AlibabaProviderOptions)\n | ({\n provider: AiProviders.FIREWORKS | `${AiProviders.FIREWORKS}`;\n } & FireworksProviderOptions)\n | ({\n provider: AiProviders.GROQ | `${AiProviders.GROQ}`;\n } & GroqProviderOptions)\n | ({\n provider: AiProviders.HUGGINGFACE | `${AiProviders.HUGGINGFACE}`;\n } & HuggingFaceProviderOptions)\n | ({\n provider: AiProviders.BEDROCK | `${AiProviders.BEDROCK}`;\n } & AmazonBedrockProviderOptions)\n | ({\n provider: AiProviders.GOOGLEVERTEX | `${AiProviders.GOOGLEVERTEX}`;\n } & VertexProviderOptions)\n | ({\n provider: AiProviders.TOGETHERAI | `${AiProviders.TOGETHERAI}`;\n } & TogetherAIProviderOptions)\n | ({ provider?: undefined } & OpenAIProviderOptions)\n) &\n CommonAIOptions;\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n accessType: AccessType[],\n aiOptions?: AIOptions,\n isAuthenticated: boolean = false\n) => {\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && isAuthenticated) {\n return aiOptions?.apiKey ?? DEFAULT_API_KEY;\n }\n\n return undefined;\n};\n\nconst getModelName = (\n provider: AiProviders,\n isUserProvidedKey: boolean,\n userModel?: Model\n): Model => {\n // If the user provides their own API key, allow custom model selection\n if (isUserProvidedKey || provider === AiProviders.OLLAMA) {\n if (userModel) {\n return userModel;\n }\n\n // No custom model specified — fall back to the default\n return DEFAULT_MODEL;\n }\n\n // Using backend's default API key — always use the default model,\n // ignore any custom model the user may have passed\n return DEFAULT_MODEL;\n};\n\nconst getLanguageModel = async (\n aiOptions: AIOptions,\n apiKey: string | undefined\n) => {\n const loadModule = async <T>(packageName: string): Promise<T> => {\n try {\n return (await import(packageName)) as T;\n } catch {\n logger(\n `${x} The package \"${colorize(packageName, ANSIColors.GREEN)}\" is required to use this AI provider. Please install it using: ${colorize(`npm install ${packageName}`, ANSIColors.GREY_DARK)}`,\n {\n level: 'error',\n }\n );\n process.exit();\n }\n };\n\n const provider = aiOptions.provider ?? AiProviders.OPENAI;\n const selectedModel = getModelName(\n provider as AiProviders,\n !!aiOptions.apiKey, // true only when the user explicitly provided their own key\n aiOptions.model\n );\n\n const baseURL = aiOptions.baseURL;\n\n switch (provider) {\n case AiProviders.OPENAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n return createOpenAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.ANTHROPIC: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAnthropic } =\n await loadModule<typeof import('@ai-sdk/anthropic')>(\n '@ai-sdk/anthropic'\n );\n\n return createAnthropic({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.MISTRAL: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createMistral } =\n await loadModule<typeof import('@ai-sdk/mistral')>('@ai-sdk/mistral');\n\n return createMistral({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.DEEPSEEK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createDeepSeek } =\n await loadModule<typeof import('@ai-sdk/deepseek')>('@ai-sdk/deepseek');\n\n return createDeepSeek({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GEMINI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel);\n }\n\n case AiProviders.GOOGLEVERTEX: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createVertex } = await loadModule<\n typeof import('@ai-sdk/google-vertex')\n >('@ai-sdk/google-vertex');\n\n return createVertex({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.GOOGLEGENERATIVEAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGoogleGenerativeAI } =\n await loadModule<typeof import('@ai-sdk/google')>('@ai-sdk/google');\n\n return createGoogleGenerativeAI({\n apiKey,\n baseURL,\n ...otherOptions,\n })(selectedModel as string);\n }\n\n case AiProviders.OLLAMA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenAI } =\n await loadModule<typeof import('@ai-sdk/openai')>('@ai-sdk/openai');\n\n // Ollama compatible mode:\n const ollama = createOpenAI({\n baseURL: baseURL ?? 'http://localhost:11434/v1',\n apiKey: apiKey ?? 'ollama', // Required but unused by Ollama\n ...otherOptions,\n });\n\n return ollama.chat(selectedModel);\n }\n\n case AiProviders.OPENROUTER: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createOpenRouter } = await loadModule<\n typeof import('@openrouter/ai-sdk-provider')\n >('@openrouter/ai-sdk-provider');\n\n const openrouter = createOpenRouter({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return openrouter(selectedModel as string);\n }\n\n case AiProviders.ALIBABA: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAlibaba } =\n await loadModule<typeof import('@ai-sdk/alibaba')>('@ai-sdk/alibaba');\n\n const alibaba = createAlibaba({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return alibaba(selectedModel as string);\n }\n\n case AiProviders.FIREWORKS: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createFireworks } =\n await loadModule<typeof import('@ai-sdk/fireworks')>(\n '@ai-sdk/fireworks'\n );\n\n const fireworks = createFireworks({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return fireworks(selectedModel as string);\n }\n\n case AiProviders.GROQ: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createGroq } =\n await loadModule<typeof import('@ai-sdk/groq')>('@ai-sdk/groq');\n\n const groq = createGroq({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return groq(selectedModel as string);\n }\n\n case AiProviders.HUGGINGFACE: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createHuggingFace } = await loadModule<\n typeof import('@ai-sdk/huggingface')\n >('@ai-sdk/huggingface');\n\n const huggingface = createHuggingFace({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return huggingface(selectedModel as string);\n }\n\n case AiProviders.BEDROCK: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createAmazonBedrock } = await loadModule<\n typeof import('@ai-sdk/amazon-bedrock')\n >('@ai-sdk/amazon-bedrock');\n\n const bedrock = createAmazonBedrock({\n accessKeyId: apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return bedrock(selectedModel as string);\n }\n\n case AiProviders.TOGETHERAI: {\n const {\n provider,\n model,\n temperature,\n applicationContext,\n dataSerialization,\n apiKey: _apiKey,\n baseURL: _baseURL,\n ...otherOptions\n } = aiOptions as any;\n\n const { createTogetherAI } =\n await loadModule<typeof import('@ai-sdk/togetherai')>(\n '@ai-sdk/togetherai'\n );\n\n const togetherai = createTogetherAI({\n apiKey,\n baseURL,\n ...otherOptions,\n });\n\n return togetherai(selectedModel as string);\n }\n\n default: {\n throw new Error(`Provider ${provider} not supported`);\n }\n }\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'> & {\n reasoningEffort?: ReasoningEffort;\n textVerbosity?: 'low' | 'medium' | 'high';\n dataSerialization?: 'json' | 'toon';\n};\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n projectOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Sends a minimal request to verify that the configured AI provider credentials\n * are valid and reachable before starting any bulk operation.\n *\n * @returns true if access is confirmed, false otherwise\n */\nexport const checkAISDKAccess = async (\n aiConfig: AIConfig\n): Promise<{ hasAIAccess: boolean; error?: string }> => {\n try {\n await generateTextFn({\n ...aiConfig,\n messages: [\n {\n role: 'user',\n content: 'ping',\n },\n ],\n maxOutputTokens: 20,\n });\n return { hasAIAccess: true };\n } catch (error) {\n return { hasAIAccess: false, error: (error as Error).message };\n }\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n options: AIConfigOptions,\n isAuthenticated: boolean = false\n): Promise<AIConfig> => {\n const {\n userOptions,\n projectOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n ...defaultOptions,\n ...projectOptions,\n ...userOptions,\n } as AIOptions;\n\n const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);\n\n // Check if API key is provided\n if (!apiKey && aiOptions.provider !== AiProviders.OLLAMA) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const languageModel = await getLanguageModel(aiOptions, apiKey);\n\n return {\n model: languageModel,\n temperature: aiOptions.temperature,\n dataSerialization: aiOptions.dataSerialization,\n };\n};\n"],"mappings":";;;;;;AAwCA,MAAM,mBAAmB,YAAY;AACrC,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,QAAQ,IAAI;AAoJpC,MAAM,aACJ,YACA,WACA,kBAA2B,UACxB;AACH,KAAI,WAAW,SAAS,SAAS,CAC/B,QAAO,WAAW,UAAU;AAG9B,KAAI,WAAW,SAAS,SAAS,IAAI,WAAW,OAC9C,QAAO,WAAW;AAGpB,KAAI,WAAW,SAAS,kBAAkB,IAAI,gBAC5C,QAAO,WAAW,UAAU;AAI9B,KAAI,WAAW,SAAS,eAAe,IAAI,gBACzC,QAAO,WAAW,UAAU;;AAMhC,MAAM,gBACJ,UACA,mBACA,cACU;AAEV,KAAI,qBAAqB,aAAa,YAAY,QAAQ;AACxD,MAAI,UACF,QAAO;AAIT,SAAO;;AAKT,QAAO;;AAGT,MAAM,mBAAmB,OACvB,WACA,WACG;CACH,MAAM,aAAa,OAAU,gBAAoC;AAC/D,MAAI;AACF,UAAQ,MAAM,OAAO;UACf;AACN,UACE,GAAG,EAAE,gBAAgB,SAAS,aAAa,WAAW,MAAM,CAAC,kEAAkE,SAAS,eAAe,eAAe,WAAW,UAAU,IAC3L,EACE,OAAO,SACR,CACF;AACD,WAAQ,MAAM;;;CAIlB,MAAM,WAAW,UAAU,YAAY,YAAY;CACnD,MAAM,gBAAgB,aACpB,UACA,CAAC,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Q,MAAgB;GAAS;;;;;;;;;;AAWlE,MAAa,cAAc,OACzB,SACA,kBAA2B,UACL;CACtB,MAAM,EACJ,aACA,gBACA,gBACA,aAAa,CAAC,kBAAkB,KAC9B;CAEJ,MAAM,YAAY;EAChB,UAAU;EACV,GAAG;EACH,GAAG;EACH,GAAG;EACJ;CAED,MAAM,SAAS,UAAU,YAAY,WAAW,gBAAgB;AAGhE,KAAI,CAAC,UAAU,UAAU,aAAa,YAAY,OAChD,OAAM,IAAI,MAAM,eAAe,UAAU,SAAS,aAAa;AAKjE,QAAO;EACL,OAAO,MAHmB,iBAAiB,WAAW,OAAO;EAI7D,aAAa,UAAU;EACvB,mBAAmB,UAAU;EAC9B"}
|
|
@@ -23,11 +23,8 @@ const auditDictionaryMetadata = async ({ fileContent, tags, aiConfig, applicatio
|
|
|
23
23
|
description: z.string(),
|
|
24
24
|
tags: z.array(z.string())
|
|
25
25
|
}) }),
|
|
26
|
+
system: prompt,
|
|
26
27
|
messages: [
|
|
27
|
-
{
|
|
28
|
-
role: "system",
|
|
29
|
-
content: prompt
|
|
30
|
-
},
|
|
31
28
|
{
|
|
32
29
|
role: "user",
|
|
33
30
|
content: EXAMPLE_REQUEST
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n messages: [\n { role: '
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/auditDictionaryMetadata/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport type { AIConfig, AIOptions } from '../aiSdk';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type AuditDictionaryMetadataOptions = {\n fileContent: string;\n tags?: Tag[];\n aiConfig: AIConfig;\n applicationContext?: string;\n};\n\nexport type AuditFileResultData = {\n fileContent: {\n title: string;\n description: string;\n tags: string[];\n };\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n // Keep default options\n};\n\n/**\n * Audits a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const auditDictionaryMetadata = async ({\n fileContent,\n tags,\n aiConfig,\n applicationContext,\n}: AuditDictionaryMetadataOptions): Promise<\n AuditFileResultData | undefined\n> => {\n const CHAT_GPT_PROMPT = readAsset('./PROMPT.md');\n const EXAMPLE_REQUEST = readAsset('./EXAMPLE_REQUEST.md');\n const EXAMPLE_RESPONSE = readAsset('./EXAMPLE_RESPONSE.md');\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = CHAT_GPT_PROMPT.replace(\n '{{applicationContext}}',\n applicationContext ?? ''\n ).replace(\n '{{tags}}',\n tags\n ? JSON.stringify(\n tags\n .map(({ key, description }) => `- ${key}: ${description}`)\n .join('\\n\\n'),\n null,\n 2\n )\n : ''\n );\n\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: z.object({\n title: z.string(),\n description: z.string(),\n tags: z.array(z.string()),\n }),\n }),\n system: prompt,\n messages: [\n { role: 'user', content: EXAMPLE_REQUEST },\n { role: 'assistant', content: EXAMPLE_RESPONSE },\n {\n role: 'user',\n content: fileContent,\n },\n ],\n });\n\n return {\n fileContent: output,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;AA0BA,MAAa,mBAA8B,EAE1C;;;;;;AAOD,MAAa,0BAA0B,OAAO,EAC5C,aACA,MACA,UACA,yBAGG;CACH,MAAM,kBAAkB,UAAU,cAAc;CAChD,MAAM,kBAAkB,UAAU,uBAAuB;CACzD,MAAM,mBAAmB,UAAU,wBAAwB;CAG3D,MAAM,SAAS,gBAAgB,QAC7B,0BACA,sBAAsB,GACvB,CAAC,QACA,YACA,OACI,KAAK,UACH,KACG,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,cAAc,CACzD,KAAK,OAAO,EACf,MACA,EACD,GACD,GACL;CAED,MAAM,EAAE,mBAAmB,GAAG,iBAAiB;CAC/C,MAAM,EAAE,QAAQ,eAAe,GAAG,kBAAkB;CAGpD,MAAM,EAAE,QAAQ,UAAU,MAAM,aAAa;EAC3C,GAAG;EACH,QAAQ,OAAO,OAAO,EACpB,QAAQ,EAAE,OAAO;GACf,OAAO,EAAE,QAAQ;GACjB,aAAa,EAAE,QAAQ;GACvB,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;GAC1B,CAAC,EACH,CAAC;EACF,QAAQ;EACR,UAAU;GACR;IAAE,MAAM;IAAQ,SAAS;IAAiB;GAC1C;IAAE,MAAM;IAAa,SAAS;IAAkB;GAChD;IACE,MAAM;IACN,SAAS;IACV;GACF;EACF,CAAC;AAEF,QAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;EAClC"}
|
package/dist/esm/customQuery.mjs
CHANGED
|
@@ -7,9 +7,10 @@ const aiDefaultOptions = { model: "gpt-4o-mini" };
|
|
|
7
7
|
* The prompt includes details about the project's locales, file paths of content declarations,
|
|
8
8
|
* and requests for identifying issues or inconsistencies.
|
|
9
9
|
*/
|
|
10
|
-
const customQuery = async ({ messages, aiConfig }) => {
|
|
10
|
+
const customQuery = async ({ messages, system, aiConfig }) => {
|
|
11
11
|
const { text: newContent, usage } = await generateText({
|
|
12
12
|
...aiConfig,
|
|
13
|
+
system,
|
|
13
14
|
messages
|
|
14
15
|
});
|
|
15
16
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customQuery.mjs","names":[],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"customQuery.mjs","names":[],"sources":["../../src/customQuery.ts"],"sourcesContent":["import { generateText, type SystemModelMessage } from 'ai';\nimport type { AIConfig, AIOptions, Messages } from './aiSdk';\n\nexport type CustomQueryOptions = {\n messages: Messages;\n system?: string | SystemModelMessage | SystemModelMessage[];\n aiConfig: AIConfig;\n};\n\nexport type CustomQueryResultData = {\n fileContent: string;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n model: 'gpt-4o-mini',\n // Keep default options\n};\n\n/**\n * CustomQuery a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const customQuery = async ({\n messages,\n system,\n aiConfig,\n}: CustomQueryOptions): Promise<CustomQueryResultData | undefined> => {\n // Use the AI SDK to generate the completion\n const { text: newContent, usage } = await generateText({\n ...aiConfig,\n system,\n messages,\n });\n\n return {\n fileContent: newContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;AAcA,MAAa,mBAA8B,EACzC,OAAO,eAER;;;;;;AAOD,MAAa,cAAc,OAAO,EAChC,UACA,QACA,eACoE;CAEpE,MAAM,EAAE,MAAM,YAAY,UAAU,MAAM,aAAa;EACrD,GAAG;EACH;EACA;EACD,CAAC;AAEF,QAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;EAClC"}
|
|
@@ -76,10 +76,8 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
|
|
|
76
76
|
if (isToon) {
|
|
77
77
|
const { text, usage } = await generateText({
|
|
78
78
|
...aiConfig,
|
|
79
|
+
system: prompt,
|
|
79
80
|
messages: [{
|
|
80
|
-
role: "system",
|
|
81
|
-
content: prompt
|
|
82
|
-
}, {
|
|
83
81
|
role: "user",
|
|
84
82
|
content: [
|
|
85
83
|
`# Translation Request`,
|
|
@@ -101,10 +99,8 @@ const translateJSON = async ({ entryFileContent, presetOutputContent, dictionary
|
|
|
101
99
|
const { text, usage } = await generateText({
|
|
102
100
|
...validAiConfig,
|
|
103
101
|
output: useStrictOutput ? Output.object({ schema }) : void 0,
|
|
102
|
+
system: prompt,
|
|
104
103
|
messages: [{
|
|
105
|
-
role: "system",
|
|
106
|
-
content: prompt
|
|
107
|
-
}, {
|
|
108
104
|
role: "user",
|
|
109
105
|
content: [
|
|
110
106
|
`# Translation Request`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["AIProvider"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validatedContent,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;;AAgCA,MAAa,mBAA8B;CACzC,UAAUA,YAAW;CACrB,OAAO;CACR;;;;;;;AAQD,MAAM,wBAAwB,WAC5B,GAAG,OAAO,IAAI,cAAc,QAAQ,eAAe;;;;;;;;AASrD,MAAM,yBAAyB,SAAwB;AACrD,KAAI,CAAC,QAAQ,KAAK,WAAW,EAC3B,QAAO;AAIT,QAAO;;EAEP,KAAK,KAAK,EAAE,KAAK,kBAAkB,KAAK,IAAI,IAAI,cAAc,CAAC,KAAK,OAAO;;AAG7E,MAAM,uBAAuB,SAAwC;AACnE,KAAI,SAAS,WACX,QAAO;AAGT,QAAO;;AAGT,MAAM,aAAa,YAA+B;AAEhD,KAA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ClD,QAAQ,2BAA2B,iBAAiB,CACpD,QAAQ,6BAA6B,yBAAyB,GAAG,CACjE,QAAQ,0BAA0B,sBAAsB,GAAG,CAC3D,QAAQ,wBAAwB,sBAAsB,QAAQ,EAAE,CAAC,CAAC,CAClE,QAAQ,wBAAwB,oBAAoB,KAAK,CAAC;AAE7D,KAAI,QAAQ;EACV,MAAM,EAAE,MAAM,UAAU,MAAM,aAAa;GACzC,GAAG;GACH,UAAU,CACR;IAAE,MAAM;IAAU,SAAS;IAAQ,EACnC;IACE,MAAM;IACN,SAAS;KACP;KACA;KACA,eAAe;KACf,aAAa;KACb;KACA;KACA;KACD,CAAC,KAAK,KAAK;IACb,CACF;GACF,CAAC;AAWF,SAAO;GACL,aALkB,OAJA,KACjB,QAAQ,qCAAqC,KAAK,CAClD,MAEmC,CAKZ;GACxB,WAAW,OAAO,eAAe;GAClC;;CAOH,MAAM,kBAJY,UAAU,iBAIK,IAAI;CAGrC,MAAM,EAAE,MAAM,UAAU,MAAM,aAAa;EACzC,GAAG;EAGH,QAAQ,kBAAkB,OAAO,OAAO,EAAE,QAAQ,CAAC,GAAG;EACtD,UAAU,CACR;GAAE,MAAM;GAAU,SAAS;GAAQ,EACnC;GACE,MAAM;GACN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACD,CAAC,KAAK,KAAK;GACb,CACF;EACF,CAAC;CAGF,MAAM,gBAAgB,YAAY,KAAK;AAGvC,QAAO;EACL,aAHuB,OAAO,MAAM,cAGP;EAC7B,WAAW,OAAO,eAAe;EAClC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["AIProvider"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\nimport { extractJson } from '../utils/extractJSON';\n\ntype Tag = {\n key: string;\n description?: string;\n};\n\nexport type TranslateJSONOptions<T = JSON> = {\n entryFileContent: T;\n presetOutputContent: Partial<T>;\n dictionaryDescription?: string;\n entryLocale: Locale;\n outputLocale: Locale;\n tags?: Tag[];\n aiConfig: AIConfig;\n mode: 'complete' | 'review';\n applicationContext?: string;\n};\n\nexport type TranslateJSONResultData<T = JSON> = {\n fileContent: T;\n tokenUsed: number;\n};\n\nexport const aiDefaultOptions: AIOptions = {\n provider: AIProvider.OPENAI,\n model: 'gpt-5-mini',\n};\n\n/**\n * Format a locale with its name.\n *\n * @param locale - The locale to format.\n * @returns A string in the format \"locale: name\", e.g. \"en: English\".\n */\nconst formatLocaleWithName = (locale: Locale): string =>\n `${locale}: ${getLocaleName(locale, DEFAULT_LOCALE)}`;\n\n/**\n * Formats tag instructions for the AI prompt.\n * Creates a string with all available tags and their descriptions.\n *\n * @param tags - The list of tags to format.\n * @returns A formatted string with tag instructions.\n */\nconst formatTagInstructions = (tags: Tag[]): string => {\n if (!tags || tags.length === 0) {\n return '';\n }\n\n // Prepare the tag instructions.\n return `Based on the dictionary content, identify specific tags from the list below that would be relevant:\n \n${tags.map(({ key, description }) => `- ${key}: ${description}`).join('\\n\\n')}`;\n};\n\nconst getModeInstructions = (mode: 'complete' | 'review'): string => {\n if (mode === 'complete') {\n return 'Mode: \"Complete\" - Enrich the preset content with the missing keys and values in the output locale. Do not update existing keys. Everything should be returned in the output.';\n }\n\n return 'Mode: \"Review\" - Fill missing content and review existing keys from the preset content. If a key from the entry is missing in the output, it must be translated to the target language and added. If you detect misspelled content, or content that should be reformulated, correct it. If a translation is not coherent with the desired language, translate it.';\n};\n\nconst jsonToZod = (content: any): z.ZodTypeAny => {\n // Base case: content is a string (the translation target)\n if (typeof content === 'string') {\n return z.string();\n }\n\n // Base cases: primitives often preserved in i18n files (e.g. strict numbers/booleans)\n if (typeof content === 'number') {\n return z.number();\n }\n if (typeof content === 'boolean') {\n return z.boolean();\n }\n\n // Recursive case: Array\n if (Array.isArray(content)) {\n // If array is empty, we assume array of strings as default for i18n\n if (content.length === 0) {\n return z.array(z.string());\n }\n // We assume all items in the array share the structure of the first item\n return z.array(jsonToZod(content[0]));\n }\n\n // Recursive case: Object\n if (typeof content === 'object' && content !== null) {\n const shape: Record<string, z.ZodTypeAny> = {};\n for (const key in content) {\n shape[key] = jsonToZod(content[key]);\n }\n return z.object(shape);\n }\n\n // Fallback\n return z.string();\n};\n\nconst countKeys = (obj: any): number => {\n if (typeof obj !== 'object' || obj === null) return 0;\n let count = 0;\n for (const key in obj) {\n count += 1 + countKeys(obj[key]);\n }\n return count;\n};\n\n/**\n * TranslateJSONs a content declaration file by constructing a prompt for AI models.\n * The prompt includes details about the project's locales, file paths of content declarations,\n * and requests for identifying issues or inconsistencies.\n */\nexport const translateJSON = async <T>({\n entryFileContent,\n presetOutputContent,\n dictionaryDescription,\n aiConfig,\n entryLocale,\n outputLocale,\n tags,\n mode,\n applicationContext,\n}: TranslateJSONOptions<T>): Promise<\n TranslateJSONResultData<T> | undefined\n> => {\n const { dataSerialization, ...restAiConfig } = aiConfig;\n const { output: _unusedOutput, ...validAiConfig } = restAiConfig;\n\n const formattedEntryLocale = formatLocaleWithName(entryLocale);\n const formattedOutputLocale = formatLocaleWithName(outputLocale);\n\n const isToon = dataSerialization === 'toon';\n const promptFile = readAsset(\n isToon ? './PROMPT_TOON.md' : './PROMPT_JSON.md'\n );\n const entryContentStr = isToon\n ? encode(entryFileContent)\n : JSON.stringify(entryFileContent);\n const presetContentStr = isToon\n ? encode(presetOutputContent)\n : JSON.stringify(presetOutputContent);\n\n const schema = jsonToZod(entryFileContent);\n\n // Prepare the prompt for AI by replacing placeholders with actual values.\n const prompt = promptFile\n .replace('{{entryLocale}}', formattedEntryLocale)\n .replace('{{outputLocale}}', formattedOutputLocale)\n .replace('{{presetOutputContent}}', presetContentStr)\n .replace('{{dictionaryDescription}}', dictionaryDescription ?? '')\n .replace('{{applicationContext}}', applicationContext ?? '')\n .replace('{{tagsInstructions}}', formatTagInstructions(tags ?? []))\n .replace('{{modeInstructions}}', getModeInstructions(mode));\n\n if (isToon) {\n const { text, usage } = await generateText({\n ...aiConfig,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following TOON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Strip markdown code blocks if present\n const cleanedText = text\n .replace(/^```(?:toon)?\\n([\\s\\S]*?)\\n```$/gm, '$1')\n .trim();\n\n const decodedJson = decode(cleanedText) as T;\n\n // schema.parse(decodedJson);\n\n return {\n fileContent: decodedJson,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n const totalKeys = countKeys(entryFileContent);\n\n const MAX_SAFE_KEYS = 70; // You will need to tune this threshold based on testing\n\n const useStrictOutput = totalKeys <= MAX_SAFE_KEYS;\n\n // Use the AI SDK to generate the completion\n const { text, usage } = await generateText({\n ...validAiConfig,\n\n // Disable schema if Schema is too complex (Block with Anthropic)\n output: useStrictOutput ? Output.object({ schema }) : undefined,\n system: prompt,\n messages: [\n {\n role: 'user',\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `CRITICAL INSTRUCTIONS:`,\n `- You MUST return ONLY raw, valid JSON.`,\n `- DO NOT wrap the response in Markdown code blocks (e.g., no \\`\\`\\`json).`,\n `- DO NOT include any conversational text before or after the JSON object.`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n // Extract and re-validate deeply\n const extractedJSON = extractJson(text);\n const validatedContent = schema.parse(extractedJSON) as T;\n\n return {\n fileContent: validat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Aa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACD,CAAC,KAAK,KAAK;GACb,CACF;EACF,CAAC;CAGF,MAAM,gBAAgB,YAAY,KAAK;AAGvC,QAAO;EACL,aAHuB,OAAO,MAAM,cAGP;EAC7B,WAAW,OAAO,eAAe;EAClC"}
|
package/dist/types/aiSdk.d.ts
CHANGED
|
@@ -41,7 +41,8 @@ type GroqProviderOptions = Parameters<typeof createGroq>[0];
|
|
|
41
41
|
type HuggingFaceProviderOptions = Parameters<typeof createHuggingFace>[0];
|
|
42
42
|
type AmazonBedrockProviderOptions = Parameters<typeof createAmazonBedrock>[0];
|
|
43
43
|
type TogetherAIProviderOptions = Parameters<typeof createTogetherAI>[0];
|
|
44
|
-
type
|
|
44
|
+
type SystemMessage = string | SystemModelMessage | SystemModelMessage[] | undefined;
|
|
45
|
+
type Messages = (UserModelMessage | AssistantModelMessage | ToolModelMessage)[];
|
|
45
46
|
/**
|
|
46
47
|
* Supported AI models
|
|
47
48
|
*/
|
|
@@ -130,5 +131,5 @@ declare const checkAISDKAccess: (aiConfig: AIConfig) => Promise<{
|
|
|
130
131
|
*/
|
|
131
132
|
declare const getAIConfig: (options: AIConfigOptions, isAuthenticated?: boolean) => Promise<AIConfig>;
|
|
132
133
|
//#endregion
|
|
133
|
-
export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig };
|
|
134
|
+
export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig };
|
|
134
135
|
//# sourceMappingURL=aiSdk.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aiSdk.d.ts","names":[],"sources":["../../src/aiSdk.ts"],"mappings":";;;;;;;;;;;;;;;;;KA8CK,cAAA,GAAiB,UAAA,CAAW,iBAAA;AAAA,KAC5B,aAAA,GAAgB,UAAA,CAAW,gBAAA;AAAA,KAC3B,YAAA,GAAe,UAAA,CAAW,eAAA;AAAA,KAC1B,WAAA,GAAc,UAAA,CAAW,cAAA;AAAA,KACzB,eAAA,GAAkB,UAAA,CAAW,kBAAA;AAAA,KAC7B,WAAA,GAAc,UAAA,CAAW,0BAAA;AAAA,KACzB,WAAA,GAAc,UAAA,CAAW,oBAAA;AAAA,KACzB,YAAA,GAAe,UAAA,CAAW,eAAA;AAAA,KAC1B,kBAAA,GAAqB,UAAA,CAAW,qBAAA;AAAA,KAChC,cAAA,GAAiB,UAAA,CAAW,iBAAA;AAAA,KAC5B,SAAA,GAAY,UAAA,CAAW,YAAA;AAAA,KACvB,gBAAA,GAAmB,UAAA,CAAW,mBAAA;AAAA,KAC9B,eAAA,GAAkB,UAAA,CAAW,kBAAA;AAAA,KAEtB,qBAAA,GAAwB,UAAA,QAAkB,YAAA;AAAA,KAC1C,wBAAA,GAA2B,UAAA,QAAkB,eAAA;AAAA,KAC7C,sBAAA,GAAyB,UAAA,QAAkB,aAAA;AAAA,KAC3C,uBAAA,GAA0B,UAAA,QAAkB,cAAA;AAAA,KAC5C,qBAAA,GAAwB,UAAA,QAC3B,wBAAA;AAAA,KAEG,qBAAA,GAAwB,UAAA,QAAkB,YAAA;AAAA,KAC1C,yBAAA,GAA4B,UAAA,QAAkB,gBAAA;AAA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EACT,eAAA,eACC,OAAA,CAAQ,QAAA"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { AIConfig, AIOptions, Messages } from "./aiSdk.js";
|
|
2
|
+
import { SystemModelMessage } from "ai";
|
|
2
3
|
|
|
3
4
|
//#region src/customQuery.d.ts
|
|
4
5
|
type CustomQueryOptions = {
|
|
5
6
|
messages: Messages;
|
|
7
|
+
system?: string | SystemModelMessage | SystemModelMessage[];
|
|
6
8
|
aiConfig: AIConfig;
|
|
7
9
|
};
|
|
8
10
|
type CustomQueryResultData = {
|
|
@@ -17,6 +19,7 @@ declare const aiDefaultOptions: AIOptions;
|
|
|
17
19
|
*/
|
|
18
20
|
declare const customQuery: ({
|
|
19
21
|
messages,
|
|
22
|
+
system,
|
|
20
23
|
aiConfig
|
|
21
24
|
}: CustomQueryOptions) => Promise<CustomQueryResultData | undefined>;
|
|
22
25
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"customQuery.d.ts","names":[],"sources":["../../src/customQuery.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"customQuery.d.ts","names":[],"sources":["../../src/customQuery.ts"],"mappings":";;;;KAGY,kBAAA;EACV,QAAA,EAAU,QAAA;EACV,MAAA,YAAkB,kBAAA,GAAqB,kBAAA;EACvC,QAAA,EAAU,QAAA;AAAA;AAAA,KAGA,qBAAA;EACV,WAAA;EACA,SAAA;AAAA;AAAA,cAGW,gBAAA,EAAkB,SAAA;;;;;;cAUlB,WAAA;EAAqB,QAAA;EAAA,MAAA;EAAA;AAAA,GAI/B,kBAAA,KAAqB,OAAA,CAAQ,qBAAA"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AIConfig, AIConfigOptions, AIOptions, AIProvider as AiProviders, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig } from "./aiSdk.js";
|
|
1
|
+
import { AIConfig, AIConfigOptions, AIOptions, AIProvider as AiProviders, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, ChatCompletionRequestMessage, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, VertexProviderOptions, checkAISDKAccess, getAIConfig } from "./aiSdk.js";
|
|
2
2
|
import { AuditDictionaryMetadataOptions, AuditFileResultData, auditDictionaryMetadata } from "./auditDictionaryMetadata/index.js";
|
|
3
3
|
import { CustomQueryOptions, CustomQueryResultData, customQuery } from "./customQuery.js";
|
|
4
4
|
import { TranslateJSONOptions, TranslateJSONResultData, translateJSON } from "./translateJSON/index.js";
|
|
@@ -25,5 +25,5 @@ declare module '@intlayer/types/config' {
|
|
|
25
25
|
}
|
|
26
26
|
} //# sourceMappingURL=index.d.ts.map
|
|
27
27
|
//#endregion
|
|
28
|
-
export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, type AuditDictionaryMetadataOptions, type AuditFileResultData, ChatCompletionRequestMessage, type CustomQueryOptions, type CustomQueryResultData, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, TogetherAIProviderOptions, type TranslateJSONOptions, type TranslateJSONResultData, VertexProviderOptions, auditDictionaryMetadata, checkAISDKAccess, customQuery, extractJson, generateText, getAIConfig, streamText, translateJSON };
|
|
28
|
+
export { AIConfig, AIConfigOptions, AIOptions, AiProviders as AIProvider, AlibabaProviderOptions, AmazonBedrockProviderOptions, AnthropicProviderOptions, type AuditDictionaryMetadataOptions, type AuditFileResultData, ChatCompletionRequestMessage, type CustomQueryOptions, type CustomQueryResultData, DeepSeekProviderOptions, FireworksProviderOptions, GoogleProviderOptions, GroqProviderOptions, HuggingFaceProviderOptions, Messages, MistralProviderOptions, Model, OpenAIProviderOptions, OpenRouterProviderOptions, ReasoningEffort, SystemMessage, TogetherAIProviderOptions, type TranslateJSONOptions, type TranslateJSONResultData, VertexProviderOptions, auditDictionaryMetadata, checkAISDKAccess, customQuery, extractJson, generateText, getAIConfig, streamText, translateJSON };
|
|
29
29
|
//# sourceMappingURL=index.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/ai",
|
|
3
|
-
"version": "8.7.
|
|
3
|
+
"version": "8.7.14",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "SDK that provides AI capabilities for Intlayer applications",
|
|
6
6
|
"keywords": [
|
|
@@ -72,29 +72,29 @@
|
|
|
72
72
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@ai-sdk/anthropic": "3.0.
|
|
76
|
-
"@ai-sdk/google": "3.0.
|
|
77
|
-
"@ai-sdk/openai": "3.0.
|
|
78
|
-
"@intlayer/api": "8.7.
|
|
79
|
-
"@intlayer/config": "8.7.
|
|
80
|
-
"@intlayer/core": "8.7.
|
|
81
|
-
"@intlayer/types": "8.7.
|
|
75
|
+
"@ai-sdk/anthropic": "3.0.74",
|
|
76
|
+
"@ai-sdk/google": "3.0.67",
|
|
77
|
+
"@ai-sdk/openai": "3.0.58",
|
|
78
|
+
"@intlayer/api": "8.7.14",
|
|
79
|
+
"@intlayer/config": "8.7.14",
|
|
80
|
+
"@intlayer/core": "8.7.14",
|
|
81
|
+
"@intlayer/types": "8.7.14",
|
|
82
82
|
"@toon-format/toon": "2.1.0",
|
|
83
|
-
"ai": "6.0.
|
|
84
|
-
"zod": "4.
|
|
83
|
+
"ai": "6.0.174",
|
|
84
|
+
"zod": "4.4.2"
|
|
85
85
|
},
|
|
86
86
|
"devDependencies": {
|
|
87
|
-
"@ai-sdk/alibaba": "1.0.
|
|
88
|
-
"@ai-sdk/amazon-bedrock": "4.0.
|
|
89
|
-
"@ai-sdk/deepseek": "2.0.
|
|
90
|
-
"@ai-sdk/fireworks": "2.0.
|
|
91
|
-
"@ai-sdk/google": "3.0.
|
|
92
|
-
"@ai-sdk/google-vertex": "^4.0.
|
|
93
|
-
"@ai-sdk/groq": "3.0.
|
|
94
|
-
"@ai-sdk/huggingface": "1.0.
|
|
95
|
-
"@ai-sdk/mistral": "3.0.
|
|
96
|
-
"@ai-sdk/togetherai": "2.0.
|
|
97
|
-
"@openrouter/ai-sdk-provider": "2.
|
|
87
|
+
"@ai-sdk/alibaba": "1.0.21",
|
|
88
|
+
"@ai-sdk/amazon-bedrock": "4.0.100",
|
|
89
|
+
"@ai-sdk/deepseek": "2.0.32",
|
|
90
|
+
"@ai-sdk/fireworks": "2.0.50",
|
|
91
|
+
"@ai-sdk/google": "3.0.67",
|
|
92
|
+
"@ai-sdk/google-vertex": "^4.0.118",
|
|
93
|
+
"@ai-sdk/groq": "3.0.38",
|
|
94
|
+
"@ai-sdk/huggingface": "1.0.47",
|
|
95
|
+
"@ai-sdk/mistral": "3.0.33",
|
|
96
|
+
"@ai-sdk/togetherai": "2.0.49",
|
|
97
|
+
"@openrouter/ai-sdk-provider": "2.9.0",
|
|
98
98
|
"@types/node": "25.6.0",
|
|
99
99
|
"@utils/ts-config": "1.0.4",
|
|
100
100
|
"@utils/ts-config-types": "1.0.4",
|
|
@@ -105,17 +105,17 @@
|
|
|
105
105
|
"vitest": "4.1.5"
|
|
106
106
|
},
|
|
107
107
|
"peerDependencies": {
|
|
108
|
-
"@ai-sdk/alibaba": "1.0.
|
|
109
|
-
"@ai-sdk/amazon-bedrock": "4.0.
|
|
110
|
-
"@ai-sdk/deepseek": "2.0.
|
|
111
|
-
"@ai-sdk/fireworks": "2.0.
|
|
112
|
-
"@ai-sdk/google": "3.0.
|
|
113
|
-
"@ai-sdk/google-vertex": "^4.0.
|
|
114
|
-
"@ai-sdk/groq": "3.0.
|
|
115
|
-
"@ai-sdk/huggingface": "1.0.
|
|
116
|
-
"@ai-sdk/mistral": "3.0.
|
|
117
|
-
"@ai-sdk/togetherai": "2.0.
|
|
118
|
-
"@openrouter/ai-sdk-provider": "2.
|
|
108
|
+
"@ai-sdk/alibaba": "1.0.21",
|
|
109
|
+
"@ai-sdk/amazon-bedrock": "4.0.100",
|
|
110
|
+
"@ai-sdk/deepseek": "2.0.32",
|
|
111
|
+
"@ai-sdk/fireworks": "2.0.50",
|
|
112
|
+
"@ai-sdk/google": "3.0.67",
|
|
113
|
+
"@ai-sdk/google-vertex": "^4.0.118",
|
|
114
|
+
"@ai-sdk/groq": "3.0.38",
|
|
115
|
+
"@ai-sdk/huggingface": "1.0.47",
|
|
116
|
+
"@ai-sdk/mistral": "3.0.33",
|
|
117
|
+
"@ai-sdk/togetherai": "2.0.49",
|
|
118
|
+
"@openrouter/ai-sdk-provider": "2.9.0"
|
|
119
119
|
},
|
|
120
120
|
"peerDependenciesMeta": {
|
|
121
121
|
"@ai-sdk/alibaba": {
|