@imenam/unified-llm-client 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -0
  3. package/dist/adapters/anthropic/AnthropicLogAdapter.d.ts +6 -0
  4. package/dist/adapters/anthropic/AnthropicLogAdapter.d.ts.map +1 -0
  5. package/dist/adapters/anthropic/AnthropicLogAdapter.js +41 -0
  6. package/dist/adapters/anthropic/AnthropicOutputAdapter.d.ts +6 -0
  7. package/dist/adapters/anthropic/AnthropicOutputAdapter.d.ts.map +1 -0
  8. package/dist/adapters/anthropic/AnthropicOutputAdapter.js +41 -0
  9. package/dist/adapters/anthropic/AnthropicPromptAdapter.d.ts +12 -0
  10. package/dist/adapters/anthropic/AnthropicPromptAdapter.d.ts.map +1 -0
  11. package/dist/adapters/anthropic/AnthropicPromptAdapter.js +249 -0
  12. package/dist/adapters/anthropic/AnthropicToolAdapter.d.ts +6 -0
  13. package/dist/adapters/anthropic/AnthropicToolAdapter.d.ts.map +1 -0
  14. package/dist/adapters/anthropic/AnthropicToolAdapter.js +20 -0
  15. package/dist/adapters/gemini/GeminiAudioAdapter.d.ts +40 -0
  16. package/dist/adapters/gemini/GeminiAudioAdapter.d.ts.map +1 -0
  17. package/dist/adapters/gemini/GeminiAudioAdapter.js +273 -0
  18. package/dist/adapters/gemini/GeminiLogAdapter.d.ts +6 -0
  19. package/dist/adapters/gemini/GeminiLogAdapter.d.ts.map +1 -0
  20. package/dist/adapters/gemini/GeminiLogAdapter.js +43 -0
  21. package/dist/adapters/gemini/GeminiOutputAdapter.d.ts +6 -0
  22. package/dist/adapters/gemini/GeminiOutputAdapter.d.ts.map +1 -0
  23. package/dist/adapters/gemini/GeminiOutputAdapter.js +38 -0
  24. package/dist/adapters/gemini/GeminiPromptAdapter.d.ts +26 -0
  25. package/dist/adapters/gemini/GeminiPromptAdapter.d.ts.map +1 -0
  26. package/dist/adapters/gemini/GeminiPromptAdapter.js +334 -0
  27. package/dist/adapters/gemini/GeminiToolAdapter.d.ts +8 -0
  28. package/dist/adapters/gemini/GeminiToolAdapter.d.ts.map +1 -0
  29. package/dist/adapters/gemini/GeminiToolAdapter.js +42 -0
  30. package/dist/adapters/gemini/types.d.ts +14 -0
  31. package/dist/adapters/gemini/types.d.ts.map +1 -0
  32. package/dist/adapters/gemini/types.js +2 -0
  33. package/dist/adapters/openai/OpenAIOutputAdapter.d.ts +6 -0
  34. package/dist/adapters/openai/OpenAIOutputAdapter.d.ts.map +1 -0
  35. package/dist/adapters/openai/OpenAIOutputAdapter.js +18 -0
  36. package/dist/adapters/openai/OpenAIPromptAdapter.d.ts +13 -0
  37. package/dist/adapters/openai/OpenAIPromptAdapter.d.ts.map +1 -0
  38. package/dist/adapters/openai/OpenAIPromptAdapter.js +215 -0
  39. package/dist/adapters/openai/OpenAiLogAdapter.d.ts +6 -0
  40. package/dist/adapters/openai/OpenAiLogAdapter.d.ts.map +1 -0
  41. package/dist/adapters/openai/OpenAiLogAdapter.js +37 -0
  42. package/dist/adapters/openai/OpenAiToolAdapter.d.ts +6 -0
  43. package/dist/adapters/openai/OpenAiToolAdapter.d.ts.map +1 -0
  44. package/dist/adapters/openai/OpenAiToolAdapter.js +20 -0
  45. package/dist/adapters/qwen/QwenLogAdapter.d.ts +7 -0
  46. package/dist/adapters/qwen/QwenLogAdapter.d.ts.map +1 -0
  47. package/dist/adapters/qwen/QwenLogAdapter.js +49 -0
  48. package/dist/adapters/qwen/QwenOutputAdapter.d.ts +6 -0
  49. package/dist/adapters/qwen/QwenOutputAdapter.d.ts.map +1 -0
  50. package/dist/adapters/qwen/QwenOutputAdapter.js +9 -0
  51. package/dist/adapters/qwen/QwenPromptAdapter.d.ts +13 -0
  52. package/dist/adapters/qwen/QwenPromptAdapter.d.ts.map +1 -0
  53. package/dist/adapters/qwen/QwenPromptAdapter.js +313 -0
  54. package/dist/adapters/qwen/QwenToolAdapter.d.ts +6 -0
  55. package/dist/adapters/qwen/QwenToolAdapter.d.ts.map +1 -0
  56. package/dist/adapters/qwen/QwenToolAdapter.js +20 -0
  57. package/dist/common/types.d.ts +106 -0
  58. package/dist/common/types.d.ts.map +1 -0
  59. package/dist/common/types.js +2 -0
  60. package/dist/core/LLMAdapter.d.ts +74 -0
  61. package/dist/core/LLMAdapter.d.ts.map +1 -0
  62. package/dist/core/LLMAdapter.js +70 -0
  63. package/dist/core/Models.d.ts +16 -0
  64. package/dist/core/Models.d.ts.map +1 -0
  65. package/dist/core/Models.js +118 -0
  66. package/dist/core/UnifiedLLMClient.d.ts +68 -0
  67. package/dist/core/UnifiedLLMClient.d.ts.map +1 -0
  68. package/dist/core/UnifiedLLMClient.js +185 -0
  69. package/dist/examples/anthropic-example.d.ts +2 -0
  70. package/dist/examples/anthropic-example.d.ts.map +1 -0
  71. package/dist/examples/anthropic-example.js +243 -0
  72. package/dist/examples/audio-example.d.ts +14 -0
  73. package/dist/examples/audio-example.d.ts.map +1 -0
  74. package/dist/examples/audio-example.js +204 -0
  75. package/dist/examples/example-logging.d.ts +2 -0
  76. package/dist/examples/example-logging.d.ts.map +1 -0
  77. package/dist/examples/example-logging.js +53 -0
  78. package/dist/examples/example.d.ts +2 -0
  79. package/dist/examples/example.d.ts.map +1 -0
  80. package/dist/examples/example.js +373 -0
  81. package/dist/examples/qwen-vl-example.d.ts +26 -0
  82. package/dist/examples/qwen-vl-example.d.ts.map +1 -0
  83. package/dist/examples/qwen-vl-example.js +314 -0
  84. package/dist/examples/test-multiturn-tools.d.ts +2 -0
  85. package/dist/examples/test-multiturn-tools.d.ts.map +1 -0
  86. package/dist/examples/test-multiturn-tools.js +139 -0
  87. package/dist/index.d.ts +7 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +7 -0
  90. package/dist/utils/audioUtils.d.ts +41 -0
  91. package/dist/utils/audioUtils.d.ts.map +1 -0
  92. package/dist/utils/audioUtils.js +185 -0
  93. package/package.json +64 -0
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
45
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
46
+ var m = o[Symbol.asyncIterator], i;
47
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
48
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
49
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
50
+ };
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.cleanupAudioExamples = cleanupAudioExamples;
53
+ exports.runAudioExamples = runAudioExamples;
54
+ exports.listAvailableVoices = listAvailableVoices;
55
+ exports.generateSimpleAudio = generateSimpleAudio;
56
+ exports.generateMultiVoiceAudio = generateMultiVoiceAudio;
57
+ exports.generateAdvancedAudio = generateAdvancedAudio;
58
+ exports.generateStreamingAudio = generateStreamingAudio;
59
+ exports.generateInMemoryAudio = generateInMemoryAudio;
60
+ const UnifiedLLMClient_1 = require("../core/UnifiedLLMClient");
61
+ const index_1 = require("../index");
62
+ const path = __importStar(require("path"));
63
+ const fs = __importStar(require("fs"));
64
+ const AUDIO_OUTPUT_DIR = "./audio-examples";
65
+ if (!fs.existsSync(AUDIO_OUTPUT_DIR)) {
66
+ fs.mkdirSync(AUDIO_OUTPUT_DIR, { recursive: true });
67
+ }
68
+ function listAvailableVoices(client) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const voices = yield client.getSupportedAudioVoices();
71
+ return voices;
72
+ });
73
+ }
74
+ function generateSimpleAudio(client) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ const simpleText = "Bonjour ! Ceci est un test de génération audio avec Gemini TTS.";
77
+ const simpleOutputPath = path.join(AUDIO_OUTPUT_DIR, "simple-example.wav");
78
+ const simpleResponse = yield client.generateSingleVoiceAudio(simpleText, "enceladus", { outputPath: simpleOutputPath, temperature: 1.0 });
79
+ return simpleResponse;
80
+ });
81
+ }
82
+ function generateMultiVoiceAudio(client) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const podcastText = `Speaker 1: Bienvenue dans notre podcast technologique !
85
+ Speaker 2: Aujourd'hui, nous parlons d'intelligence artificielle et de génération de voix.`;
86
+ const multiOutputPath = path.join(AUDIO_OUTPUT_DIR, "podcast-example.wav");
87
+ const multiResponse = yield client.generateMultiVoiceAudio(podcastText, [
88
+ { speaker: "Speaker 1", voiceName: "enceladus" },
89
+ { speaker: "Speaker 2", voiceName: "puck" }
90
+ ], { outputPath: multiOutputPath, temperature: 1.3 });
91
+ return multiResponse;
92
+ });
93
+ }
94
+ function generateAdvancedAudio(client) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ const advancedText = "Cette démonstration utilise des paramètres avancés pour une voix plus expressive.";
97
+ const advancedOutputPath = path.join(AUDIO_OUTPUT_DIR, "advanced-example.wav");
98
+ const advancedResponse = yield client.generateAudio({
99
+ text: advancedText,
100
+ outputPath: advancedOutputPath,
101
+ voiceConfig: {
102
+ voiceName: "enceladus",
103
+ temperature: 1.8
104
+ },
105
+ multiSpeaker: false
106
+ });
107
+ return advancedResponse;
108
+ });
109
+ }
110
+ function generateStreamingAudio(client) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ var _a, e_1, _b, _c;
113
+ const streamText = "Ceci est un exemple de streaming audio en temps réel. Le texte doit être plus long pour que le streaming soit visible, alors voila un texte un peu plus long pour que le streaming soit visible.";
114
+ let totalChunks = 0;
115
+ let totalBytes = 0;
116
+ const streamingAudio = client.generateAudioStream({
117
+ text: streamText,
118
+ voiceConfig: { voiceName: "enceladus" }
119
+ });
120
+ try {
121
+ for (var _d = true, streamingAudio_1 = __asyncValues(streamingAudio), streamingAudio_1_1; streamingAudio_1_1 = yield streamingAudio_1.next(), _a = streamingAudio_1_1.done, !_a; _d = true) {
122
+ _c = streamingAudio_1_1.value;
123
+ _d = false;
124
+ const chunk = _c;
125
+ totalChunks++;
126
+ totalBytes += chunk.length;
127
+ }
128
+ }
129
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
130
+ finally {
131
+ try {
132
+ if (!_d && !_a && (_b = streamingAudio_1.return)) yield _b.call(streamingAudio_1);
133
+ }
134
+ finally { if (e_1) throw e_1.error; }
135
+ }
136
+ return { totalChunks, totalBytes };
137
+ });
138
+ }
139
+ function generateInMemoryAudio(client) {
140
+ return __awaiter(this, void 0, void 0, function* () {
141
+ const memoryText = "Audio généré uniquement en mémoire, sans fichier de sortie.";
142
+ const memoryResponse = yield client.generateAudio({
143
+ text: memoryText,
144
+ voiceConfig: { voiceName: "enceladus" }
145
+ });
146
+ return memoryResponse;
147
+ });
148
+ }
149
+ function runAudioExamples() {
150
+ return __awaiter(this, void 0, void 0, function* () {
151
+ if (!process.env.GOOGLE_API_KEY) {
152
+ console.error("❌ Variable d'environnement GOOGLE_API_KEY manquante");
153
+ process.exit(1);
154
+ }
155
+ const client = new UnifiedLLMClient_1.UnifiedLLMClient(index_1.MODELS.GEMINI_FLASH_2_5);
156
+ try {
157
+ if (!client.isAudioSupported()) {
158
+ return;
159
+ }
160
+ // await listAvailableVoices(client);
161
+ // await generateSimpleAudio(client);
162
+ yield generateMultiVoiceAudio(client);
163
+ // await generateAdvancedAudio(client);
164
+ // await generateStreamingAudio(client);
165
+ // await generateInMemoryAudio(client);
166
+ }
167
+ catch (error) {
168
+ console.error("❌ Erreur lors de l'exécution des exemples audio:", error);
169
+ }
170
+ });
171
+ }
172
+ function displayAudioInfo(filePath) {
173
+ if (fs.existsSync(filePath)) {
174
+ const stats = fs.statSync(filePath);
175
+ }
176
+ }
177
+ function cleanupAudioExamples() {
178
+ const files = [
179
+ "simple-example.wav",
180
+ "podcast-example.wav",
181
+ "advanced-example.wav"
182
+ ];
183
+ files.forEach(file => {
184
+ const filePath = path.join(AUDIO_OUTPUT_DIR, file);
185
+ try {
186
+ if (fs.existsSync(filePath)) {
187
+ fs.unlinkSync(filePath);
188
+ }
189
+ }
190
+ catch (error) {
191
+ console.warn(`⚠️ Impossible de supprimer ${file}:`, error);
192
+ }
193
+ });
194
+ }
195
+ if (require.main === module) {
196
+ runAudioExamples()
197
+ .then(() => {
198
+ const files = fs.readdirSync(AUDIO_OUTPUT_DIR);
199
+ files.forEach(file => {
200
+ displayAudioInfo(path.join(AUDIO_OUTPUT_DIR, file));
201
+ });
202
+ })
203
+ .catch(console.error);
204
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=example-logging.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example-logging.d.ts","sourceRoot":"","sources":["../../src/examples/example-logging.ts"],"names":[],"mappings":""}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const __1 = require("..");
13
+ function testLogging() {
14
+ return __awaiter(this, void 0, void 0, function* () {
15
+ console.log("🚀 Testing LLM Logging System...");
16
+ // Example of a custom logger that could be a database logger, file logger, etc.
17
+ const customLogger = (log) => {
18
+ console.log("\n--- CUSTOM LOGGER START ---");
19
+ console.log(`[${log.timestamp.toISOString()}] ${log.provider} ${log.model} - Latency: ${log.latencyMs}ms`);
20
+ console.log("Usage totals:", log.usage.totalTokens, "tokens");
21
+ console.log("--- CUSTOM LOGGER END ---\n");
22
+ };
23
+ // We pass the logger at instantiation
24
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5, { logger: customLogger });
25
+ console.log("\n--- Call 1: Simple Question ---");
26
+ yield client.chat({
27
+ message: "Bonjour, qui es-tu ?",
28
+ config: {
29
+ metadata: {
30
+ userId: "user_123",
31
+ session: "test_session_abc"
32
+ }
33
+ }
34
+ });
35
+ console.log("\n--- Call 2: Streaming Question ---");
36
+ yield client.chat({
37
+ message: "Raconte-moi une très courte blague.",
38
+ stream: true,
39
+ onChunk: (chunk) => {
40
+ process.stdout.write(chunk.contentChunk || "");
41
+ },
42
+ onFinalResponse: ({ content }) => {
43
+ console.log("\nFinal Content:", content);
44
+ },
45
+ config: {
46
+ metadata: {
47
+ type: "streaming_test"
48
+ }
49
+ }
50
+ });
51
+ });
52
+ }
53
+ testLogging().catch(console.error);
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"example.d.ts","sourceRoot":"","sources":["../../src/examples/example.ts"],"names":[],"mappings":""}
@@ -0,0 +1,373 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const __1 = require("..");
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const tools = [
18
+ {
19
+ name: "get_user_birth_city",
20
+ description: "Retrieve user birth city",
21
+ parameters: {
22
+ type: "object",
23
+ properties: {
24
+ user: { type: "string", description: "User name" },
25
+ },
26
+ required: ["user"],
27
+ },
28
+ executor: (_a) => __awaiter(void 0, [_a], void 0, function* ({ user }) {
29
+ // fetch weather data from API and then
30
+ let cities = [
31
+ "Paris",
32
+ "Marrakech",
33
+ "Marseille",
34
+ "Toulouse",
35
+ "Nice",
36
+ "Nantes",
37
+ "Strasbourg",
38
+ ];
39
+ return `User ${user} was born in ${cities[Math.floor(Math.random() * cities.length)]}`; // Placeholder
40
+ })
41
+ },
42
+ {
43
+ name: "get_weather",
44
+ description: "Retrieve weather for a given city",
45
+ parameters: {
46
+ type: "object",
47
+ properties: {
48
+ city: { type: "string", description: "City name" },
49
+ },
50
+ required: ["city"],
51
+ },
52
+ executor: (_a) => __awaiter(void 0, [_a], void 0, function* ({ city }) {
53
+ // fetch weather data from API and then
54
+ let temperature = Math.floor(10 + Math.random() * 20);
55
+ return `Weather in ${city} is ${temperature}°C, and sunny`; // Placeholder
56
+ })
57
+ },
58
+ {
59
+ name: "create_md_file",
60
+ description: "Create a markdown file",
61
+ parameters: {
62
+ type: "object",
63
+ properties: {
64
+ content: { type: "string", description: "Content of the file" },
65
+ filename: { type: "string", description: "filename of the file" },
66
+ },
67
+ required: ["content", "filename"],
68
+ },
69
+ executor: (_a) => __awaiter(void 0, [_a], void 0, function* ({ title }) {
70
+ return `Created markdown file with title ${title}`; // Placeholder
71
+ })
72
+ }
73
+ ];
74
+ function basicUsage() {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
77
+ // const tools: ToolDefinition[] = [
78
+ // {
79
+ // name: "get_weather",
80
+ // description: "Retrieve weather for a given city",
81
+ // parameters: {
82
+ // type: "object",
83
+ // properties: {
84
+ // city: { type: "string", description: "City name" },
85
+ // },
86
+ // required: ["city"],
87
+ // },
88
+ // executor: async ({ city }) => {
89
+ // // fetch weather data from API and then
90
+ // return `Weather in ${city}... `; // Placeholder
91
+ // }
92
+ // }
93
+ // ];
94
+ const res = yield client.chat({
95
+ message: "Quel modèle es-tu ? 2.5-flash ou 2.5-pro ? Répond l'un ou l'autre, soit '2.5-flash' ou '2.5-pro', rien d'autre.",
96
+ // tools
97
+ });
98
+ console.log("response", JSON.stringify(res.content));
99
+ });
100
+ }
101
+ function basicUsageWithAudio() {
102
+ return __awaiter(this, void 0, void 0, function* () {
103
+ var _a, _b;
104
+ const tool = {
105
+ name: "save_audio_transcription",
106
+ description: "Save audio transcription",
107
+ parameters: {
108
+ type: "object",
109
+ properties: {
110
+ transcription: { type: "string", description: "Transcription of the audio" },
111
+ attachedFileName: { type: "string", description: "Audio file to save" },
112
+ },
113
+ required: ["transcription", "attachedFileName"],
114
+ },
115
+ executor: (_a) => __awaiter(this, [_a], void 0, function* ({ transcription, attachedFileName }) {
116
+ return `Saved transcription: ${transcription}`;
117
+ })
118
+ };
119
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
120
+ const res = yield client.chat({
121
+ message: {
122
+ role: "user",
123
+ content: "Transcrit cet audio, et nomme le fichier avec un nom en rapport avec le contenu",
124
+ attachedFile: "./media/audio.mp3"
125
+ },
126
+ tools: [tool]
127
+ });
128
+ console.log("response", JSON.stringify((_b = (_a = res.toolCalls) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.arguments, null, 2));
129
+ });
130
+ }
131
+ function basicStreamUsage() {
132
+ return __awaiter(this, void 0, void 0, function* () {
133
+ console.log('Gemini Streaming Example');
134
+ // Initialize the client with Gemini
135
+ // Ensure your PROVIDERS_CONFIG in LLMAdapter.ts is set up for Gemini
136
+ // and that GeminiPromptAdapter is correctly imported and used there.
137
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
138
+ const message = 'Quel temps y fait-il aujourd\'hui à Marseille ?';
139
+ try {
140
+ console.log('\n--- Starting stream ---');
141
+ const response = yield client.chat({
142
+ message,
143
+ tools,
144
+ onChunk: chunk => {
145
+ console.log('chunk', chunk.contentChunk);
146
+ },
147
+ onFinalResponse: finalResponse => {
148
+ console.log('finalResponse', JSON.stringify(finalResponse, null, 2));
149
+ },
150
+ stream: true
151
+ });
152
+ // console.log('response', response);
153
+ }
154
+ catch (error) {
155
+ console.error('\n--- Error in example ---', error);
156
+ }
157
+ });
158
+ }
159
+ function basicAudioGeneration() {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ console.log('🎵 Exemple de génération audio basique');
162
+ console.log('='.repeat(40));
163
+ // Utiliser Gemini car c'est le seul provider avec support audio actuellement
164
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
165
+ try {
166
+ // Vérifier si l'audio est supporté
167
+ if (!client.isAudioSupported()) {
168
+ console.log('❌ La génération audio n\'est pas supportée pour ce provider');
169
+ return;
170
+ }
171
+ console.log('✅ Support audio confirmé');
172
+ // Exemple 1: Génération simple
173
+ console.log('\n🗣️ Génération audio simple...');
174
+ const simpleText = "Bonjour ! Ceci est un test de génération audio avec l'interface unifiée.";
175
+ const audioResponse = yield client.generateSingleVoiceAudio(simpleText, "Kore", // Voix principale
176
+ { temperature: 1.0 });
177
+ console.log(`✅ Audio généré: ${audioResponse.audioData.length} bytes`);
178
+ console.log(`🗂️ Type MIME: ${audioResponse.mimeType}`);
179
+ // Exemple 2: Vérifier les voix disponibles
180
+ console.log('\n🎭 Voix disponibles:');
181
+ const voices = yield client.getSupportedAudioVoices();
182
+ console.log(voices.join(', '));
183
+ // Exemple 3: Génération multi-voix simple
184
+ console.log('\n🎙️ Génération multi-voix...');
185
+ const dialogText = `Speaker 1: Salut ! content ça va ?
186
+ Speaker 2: Très bien, merci ! Et toi ?
187
+ Speaker 1: Ça va super bien, merci de demander !`;
188
+ const multiAudioResponse = yield client.generateMultiVoiceAudio(dialogText, [
189
+ { speaker: "Speaker 1", voiceName: "Kore" },
190
+ { speaker: "Speaker 2", voiceName: "Puck" }
191
+ ], { temperature: 1.2 });
192
+ console.log(`✅ Dialogue généré: ${multiAudioResponse.audioData.length} bytes`);
193
+ console.log('\n🎉 Génération audio terminée avec succès !');
194
+ console.log('💡 Consultez examples/audio-example.ts pour des exemples plus détaillés');
195
+ }
196
+ catch (error) {
197
+ console.error('❌ Erreur lors de la génération audio:', error);
198
+ }
199
+ });
200
+ }
201
+ function getExercisesBoundaries() {
202
+ return __awaiter(this, void 0, void 0, function* () {
203
+ var _a, _b;
204
+ // sends an image to the model and returns a description
205
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
206
+ let tool = {
207
+ name: "exercises_boundaries",
208
+ description: "Get the boundaries of the exercises, by providing the start and end lines of the exercises in the image.",
209
+ parameters: {
210
+ type: "object",
211
+ properties: {
212
+ exercises: {
213
+ type: "array",
214
+ items: {
215
+ type: "object",
216
+ properties: {
217
+ startLine: { type: "number", description: "Start line of the exercise, based on the red line numbers in the image" },
218
+ endLine: { type: "number", description: "End line of the exercise, based on the red line numbers in the image. Can be the same as the start line if the exercise is on a single line" },
219
+ content: { type: "string", description: "Content of the exercise" },
220
+ questionNumber: { type: "string", description: "The number of the question. Only if provided in the image" },
221
+ },
222
+ }
223
+ }
224
+ },
225
+ required: ["exercises"],
226
+ },
227
+ executor: (_a) => __awaiter(this, [_a], void 0, function* ({ exercises }) {
228
+ // fetch weather data from API and then
229
+ return `Exercises: ${exercises}`; // Placeholder
230
+ })
231
+ };
232
+ const res = yield client.chat({
233
+ message: {
234
+ role: "user",
235
+ content: "Donne moi les limites des exercices dans l'image",
236
+ attachedFile: "./media/Gaspard_5_with_lines.png"
237
+ },
238
+ tools: [tool]
239
+ });
240
+ console.log("response", (_b = (_a = res.toolCalls) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.arguments);
241
+ });
242
+ }
243
+ function exerciseMatching() {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ var _a, _b;
246
+ const answers = [
247
+ {
248
+ index: 0,
249
+ endLine: 20,
250
+ comment: 'Graphiquement, j’observe que la longueur d’onde λ max = 760 nm. Je convertis en mètres : λmax = 750 x 10^-9 = 7,5 x 10^-7',
251
+ questionNumber: '1',
252
+ startLine: 17
253
+ },
254
+ {
255
+ index: 1,
256
+ questionNumber: '2',
257
+ startLine: 21,
258
+ endLine: 27,
259
+ comment: 'Je sais que λmax x T = constante donc T = constante / λmax d’où T = 2,8978 x 10^-3 / 7,5 x 10^-7 T = 3877,7 K'
260
+ },
261
+ {
262
+ index: 2,
263
+ startLine: 29,
264
+ comment: 'Je calcule T en °C : T = 3877,7 + 273 = 4136,7 °C',
265
+ endLine: 30,
266
+ questionNumber: '3'
267
+ },
268
+ {
269
+ index: 3,
270
+ questionNumber: '4',
271
+ startLine: 31,
272
+ endLine: 36,
273
+ comment: 'Comme λmax se situe vers 800 nm, c’est l’intensité lumineuse la plus importante graphiquement. Ainsi, le rouge étant un rayonnement monochromatique dont la longueur d’onde s’approche de 800 nm, Kepler-186 apparaît plus rouge d’où le terme de "naine rouge" la désignant.'
274
+ },
275
+ {
276
+ index: 4,
277
+ startLine: 38,
278
+ comment: 'Je sais que pour calculer la masse perdue par une étoile chaque seconde, on résout Δm = ΔE / c^2 A.N. => Δm = 1,20 x 10^7 / 3,0 x 10^8 = 1/25 Kg. Ainsi, chaque seconde, Kepler-186 perd 1/25 kg.',
279
+ questionNumber: '5',
280
+ endLine: 43
281
+ }
282
+ ];
283
+ // sends an image to the model and returns a description
284
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
285
+ let tool = {
286
+ name: "exercise_matching",
287
+ description: "Match the students answers to the questions. Qestions are on the PDF file, and answers are on the data array.",
288
+ parameters: {
289
+ type: "object",
290
+ properties: {
291
+ matches: {
292
+ type: "array",
293
+ items: {
294
+ type: "object",
295
+ properties: {
296
+ questionNumber: { type: "string", description: "The number of the question in the pdf" },
297
+ index: { type: "number", description: "The index of the exercise in the answers data array" },
298
+ },
299
+ }
300
+ }
301
+ },
302
+ required: ["matches"],
303
+ },
304
+ executor: (_a) => __awaiter(this, [_a], void 0, function* ({ matches }) {
305
+ // fetch weather data from API and then
306
+ return `Matches: ${matches}`; // Placeholder
307
+ })
308
+ };
309
+ const res = yield client.chat({
310
+ message: {
311
+ role: "user",
312
+ content: "Voila les reponses des etudiants, et le sujet du devoir. Peux-tu les associer ? answers:\n" + JSON.stringify(answers),
313
+ // content: "Quelles sont les questions du sujet ?",
314
+ attachedFile: "./media/subject.pdf"
315
+ },
316
+ tools: [tool]
317
+ });
318
+ // console.log("response", res);
319
+ console.log("response", (_b = (_a = res.toolCalls) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.arguments);
320
+ });
321
+ }
322
+ function parseSubject() {
323
+ return __awaiter(this, void 0, void 0, function* () {
324
+ var _a;
325
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
326
+ const res = yield client.chat({
327
+ message: {
328
+ role: "user",
329
+ content: `Voila le sujet du devoir. Peux-tu le parser en respectant la structure suivante ?
330
+ {
331
+ questions: [
332
+ {
333
+ number: "1",
334
+ content: "Question 1" or "Exercie N", etc...,
335
+ type: "Title" or "Question",
336
+ marking_scheme: "X" or "", // if type is "Question", X can be a float - 3.5, 4, etc...
337
+ sub_questions: [
338
+ ...same structure
339
+ ]
340
+ }
341
+ ]
342
+ }
343
+ `,
344
+ attachedFile: "./media/nested_subject.pdf"
345
+ },
346
+ });
347
+ console.log("response", res.content);
348
+ // Remove JSON code block markers if they exist
349
+ const cleanedContent = (_a = res.content) === null || _a === void 0 ? void 0 : _a.replace(/```json\n?/g, '').replace(/```\n?/g, '');
350
+ fs_1.default.writeFileSync("./media/questions.json", cleanedContent || "");
351
+ });
352
+ }
353
+ function multiFileSend() {
354
+ return __awaiter(this, void 0, void 0, function* () {
355
+ const client = new __1.UnifiedLLMClient(__1.MODELS.GEMINI_FLASH_2_5);
356
+ const res = yield client.chat({
357
+ message: {
358
+ role: "user",
359
+ content: `Le sujet de devoir et les réponses données te semblent-ils cohérents ?`,
360
+ attachedFile: ["./media/nested_subject.pdf", "./media/test_1_lines_plus.png"]
361
+ },
362
+ });
363
+ console.log("response", res.content);
364
+ });
365
+ }
366
+ basicUsage();
367
+ // basicStreamUsage();
368
+ // basicUsageWithAudio();
369
+ // basicAudioGeneration();
370
+ // getExercisesBoundaries();
371
+ // exerciseMatching();
372
+ // parseSubject();
373
+ // multiFileSend();
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Exemple 1: Analyse d'une image simple avec Qwen VL
3
+ */
4
+ declare function qwenVLImageAnalysisExample(): Promise<void>;
5
+ /**
6
+ * Exemple 2: Extraction de texte structuré (bounding boxes) avec Qwen VL
7
+ */
8
+ declare function qwenVLBoundingBoxesExample(): Promise<void>;
9
+ /**
10
+ * Exemple 3: Analyse de document PDF avec Qwen VL
11
+ */
12
+ declare function qwenVLPdfAnalysisExample(): Promise<void>;
13
+ /**
14
+ * Exemple 4: Analyse d'image avec streaming pour voir la génération en temps réel
15
+ */
16
+ declare function qwenVLStreamingExample(): Promise<void>;
17
+ /**
18
+ * Exécute tous les exemples Qwen VL
19
+ */
20
+ declare function runAllQwenVLExamples(): Promise<void>;
21
+ /**
22
+ * Fonction utilitaire pour parser les réponses JSON de Qwen
23
+ */
24
+ declare function parseQwenJsonResponse(responseContent: string | null): any;
25
+ export { qwenVLImageAnalysisExample, qwenVLBoundingBoxesExample, qwenVLPdfAnalysisExample, qwenVLStreamingExample, runAllQwenVLExamples, parseQwenJsonResponse };
26
+ //# sourceMappingURL=qwen-vl-example.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"qwen-vl-example.d.ts","sourceRoot":"","sources":["../../src/examples/qwen-vl-example.ts"],"names":[],"mappings":"AAuDA;;GAEG;AACH,iBAAe,0BAA0B,kBAiCxC;AAED;;GAEG;AACH,iBAAe,0BAA0B,kBAmDxC;AAED;;GAEG;AACH,iBAAe,wBAAwB,kBAsBtC;AAED;;GAEG;AACH,iBAAe,sBAAsB,kBA8DpC;AAED;;GAEG;AACH,iBAAe,oBAAoB,kBAelC;AAED;;GAEG;AACH,iBAAS,qBAAqB,CAAC,eAAe,EAAE,MAAM,GAAG,IAAI,OAe5D;AASD,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,EACtB,oBAAoB,EACpB,qBAAqB,EACtB,CAAC"}