@lvx74/openrrouter-ai-agent 1.0.13 → 1.0.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lvx74/openrrouter-ai-agent",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "description": "A powerful AI agent toolkit compatible with @openai/agents for building conversational AI with tool calling support using OpenRouter",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/Agent.js CHANGED
@@ -165,7 +165,8 @@ export class Agent extends EventEmitter {
165
165
  const { name, arguments: argsStr } = toolCall.function
166
166
 
167
167
  try {
168
- const args = JSON.parse(argsStr)
168
+ console.log(`šŸ”§ Esecuzione tool: ${name} con args:`, argsStr)
169
+ const args = argsStr.trim() ? JSON.parse(argsStr.trim()) : {}
169
170
  const tool = this.toolMap.get(name)
170
171
 
171
172
  if (!tool) {
@@ -187,7 +188,7 @@ export class Agent extends EventEmitter {
187
188
  continue
188
189
  }
189
190
 
190
- console.log(`⚔ Eseguendo tool: ${name}...`)
191
+ console.log(`⚔ Eseguendo tool: ${name}(${JSON.stringify(args)})`)
191
192
  const startTime = Date.now()
192
193
  const result = await tool.execute(args, this.session)
193
194
 
@@ -217,6 +218,7 @@ export class Agent extends EventEmitter {
217
218
  } catch (error) {
218
219
  const errorMsg = `Errore nell'esecuzione di ${name}: ${error.message}`
219
220
  console.log(`āŒ Tool Error: ${errorMsg}`)
221
+ console.log(error)
220
222
 
221
223
  const toolMessage = {
222
224
  role: 'tool',
package/src/cli.js CHANGED
@@ -97,33 +97,40 @@ export function createChatInterface(agent, options = {}) {
97
97
  console.log(' • /help - Mostra questo aiuto')
98
98
  }
99
99
 
100
+ let isRunning = false;
101
+
100
102
  // Main input handler
101
103
  async function handleInput(input) {
102
-
104
+ if (isRunning) {
105
+ console.log('\nā³ Attendi che la risposta precedente sia completata...');
106
+ return;
107
+ }
103
108
  if (handleSpecialCommands(input)) {
104
- return
109
+ return;
105
110
  }
106
-
107
111
  if (input.trim() === '') {
108
- return
112
+ return;
109
113
  }
110
-
111
114
  try {
112
- const result = await agent.run(input)
113
- console.log(`\nšŸ¤– ${assistantName}: ${result.content}`)
115
+ isRunning = true;
116
+ const result = await agent.run(input);
117
+ console.log(`\nšŸ¤– ${assistantName}: ${result.content}`);
118
+ rl.prompt()
114
119
  if (historyFile) {
115
- saveHistory(agent, historyFile)
116
- console.log(`\nšŸ’¾ Cronologia salvata in ${historyFile}`)
120
+ saveHistory(agent, historyFile);
121
+ // console.log(`\nšŸ’¾ Cronologia salvata in ${historyFile}`);
117
122
  }
118
123
  } catch (error) {
119
- console.error('\nāŒ Errore:', error.message)
124
+ console.error('\nāŒ Errore:', error.message);
125
+ } finally {
126
+ isRunning = false;
120
127
  }
121
128
  }
122
129
 
123
130
  // Event listeners
124
131
  rl.on('line', async (input) => {
125
132
  await handleInput(input)
126
- rl.prompt()
133
+
127
134
  })
128
135
 
129
136
  rl.on('close', () => {
@@ -5,23 +5,34 @@ export async function callAI(prompt, temperature = 0.7, model = process.env.MODE
5
5
  apiKey: process.env.OPENROUTER_API_KEY,
6
6
  baseURL: 'https://openrouter.ai/api/v1',
7
7
  })
8
- try {
9
- const res = await openai.chat.completions.create({
10
- model,
11
- prompt: `${systemPrompt}\n\nUser: ${prompt}`,
12
- temperature: temperature
13
- })
14
- if(res.error) {
15
- throw new Error(`OpenAI API error: ${res.error.message}`);
8
+ let lastError;
9
+ for (let attempt = 1; attempt <= retry; attempt++) {
10
+ try {
11
+ const res = await openai.chat.completions.create({
12
+ model,
13
+ prompt: `${systemPrompt}\n\nUser: ${prompt}`,
14
+ temperature: temperature
15
+ })
16
+ if(res.error) {
17
+ throw new Error(`OpenAI API error: ${res.error.message}`);
18
+ }
19
+ const {usage} = res;
20
+ console.log('Usage:', usage);
21
+ const msg = res.choices[0].text.trim();
22
+ if (!msg) {
23
+ throw new Error('Risposta vuota dal modello');
24
+ }
25
+ return msg
26
+ } catch (error) {
27
+ lastError = error;
28
+ if (error.response && error.response.data) {
29
+ console.error('API error response:', error.response.data);
30
+ }
31
+ console.error(`Tentativo ${attempt} fallito:`, error.message);
32
+ if (attempt < retry) {
33
+ await new Promise(r => setTimeout(r, 500 * attempt));
34
+ }
16
35
  }
17
- const msg = res.choices[0].text.trim();
18
- return msg
19
- } catch (error) {
20
- // Mostra il body della risposta se disponibile (es. 400)
21
- if (error.response && error.response.data) {
22
- console.error('API error response:', error.response.data);
23
- }
24
- console.error(error);
25
- throw error;
26
36
  }
37
+ throw lastError;
27
38
  }
package/src/lib/utils.js CHANGED
@@ -8,7 +8,7 @@ const __dirname = dirname(__filename);
8
8
 
9
9
  export async function parseJSON(content, tryAgain = true, logger = console) {
10
10
 
11
- logger.log('šŸ” parseJSON - Contenuto ricevuto (primi 200 caratteri):', content.substring(0, 200));
11
+ //logger.log('šŸ” parseJSON - Contenuto ricevuto (primi 200 caratteri):', content.substring(0, 200));
12
12
 
13
13
  try {
14
14
  // Tenta di trovare il primo blocco JSON valido
@@ -20,9 +20,15 @@ export async function parseJSON(content, tryAgain = true, logger = console) {
20
20
 
21
21
 
22
22
 
23
- const start = content.indexOf(/[\{\[]/)
24
- const end = content.lastIndexOf(/[\}\]]/)
25
- logger.log('šŸ” parseJSON - Posizioni JSON:', { start, end, contentLength: content.length });
23
+ // Trova la posizione del primo '{' o '['
24
+ const startMatch = content.match(/[\{\[]/);
25
+ const start = startMatch ? startMatch.index : -1;
26
+
27
+ // Trova la posizione dell'ultimo '}' o ']'
28
+ const endMatch = [...content.matchAll(/[\}\]]/g)].pop();
29
+ const end = endMatch ? endMatch.index : -1;
30
+
31
+ //logger.log('šŸ” parseJSON - Posizioni JSON:', { start, end, contentLength: content.length });
26
32
 
27
33
  if (start === -1 || end === -1) {
28
34
  console.error('āŒ Nessun blocco JSON trovato nel contenuto');
@@ -31,7 +37,7 @@ export async function parseJSON(content, tryAgain = true, logger = console) {
31
37
  }
32
38
 
33
39
  let jsonString = content.substring(start, end + 1);
34
- logger.log('šŸ” parseJSON - JSON estratto (primi 200 caratteri):', jsonString.substring(0, 200));
40
+ //logger.log('šŸ” parseJSON - JSON estratto (primi 200 caratteri):', jsonString.substring(0, 200));
35
41
 
36
42
  // Escape virgolette interne per evitare crash
37
43
  jsonString = jsonString.replace(/:\s*"([^"]*?)"(?=\s*,|\s*})/g, (match, group) => {
@@ -41,7 +47,7 @@ export async function parseJSON(content, tryAgain = true, logger = console) {
41
47
 
42
48
  try {
43
49
  const parsed = JSON.parse(jsonString);
44
- logger.log('āœ… parseJSON - JSON parsato con successo');
50
+ //logger.log('āœ… parseJSON - JSON parsato con successo');
45
51
  return parsed;
46
52
  } catch (error) {
47
53
  if (!tryAgain) {