@intlayer/ai 8.1.2 → 8.1.3

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.
@@ -1,120 +1,8 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require__utils_asset = require('../_virtual/_utils_asset.cjs');
3
- let _intlayer_types = require("@intlayer/types");
4
- let ai = require("ai");
5
- let zod = require("zod");
6
- let _intlayer_core = require("@intlayer/core");
7
- let _toon_format_toon = require("@toon-format/toon");
8
-
9
- //#region src/translateJSON/index.ts
10
- const aiDefaultOptions = {
11
- provider: _intlayer_types.AiProviders.OPENAI,
12
- model: "gpt-5-mini"
13
- };
14
- /**
15
- * Format a locale with its name.
16
- *
17
- * @param locale - The locale to format.
18
- * @returns A string in the format "locale: name", e.g. "en: English".
19
- */
20
- const formatLocaleWithName = (locale) => `${locale}: ${(0, _intlayer_core.getLocaleName)(locale, _intlayer_types.Locales.ENGLISH)}`;
21
- /**
22
- * Formats tag instructions for the AI prompt.
23
- * Creates a string with all available tags and their descriptions.
24
- *
25
- * @param tags - The list of tags to format.
26
- * @returns A formatted string with tag instructions.
27
- */
28
- const formatTagInstructions = (tags) => {
29
- if (!tags || tags.length === 0) return "";
30
- return `Based on the dictionary content, identify specific tags from the list below that would be relevant:
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_utils_asset.cjs`);let t=require(`@intlayer/types`),n=require(`ai`),r=require(`zod`),i=require(`@intlayer/core/localization`),a=require(`@toon-format/toon`);const o={provider:t.AiProviders.OPENAI,model:`gpt-5-mini`},s=e=>`${e}: ${(0,i.getLocaleName)(e,t.Locales.ENGLISH)}`,c=e=>!e||e.length===0?``:`Based on the dictionary content, identify specific tags from the list below that would be relevant:
31
2
 
32
- ${tags.map(({ key, description }) => `- ${key}: ${description}`).join("\n\n")}`;
33
- };
34
- const getModeInstructions = (mode) => {
35
- if (mode === "complete") 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.";
36
- 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.";
37
- };
38
- const jsonToZod = (content) => {
39
- if (typeof content === "string") return zod.z.string();
40
- if (typeof content === "number") return zod.z.number();
41
- if (typeof content === "boolean") return zod.z.boolean();
42
- if (Array.isArray(content)) {
43
- if (content.length === 0) return zod.z.array(zod.z.string());
44
- return zod.z.array(jsonToZod(content[0]));
45
- }
46
- if (typeof content === "object" && content !== null) {
47
- const shape = {};
48
- for (const key in content) shape[key] = jsonToZod(content[key]);
49
- return zod.z.object(shape);
50
- }
51
- return zod.z.any();
52
- };
53
- /**
54
- * TranslateJSONs a content declaration file by constructing a prompt for AI models.
55
- * The prompt includes details about the project's locales, file paths of content declarations,
56
- * and requests for identifying issues or inconsistencies.
57
- */
58
- const translateJSON = async ({ entryFileContent, presetOutputContent, dictionaryDescription, aiConfig, entryLocale, outputLocale, tags, mode, applicationContext }) => {
59
- const { dataSerialization, ...restAiConfig } = aiConfig;
60
- const { output: _unusedOutput, ...validAiConfig } = restAiConfig;
61
- const formattedEntryLocale = formatLocaleWithName(entryLocale);
62
- const formattedOutputLocale = formatLocaleWithName(outputLocale);
63
- const isToon = dataSerialization === "toon";
64
- const promptFile = require__utils_asset.readAsset(isToon ? "./PROMPT_TOON.md" : "./PROMPT_JSON.md");
65
- const entryContentStr = isToon ? (0, _toon_format_toon.encode)(entryFileContent) : JSON.stringify(entryFileContent);
66
- const presetContentStr = isToon ? (0, _toon_format_toon.encode)(presetOutputContent) : JSON.stringify(presetOutputContent);
67
- const prompt = promptFile.replace("{{entryLocale}}", formattedEntryLocale).replace("{{outputLocale}}", formattedOutputLocale).replace("{{presetOutputContent}}", presetContentStr).replace("{{dictionaryDescription}}", dictionaryDescription ?? "").replace("{{applicationContext}}", applicationContext ?? "").replace("{{tagsInstructions}}", formatTagInstructions(tags ?? [])).replace("{{modeInstructions}}", getModeInstructions(mode));
68
- if (isToon) {
69
- const { text, usage } = await (0, ai.generateText)({
70
- ...aiConfig,
71
- messages: [{
72
- role: "system",
73
- content: prompt
74
- }, {
75
- role: "user",
76
- content: [
77
- `# Translation Request`,
78
- `Please translate the following TOON content.`,
79
- `- **From:** ${formattedEntryLocale}`,
80
- `- **To:** ${formattedOutputLocale}`,
81
- ``,
82
- `## Entry Content:`,
83
- entryContentStr
84
- ].join("\n")
85
- }]
86
- });
87
- return {
88
- fileContent: (0, _toon_format_toon.decode)(text.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm, "$1").trim()),
89
- tokenUsed: usage?.totalTokens ?? 0
90
- };
91
- }
92
- const { output, usage } = await (0, ai.generateText)({
93
- ...validAiConfig,
94
- output: ai.Output.object({ schema: jsonToZod(entryFileContent) }),
95
- messages: [{
96
- role: "system",
97
- content: prompt
98
- }, {
99
- role: "user",
100
- content: [
101
- `# Translation Request`,
102
- `Please translate the following JSON content.`,
103
- `- **From:** ${formattedEntryLocale}`,
104
- `- **To:** ${formattedOutputLocale}`,
105
- ``,
106
- `## Entry Content:`,
107
- entryContentStr
108
- ].join("\n")
109
- }]
110
- });
111
- return {
112
- fileContent: output,
113
- tokenUsed: usage?.totalTokens ?? 0
114
- };
115
- };
3
+ ${e.map(({key:e,description:t})=>`- ${e}: ${t}`).join(`
116
4
 
117
- //#endregion
118
- exports.aiDefaultOptions = aiDefaultOptions;
119
- exports.translateJSON = translateJSON;
5
+ `)}`,l=e=>e===`complete`?`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.`:`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.`,u=e=>{if(typeof e==`string`)return r.z.string();if(typeof e==`number`)return r.z.number();if(typeof e==`boolean`)return r.z.boolean();if(Array.isArray(e))return e.length===0?r.z.array(r.z.string()):r.z.array(u(e[0]));if(typeof e==`object`&&e){let t={};for(let n in e)t[n]=u(e[n]);return r.z.object(t)}return r.z.any()},d=async({entryFileContent:t,presetOutputContent:r,dictionaryDescription:i,aiConfig:o,entryLocale:d,outputLocale:f,tags:p,mode:m,applicationContext:h})=>{let{dataSerialization:g,..._}=o,{output:v,...y}=_,b=s(d),x=s(f),S=g===`toon`,C=e.readAsset(S?`./PROMPT_TOON.md`:`./PROMPT_JSON.md`),w=S?(0,a.encode)(t):JSON.stringify(t),T=S?(0,a.encode)(r):JSON.stringify(r),E=C.replace(`{{entryLocale}}`,b).replace(`{{outputLocale}}`,x).replace(`{{presetOutputContent}}`,T).replace(`{{dictionaryDescription}}`,i??``).replace(`{{applicationContext}}`,h??``).replace(`{{tagsInstructions}}`,c(p??[])).replace(`{{modeInstructions}}`,l(m));if(S){let{text:e,usage:t}=await(0,n.generateText)({...o,messages:[{role:`system`,content:E},{role:`user`,content:[`# Translation Request`,`Please translate the following TOON content.`,`- **From:** ${b}`,`- **To:** ${x}`,``,`## Entry Content:`,w].join(`
6
+ `)}]});return{fileContent:(0,a.decode)(e.replace(/^```(?:toon)?\n([\s\S]*?)\n```$/gm,`$1`).trim()),tokenUsed:t?.totalTokens??0}}let{output:D,usage:O}=await(0,n.generateText)({...y,output:n.Output.object({schema:u(t)}),messages:[{role:`system`,content:E},{role:`user`,content:[`# Translation Request`,`Please translate the following JSON content.`,`- **From:** ${b}`,`- **To:** ${x}`,``,`## Entry Content:`,w].join(`
7
+ `)}]});return{fileContent:D,tokenUsed:O?.totalTokens??0}};exports.aiDefaultOptions=o,exports.translateJSON=d;
120
8
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["AIProvider","Locales","z","readAsset","Output"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { getLocaleName } from '@intlayer/core';\nimport { type Locale, Locales } from '@intlayer/types';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\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, Locales.ENGLISH)}`;\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.any();\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 // @ts-ignore\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 // 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 return {\n fileContent: decode(cleanedText) as T,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: jsonToZod(entryFileContent),\n }),\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n // KEY CHANGE: Explicitly repeating instructions in the user message\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n return {\n fileContent: output as T,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":";;;;;;;;;AA8BA,MAAa,mBAA8B;CACzC,UAAUA,4BAAW;CACrB,OAAO;CACR;;;;;;;AAQD,MAAM,wBAAwB,WAC5B,GAAG,OAAO,sCAAkB,QAAQC,wBAAQ,QAAQ;;;;;;;;AAStD,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,KAAK;;;;;;;AAQhB,MAAa,gBAAgB,OAAU,EACrC,kBACA,qBACA,uBACA,UACA,aACA,cACA,MACA,MACA,yBAGG;CACH,MAAM,EAAE,mBAAmB,GAAG,iBAAiB;CAE/C,MAAM,EAAE,QAAQ,eAAe,GAAG,kBAAkB;CAEpD,MAAM,uBAAuB,qBAAqB,YAAY;CAC9D,MAAM,wBAAwB,qBAAqB,aAAa;CAEhE,MAAM,SAAS,sBAAsB;CACrC,MAAM,aAAaC,+BACjB,SAAS,qBAAqB,mBAC/B;CACD,MAAM,kBAAkB,uCACb,iBAAiB,GACxB,KAAK,UAAU,iBAAiB;CACpC,MAAM,mBAAmB,uCACd,oBAAoB,GAC3B,KAAK,UAAU,oBAAoB;CAGvC,MAAM,SAAS,WACZ,QAAQ,mBAAmB,qBAAqB,CAChD,QAAQ,oBAAoB,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,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;AAOF,SAAO;GACL,2CALkB,KACjB,QAAQ,qCAAqC,KAAK,CAClD,MAAM,CAGyB;GAChC,WAAW,OAAO,eAAe;GAClC;;CAIH,MAAM,EAAE,QAAQ,UAAU,2BAAmB;EAC3C,GAAG;EACH,QAAQC,UAAO,OAAO,EACpB,QAAQ,UAAU,iBAAiB,EACpC,CAAC;EACF,UAAU,CACR;GAAE,MAAM;GAAU,SAAS;GAAQ,EACnC;GACE,MAAM;GAEN,SAAS;IACP;IACA;IACA,eAAe;IACf,aAAa;IACb;IACA;IACA;IACD,CAAC,KAAK,KAAK;GACb,CACF;EACF,CAAC;AAEF,QAAO;EACL,aAAa;EACb,WAAW,OAAO,eAAe;EAClC"}
1
+ {"version":3,"file":"index.cjs","names":["AIProvider","Locales","z","readAsset","Output"],"sources":["../../../src/translateJSON/index.ts"],"sourcesContent":["import { readAsset } from 'utils:asset';\nimport { getLocaleName } from '@intlayer/core/localization';\nimport { type Locale, Locales } from '@intlayer/types';\nimport { decode, encode } from '@toon-format/toon';\nimport { generateText, Output } from 'ai';\nimport { z } from 'zod';\nimport { type AIConfig, type AIOptions, AIProvider } from '../aiSdk';\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, Locales.ENGLISH)}`;\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.any();\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 // @ts-ignore\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 // 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 return {\n fileContent: decode(cleanedText) as T,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n }\n\n // Use the AI SDK to generate the completion\n const { output, usage } = await generateText({\n ...validAiConfig,\n output: Output.object({\n schema: jsonToZod(entryFileContent),\n }),\n messages: [\n { role: 'system', content: prompt },\n {\n role: 'user',\n // KEY CHANGE: Explicitly repeating instructions in the user message\n content: [\n `# Translation Request`,\n `Please translate the following JSON content.`,\n `- **From:** ${formattedEntryLocale}`,\n `- **To:** ${formattedOutputLocale}`,\n ``,\n `## Entry Content:`,\n entryContentStr,\n ].join('\\n'),\n },\n ],\n });\n\n return {\n fileContent: output as T,\n tokenUsed: usage?.totalTokens ?? 0,\n };\n};\n"],"mappings":"6PA8BA,MAAa,EAA8B,CACzC,SAAUA,EAAAA,YAAW,OACrB,MAAO,aACR,CAQK,EAAwB,GAC5B,GAAG,EAAO,KAAA,EAAA,EAAA,eAAkB,EAAQC,EAAAA,QAAQ,QAAQ,GAShD,EAAyB,GACzB,CAAC,GAAQ,EAAK,SAAW,EACpB,GAIF;;EAEP,EAAK,KAAK,CAAE,MAAK,iBAAkB,KAAK,EAAI,IAAI,IAAc,CAAC,KAAK;;EAAO,GAGvE,EAAuB,GACvB,IAAS,WACJ,gLAGF,oWAGH,EAAa,GAA+B,CAEhD,GAAI,OAAO,GAAY,SACrB,OAAOC,EAAAA,EAAE,QAAQ,CAInB,GAAI,OAAO,GAAY,SACrB,OAAOA,EAAAA,EAAE,QAAQ,CAEnB,GAAI,OAAO,GAAY,UACrB,OAAOA,EAAAA,EAAE,SAAS,CAIpB,GAAI,MAAM,QAAQ,EAAQ,CAMxB,OAJI,EAAQ,SAAW,EACdA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,QAAQ,CAAC,CAGrBA,EAAAA,EAAE,MAAM,EAAU,EAAQ,GAAG,CAAC,CAIvC,GAAI,OAAO,GAAY,UAAY,EAAkB,CACnD,IAAM,EAAsC,EAAE,CAC9C,IAAK,IAAM,KAAO,EAChB,EAAM,GAAO,EAAU,EAAQ,GAAK,CAEtC,OAAOA,EAAAA,EAAE,OAAO,EAAM,CAIxB,OAAOA,EAAAA,EAAE,KAAK,EAQH,EAAgB,MAAU,CACrC,mBACA,sBACA,wBACA,WACA,cACA,eACA,OACA,OACA,wBAGG,CACH,GAAM,CAAE,oBAAmB,GAAG,GAAiB,EAEzC,CAAE,OAAQ,EAAe,GAAG,GAAkB,EAE9C,EAAuB,EAAqB,EAAY,CACxD,EAAwB,EAAqB,EAAa,CAE1D,EAAS,IAAsB,OAC/B,EAAaC,EAAAA,UACjB,EAAS,mBAAqB,mBAC/B,CACK,EAAkB,GAAA,EAAA,EAAA,QACb,EAAiB,CACxB,KAAK,UAAU,EAAiB,CAC9B,EAAmB,GAAA,EAAA,EAAA,QACd,EAAoB,CAC3B,KAAK,UAAU,EAAoB,CAGjC,EAAS,EACZ,QAAQ,kBAAmB,EAAqB,CAChD,QAAQ,mBAAoB,EAAsB,CAClD,QAAQ,0BAA2B,EAAiB,CACpD,QAAQ,4BAA6B,GAAyB,GAAG,CACjE,QAAQ,yBAA0B,GAAsB,GAAG,CAC3D,QAAQ,uBAAwB,EAAsB,GAAQ,EAAE,CAAC,CAAC,CAClE,QAAQ,uBAAwB,EAAoB,EAAK,CAAC,CAE7D,GAAI,EAAQ,CACV,GAAM,CAAE,OAAM,SAAU,MAAA,EAAA,EAAA,cAAmB,CACzC,GAAG,EACH,SAAU,CACR,CAAE,KAAM,SAAU,QAAS,EAAQ,CACnC,CACE,KAAM,OACN,QAAS,CACP,wBACA,+CACA,eAAe,IACf,aAAa,IACb,GACA,oBACA,EACD,CAAC,KAAK;EAAK,CACb,CACF,CACF,CAAC,CAOF,MAAO,CACL,aAAA,EAAA,EAAA,QALkB,EACjB,QAAQ,oCAAqC,KAAK,CAClD,MAAM,CAGyB,CAChC,UAAW,GAAO,aAAe,EAClC,CAIH,GAAM,CAAE,SAAQ,SAAU,MAAA,EAAA,EAAA,cAAmB,CAC3C,GAAG,EACH,OAAQC,EAAAA,OAAO,OAAO,CACpB,OAAQ,EAAU,EAAiB,CACpC,CAAC,CACF,SAAU,CACR,CAAE,KAAM,SAAU,QAAS,EAAQ,CACnC,CACE,KAAM,OAEN,QAAS,CACP,wBACA,+CACA,eAAe,IACf,aAAa,IACb,GACA,oBACA,EACD,CAAC,KAAK;EAAK,CACb,CACF,CACF,CAAC,CAEF,MAAO,CACL,YAAa,EACb,UAAW,GAAO,aAAe,EAClC"}
@@ -1,62 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
- //#region src/utils/extractJSON.ts
4
- /**
5
- * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.
6
- * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.
7
- *
8
- * @example
9
- * // Extracts JSON object from markdown response:
10
- * ```json
11
- * {
12
- * "title": "Test content declarations",
13
- * "description": "A comprehensive test dictionary...",
14
- * "tags": ["test tag"]
15
- * }
16
- * ```
17
- *
18
- * @example
19
- * // Extracts JSON array:
20
- * ```json
21
- * ["item1", "item2", "item3"]
22
- * ```
23
- *
24
- * @example
25
- * // Extracts JSON from markdown:
26
- * Here is the response:
27
- * ```json
28
- * {"key": "value"}
29
- * ```
30
- * End of response.
31
- *
32
- * @throws {Error} If no valid JSON object/array is found or if parsing fails
33
- * @returns {T} The parsed JSON value cast to type T
34
- */
35
- const extractJson = (input) => {
36
- const opening = input.match(/[{[]/);
37
- if (!opening) throw new Error("No JSON start character ({ or [) found.");
38
- const startIdx = opening.index;
39
- const openChar = input[startIdx];
40
- const closeChar = openChar === "{" ? "}" : "]";
41
- let depth = 0;
42
- for (let i = startIdx; i < input.length; i++) {
43
- const char = input[i];
44
- if (char === openChar) depth++;
45
- else if (char === closeChar) {
46
- depth--;
47
- if (depth === 0) {
48
- const jsonSubstring = input.slice(startIdx, i + 1);
49
- try {
50
- return JSON.parse(jsonSubstring);
51
- } catch (err) {
52
- throw new Error(`Failed to parse JSON: ${err.message}`);
53
- }
54
- }
55
- }
56
- }
57
- throw new Error("Reached end of input without closing JSON bracket.");
58
- };
59
-
60
- //#endregion
61
- exports.extractJson = extractJson;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>{let t=e.match(/[{[]/);if(!t)throw Error(`No JSON start character ({ or [) found.`);let n=t.index,r=e[n],i=r===`{`?`}`:`]`,a=0;for(let t=n;t<e.length;t++){let o=e[t];if(o===r)a++;else if(o===i&&(a--,a===0)){let r=e.slice(n,t+1);try{return JSON.parse(r)}catch(e){throw Error(`Failed to parse JSON: ${e.message}`)}}}throw Error(`Reached end of input without closing JSON bracket.`)};exports.extractJson=e;
62
2
  //# sourceMappingURL=extractJSON.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"extractJSON.cjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n let depth = 0;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n if (char === openChar) depth++;\n else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,eAAwB,UAAqB;CACxD,MAAM,UAAU,MAAM,MAAM,OAAO;AACnC,KAAI,CAAC,QAAS,OAAM,IAAI,MAAM,0CAA0C;CAExE,MAAM,WAAW,QAAQ;CACzB,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,aAAa,MAAM,MAAM;CAC3C,IAAI,QAAQ;AAEZ,MAAK,IAAI,IAAI,UAAU,IAAI,MAAM,QAAQ,KAAK;EAC5C,MAAM,OAAO,MAAM;AACnB,MAAI,SAAS,SAAU;WACd,SAAS,WAAW;AAC3B;AACA,OAAI,UAAU,GAAG;IACf,MAAM,gBAAgB,MAAM,MAAM,UAAU,IAAI,EAAE;AAClD,QAAI;AACF,YAAO,KAAK,MAAM,cAAc;aACzB,KAAK;AACZ,WAAM,IAAI,MAAM,yBAA0B,IAAc,UAAU;;;;;AAM1E,OAAM,IAAI,MAAM,qDAAqD"}
1
+ {"version":3,"file":"extractJSON.cjs","names":[],"sources":["../../../src/utils/extractJSON.ts"],"sourcesContent":["/**\n * Extracts and parses the first valid JSON value (object or array) from a string containing arbitrary text.\n * This is used to safely extract JSON from LLM responses that may contain additional text or markdown.\n *\n * @example\n * // Extracts JSON object from markdown response:\n * ```json\n * {\n * \"title\": \"Test content declarations\",\n * \"description\": \"A comprehensive test dictionary...\",\n * \"tags\": [\"test tag\"]\n * }\n * ```\n *\n * @example\n * // Extracts JSON array:\n * ```json\n * [\"item1\", \"item2\", \"item3\"]\n * ```\n *\n * @example\n * // Extracts JSON from markdown:\n * Here is the response:\n * ```json\n * {\"key\": \"value\"}\n * ```\n * End of response.\n *\n * @throws {Error} If no valid JSON object/array is found or if parsing fails\n * @returns {T} The parsed JSON value cast to type T\n */\nexport const extractJson = <T = any>(input: string): T => {\n const opening = input.match(/[{[]/);\n if (!opening) throw new Error('No JSON start character ({ or [) found.');\n\n const startIdx = opening.index!;\n const openChar = input[startIdx];\n const closeChar = openChar === '{' ? '}' : ']';\n let depth = 0;\n\n for (let i = startIdx; i < input.length; i++) {\n const char = input[i];\n if (char === openChar) depth++;\n else if (char === closeChar) {\n depth--;\n if (depth === 0) {\n const jsonSubstring = input.slice(startIdx, i + 1);\n try {\n return JSON.parse(jsonSubstring) as T;\n } catch (err) {\n throw new Error(`Failed to parse JSON: ${(err as Error).message}`);\n }\n }\n }\n }\n\n throw new Error('Reached end of input without closing JSON bracket.');\n};\n"],"mappings":"mEA+BA,MAAa,EAAwB,GAAqB,CACxD,IAAM,EAAU,EAAM,MAAM,OAAO,CACnC,GAAI,CAAC,EAAS,MAAU,MAAM,0CAA0C,CAExE,IAAM,EAAW,EAAQ,MACnB,EAAW,EAAM,GACjB,EAAY,IAAa,IAAM,IAAM,IACvC,EAAQ,EAEZ,IAAK,IAAI,EAAI,EAAU,EAAI,EAAM,OAAQ,IAAK,CAC5C,IAAM,EAAO,EAAM,GACnB,GAAI,IAAS,EAAU,YACd,IAAS,IAChB,IACI,IAAU,GAAG,CACf,IAAM,EAAgB,EAAM,MAAM,EAAU,EAAI,EAAE,CAClD,GAAI,CACF,OAAO,KAAK,MAAM,EAAc,OACzB,EAAK,CACZ,MAAU,MAAM,yBAA0B,EAAc,UAAU,GAM1E,MAAU,MAAM,qDAAqD"}
@@ -1,97 +1,2 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
-
5
- //#region \0utils:asset
6
- const hereDirname = () => {
7
- try {
8
- return dirname(fileURLToPath(import.meta.url));
9
- } catch {
10
- return typeof __dirname !== "undefined" ? __dirname : process.cwd();
11
- }
12
- };
13
- const findDistRoot = (startDir) => {
14
- let dir = startDir;
15
- for (let i = 0; i < 12; i++) {
16
- if (basename(dir) === "dist") return dir;
17
- const parent = resolve(dir, "..");
18
- if (parent === dir) break;
19
- dir = parent;
20
- }
21
- return null;
22
- };
23
- const normalizeFrameFile = (file) => {
24
- if (!file) return null;
25
- try {
26
- if (file.startsWith("file://")) return fileURLToPath(file);
27
- } catch {}
28
- return file;
29
- };
30
- /**
31
- * Returns the directory of the *caller* module that invoked readAsset.
32
- * Prefers non-virtual frames; falls back to the first real frame.
33
- */
34
- const getCallerDir = () => {
35
- const prev = Error.prepareStackTrace;
36
- try {
37
- Error.prepareStackTrace = (_, structured) => structured;
38
- const err = /* @__PURE__ */ new Error();
39
- Error.captureStackTrace(err, getCallerDir);
40
- /** @type {import('node:vm').CallSite[]} */
41
- const frames = err.stack || [];
42
- const isVirtualPath = (p) => p.includes(`${sep}_virtual${sep}`) || p.includes("/_virtual/");
43
- for (const frame of frames) {
44
- const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
45
- if (!file) continue;
46
- if (file.includes("node:internal") || file.includes(`${sep}internal${sep}modules${sep}`)) continue;
47
- if (!isVirtualPath(file)) return dirname(file);
48
- }
49
- for (const frame of frames) {
50
- const file = normalizeFrameFile(typeof frame.getFileName === "function" ? frame.getFileName() : null);
51
- if (file) return dirname(file);
52
- }
53
- } catch {} finally {
54
- Error.prepareStackTrace = prev;
55
- }
56
- return hereDirname();
57
- };
58
- /**
59
- * Read an asset copied from src/** to dist/assets/**.
60
- * - './' or '../' is resolved relative to the *caller module's* emitted directory.
61
- * - otherwise, treat as src-relative.
62
- *
63
- * @param {string} relPath - e.g. './PROMPT.md' or 'utils/AI/askDocQuestion/embeddings/<fileKey>.json'
64
- * @param {BufferEncoding} [encoding='utf8']
65
- */
66
- const readAsset = (relPath, encoding = "utf8") => {
67
- const here = hereDirname();
68
- const distRoot = findDistRoot(here) ?? resolve(here, "..", "..", "dist");
69
- const assetsRoot = join(distRoot, "assets");
70
- const tried = [];
71
- /**
72
- * Transform dist/(esm|cjs)/... and _virtual/ prefix to clean subpath (Windows-safe)
73
- */
74
- const callerSubpath = relative(distRoot, getCallerDir()).split("\\").join("/").replace(/^(?:dist\/)?(?:esm|cjs)\//, "").replace(/^_virtual\//, "");
75
- if (relPath.startsWith("./") || relPath.startsWith("../")) {
76
- const fromCallerAbs = resolve(assetsRoot, callerSubpath, relPath);
77
- tried.push(fromCallerAbs);
78
- if (existsSync(fromCallerAbs)) return readFileSync(fromCallerAbs, encoding);
79
- }
80
- const directPath = join(assetsRoot, relPath);
81
- tried.push(directPath);
82
- if (existsSync(directPath)) return readFileSync(directPath, encoding);
83
- if (callerSubpath) {
84
- const nested = join(assetsRoot, callerSubpath, relPath);
85
- tried.push(nested);
86
- if (existsSync(nested)) return readFileSync(nested, encoding);
87
- }
88
- const msg = [
89
- "readAsset: file not found.",
90
- "Searched:",
91
- ...tried.map((p) => `- ${p}`)
92
- ].join("\n");
93
- throw new Error(msg);
94
- };
95
-
96
- //#endregion
97
- export { readAsset };
1
+ import{existsSync as e,readFileSync as t}from"node:fs";import{basename as n,dirname as r,join as i,relative as a,resolve as o,sep as s}from"node:path";import{fileURLToPath as c}from"node:url";const l=()=>{try{return r(c(import.meta.url))}catch{return typeof __dirname<`u`?__dirname:process.cwd()}},u=e=>{let t=e;for(let e=0;e<12;e++){if(n(t)===`dist`)return t;let e=o(t,`..`);if(e===t)break;t=e}return null},d=e=>{if(!e)return null;try{if(e.startsWith(`file://`))return c(e)}catch{}return e},f=()=>{let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error();Error.captureStackTrace(e,f);let t=e.stack||[],n=e=>e.includes(`${s}_virtual${s}`)||e.includes(`/_virtual/`);for(let e of t){let t=d(typeof e.getFileName==`function`?e.getFileName():null);if(t&&!(t.includes(`node:internal`)||t.includes(`${s}internal${s}modules${s}`))&&!n(t))return r(t)}for(let e of t){let t=d(typeof e.getFileName==`function`?e.getFileName():null);if(t)return r(t)}}catch{}finally{Error.prepareStackTrace=e}return l()},p=(n,r=`utf8`)=>{let s=l(),c=u(s)??o(s,`..`,`..`,`dist`),d=i(c,`assets`),p=[],m=a(c,f()).split(`\\`).join(`/`).replace(/^(?:dist\/)?(?:esm|cjs)\//,``).replace(/^_virtual\//,``);if(n.startsWith(`./`)||n.startsWith(`../`)){let i=o(d,m,n);if(p.push(i),e(i))return t(i,r)}let h=i(d,n);if(p.push(h),e(h))return t(h,r);if(m){let a=i(d,m,n);if(p.push(a),e(a))return t(a,r)}let g=[`readAsset: file not found.`,`Searched:`,...p.map(e=>`- ${e}`)].join(`
2
+ `);throw Error(g)};export{p as readAsset};
@@ -1,201 +1,2 @@
1
- import { ANSIColors, colorize, logger, x } from "@intlayer/config";
2
- import { AiProviders } from "@intlayer/types";
3
-
4
- //#region src/aiSdk.ts
5
- const getAPIKey = (accessType, aiOptions, isAuthenticated = false) => {
6
- const defaultApiKey = process.env.OPENAI_API_KEY;
7
- if (accessType.includes("public")) return aiOptions?.apiKey ?? defaultApiKey;
8
- if (accessType.includes("apiKey") && aiOptions?.apiKey) return aiOptions?.apiKey;
9
- if (accessType.includes("registered_user") && isAuthenticated) return aiOptions?.apiKey ?? defaultApiKey;
10
- if (accessType.includes("premium_user") && isAuthenticated) return aiOptions?.apiKey ?? defaultApiKey;
11
- };
12
- const getModelName = (provider, userApiKey, userModel, defaultModel = "gpt-5-mini") => {
13
- if (userApiKey || provider === AiProviders.OLLAMA) {
14
- if (provider === AiProviders.OPENAI) return userModel ?? defaultModel;
15
- if (userModel) return userModel;
16
- switch (provider) {
17
- default: return "-";
18
- }
19
- }
20
- if (userModel || provider) throw new Error("The user should use his own API key to use a custom model");
21
- return defaultModel;
22
- };
23
- const getLanguageModel = async (aiOptions, apiKey, defaultModel) => {
24
- const loadModule = async (packageName) => {
25
- try {
26
- return await import(packageName);
27
- } catch {
28
- logger(`${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)}`, { level: "error" });
29
- process.exit();
30
- }
31
- };
32
- const provider = aiOptions.provider ?? AiProviders.OPENAI;
33
- const selectedModel = getModelName(provider, apiKey, aiOptions.model, defaultModel);
34
- const baseURL = aiOptions.baseURL;
35
- switch (provider) {
36
- case AiProviders.OPENAI: {
37
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
38
- const { createOpenAI } = await loadModule("@ai-sdk/openai");
39
- return createOpenAI({
40
- apiKey,
41
- baseURL,
42
- ...otherOptions
43
- })(selectedModel);
44
- }
45
- case AiProviders.ANTHROPIC: {
46
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
47
- const { createAnthropic } = await loadModule("@ai-sdk/anthropic");
48
- return createAnthropic({
49
- apiKey,
50
- baseURL,
51
- ...otherOptions
52
- })(selectedModel);
53
- }
54
- case AiProviders.MISTRAL: {
55
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
56
- const { createMistral } = await loadModule("@ai-sdk/mistral");
57
- return createMistral({
58
- apiKey,
59
- baseURL,
60
- ...otherOptions
61
- })(selectedModel);
62
- }
63
- case AiProviders.DEEPSEEK: {
64
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
65
- const { createDeepSeek } = await loadModule("@ai-sdk/deepseek");
66
- return createDeepSeek({
67
- apiKey,
68
- baseURL,
69
- ...otherOptions
70
- })(selectedModel);
71
- }
72
- case AiProviders.GEMINI: {
73
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
74
- const { createGoogleGenerativeAI } = await loadModule("@ai-sdk/google");
75
- return createGoogleGenerativeAI({
76
- apiKey,
77
- baseURL,
78
- ...otherOptions
79
- })(selectedModel);
80
- }
81
- case AiProviders.GOOGLEVERTEX: {
82
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
83
- const { createVertex } = await loadModule("@ai-sdk/google-vertex");
84
- return createVertex({
85
- apiKey,
86
- baseURL,
87
- ...otherOptions
88
- })(selectedModel);
89
- }
90
- case AiProviders.GOOGLEGENERATIVEAI: {
91
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
92
- const { createGoogleGenerativeAI } = await loadModule("@ai-sdk/google");
93
- return createGoogleGenerativeAI({
94
- apiKey,
95
- baseURL,
96
- ...otherOptions
97
- })(selectedModel);
98
- }
99
- case AiProviders.OLLAMA: {
100
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
101
- const { createOpenAI } = await loadModule("@ai-sdk/openai");
102
- return createOpenAI({
103
- baseURL: baseURL ?? "http://localhost:11434/v1",
104
- apiKey: apiKey ?? "ollama",
105
- ...otherOptions
106
- }).chat(selectedModel);
107
- }
108
- case AiProviders.OPENROUTER: {
109
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
110
- const { createOpenRouter } = await loadModule("@openrouter/ai-sdk-provider");
111
- return createOpenRouter({
112
- apiKey,
113
- baseURL,
114
- ...otherOptions
115
- })(selectedModel);
116
- }
117
- case AiProviders.ALIBABA: {
118
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
119
- const { createAlibaba } = await loadModule("@ai-sdk/alibaba");
120
- return createAlibaba({
121
- apiKey,
122
- baseURL,
123
- ...otherOptions
124
- })(selectedModel);
125
- }
126
- case AiProviders.FIREWORKS: {
127
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
128
- const { createFireworks } = await loadModule("@ai-sdk/fireworks");
129
- return createFireworks({
130
- apiKey,
131
- baseURL,
132
- ...otherOptions
133
- })(selectedModel);
134
- }
135
- case AiProviders.GROQ: {
136
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
137
- const { createGroq } = await loadModule("@ai-sdk/groq");
138
- return createGroq({
139
- apiKey,
140
- baseURL,
141
- ...otherOptions
142
- })(selectedModel);
143
- }
144
- case AiProviders.HUGGINGFACE: {
145
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
146
- const { createHuggingFace } = await loadModule("@ai-sdk/huggingface");
147
- return createHuggingFace({
148
- apiKey,
149
- baseURL,
150
- ...otherOptions
151
- })(selectedModel);
152
- }
153
- case AiProviders.BEDROCK: {
154
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
155
- const { createAmazonBedrock } = await loadModule("@ai-sdk/amazon-bedrock");
156
- return createAmazonBedrock({
157
- accessKeyId: apiKey,
158
- baseURL,
159
- ...otherOptions
160
- })(selectedModel);
161
- }
162
- case AiProviders.TOGETHERAI: {
163
- const { provider, model, temperature, applicationContext, dataSerialization, apiKey: _apiKey, baseURL: _baseURL, ...otherOptions } = aiOptions;
164
- const { createTogetherAI } = await loadModule("@ai-sdk/togetherai");
165
- return createTogetherAI({
166
- apiKey,
167
- baseURL,
168
- ...otherOptions
169
- })(selectedModel);
170
- }
171
- default: throw new Error(`Provider ${provider} not supported`);
172
- }
173
- };
174
- const DEFAULT_PROVIDER = AiProviders.OPENAI;
175
- /**
176
- * Get AI model configuration based on the selected provider and options
177
- * This function handles the configuration for different AI providers
178
- *
179
- * @param options Configuration options including provider, API keys, models and temperature
180
- * @returns Configured AI model ready to use with generateText
181
- */
182
- const getAIConfig = async (options, isAuthenticated = false) => {
183
- const { userOptions, projectOptions, defaultOptions, accessType = ["registered_user"] } = options;
184
- const aiOptions = {
185
- provider: DEFAULT_PROVIDER,
186
- ...defaultOptions,
187
- ...projectOptions,
188
- ...userOptions
189
- };
190
- const apiKey = getAPIKey(accessType, aiOptions, isAuthenticated);
191
- if (!apiKey && aiOptions.provider !== AiProviders.OLLAMA) throw new Error(`API key for ${aiOptions.provider} is missing`);
192
- return {
193
- model: await getLanguageModel(aiOptions, apiKey, defaultOptions?.model),
194
- temperature: aiOptions.temperature,
195
- dataSerialization: aiOptions.dataSerialization
196
- };
197
- };
198
-
199
- //#endregion
200
- export { AiProviders as AIProvider, getAIConfig };
1
+ import{ANSIColors as e,colorize as t,logger as n,x as r}from"@intlayer/config/logger";import{AiProviders as i}from"@intlayer/types";const a=(e,t,n=!1)=>{let r=process.env.OPENAI_API_KEY;if(e.includes(`public`))return t?.apiKey??r;if(e.includes(`apiKey`)&&t?.apiKey)return t?.apiKey;if(e.includes(`registered_user`)&&n||e.includes(`premium_user`)&&n)return t?.apiKey??r},o=(e,t,n,r=`gpt-5-mini`)=>{if(t||e===i.OLLAMA){if(e===i.OPENAI)return n??r;if(n)return n;switch(e){default:return`-`}}if(n||e)throw Error(`The user should use his own API key to use a custom model`);return r},s=async(a,s,c)=>{let l=async i=>{try{return await import(i)}catch{n(`${r} The package "${t(i,e.GREEN)}" is required to use this AI provider. Please install it using: ${t(`npm install ${i}`,e.GREY_DARK)}`,{level:`error`}),process.exit()}},u=a.provider??i.OPENAI,d=o(u,s,a.model,c),f=a.baseURL;switch(u){case i.OPENAI:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createOpenAI:p}=await l(`@ai-sdk/openai`);return p({apiKey:s,baseURL:f,...u})(d)}case i.ANTHROPIC:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createAnthropic:p}=await l(`@ai-sdk/anthropic`);return p({apiKey:s,baseURL:f,...u})(d)}case i.MISTRAL:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createMistral:p}=await l(`@ai-sdk/mistral`);return p({apiKey:s,baseURL:f,...u})(d)}case i.DEEPSEEK:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createDeepSeek:p}=await l(`@ai-sdk/deepseek`);return p({apiKey:s,baseURL:f,...u})(d)}case i.GEMINI:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createGoogleGenerativeAI:p}=await l(`@ai-sdk/google`);return p({apiKey:s,baseURL:f,...u})(d)}case i.GOOGLEVERTEX:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createVertex:p}=await l(`@ai-sdk/google-vertex`);return p({apiKey:s,baseURL:f,...u})(d)}case i.GOOGLEGENERATIVEAI:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createGoogleGenerativeAI:p}=await l(`@ai-sdk/google`);return p({apiKey:s,baseURL:f,...u})(d)}case i.OLLAMA:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createOpenAI:p}=await l(`@ai-sdk/openai`);return p({baseURL:f??`http://localhost:11434/v1`,apiKey:s??`ollama`,...u}).chat(d)}case i.OPENROUTER:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createOpenRouter:p}=await l(`@openrouter/ai-sdk-provider`);return p({apiKey:s,baseURL:f,...u})(d)}case i.ALIBABA:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createAlibaba:p}=await l(`@ai-sdk/alibaba`);return p({apiKey:s,baseURL:f,...u})(d)}case i.FIREWORKS:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createFireworks:p}=await l(`@ai-sdk/fireworks`);return p({apiKey:s,baseURL:f,...u})(d)}case i.GROQ:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createGroq:p}=await l(`@ai-sdk/groq`);return p({apiKey:s,baseURL:f,...u})(d)}case i.HUGGINGFACE:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createHuggingFace:p}=await l(`@ai-sdk/huggingface`);return p({apiKey:s,baseURL:f,...u})(d)}case i.BEDROCK:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createAmazonBedrock:p}=await l(`@ai-sdk/amazon-bedrock`);return p({accessKeyId:s,baseURL:f,...u})(d)}case i.TOGETHERAI:{let{provider:e,model:t,temperature:n,applicationContext:r,dataSerialization:i,apiKey:o,baseURL:c,...u}=a,{createTogetherAI:p}=await l(`@ai-sdk/togetherai`);return p({apiKey:s,baseURL:f,...u})(d)}default:throw Error(`Provider ${u} not supported`)}},c=i.OPENAI,l=async(e,t=!1)=>{let{userOptions:n,projectOptions:r,defaultOptions:o,accessType:l=[`registered_user`]}=e,u={provider:c,...o,...r,...n},d=a(l,u,t);if(!d&&u.provider!==i.OLLAMA)throw Error(`API key for ${u.provider} is missing`);return{model:await s(u,d,o?.model),temperature:u.temperature,dataSerialization:u.dataSerialization}};export{i as AIProvider,l as getAIConfig};
201
2
  //# sourceMappingURL=aiSdk.mjs.map