jsvelox 1.7.0 → 1.9.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 (3) hide show
  1. package/package.json +1 -1
  2. package/src/index.js +139 -122
  3. package/test.js +25 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsvelox",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "description": "Lightweight JS library for AI integration and developer utilities",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/index.js CHANGED
@@ -1,143 +1,160 @@
1
- export class VeloxAI {
2
- // TR: Kütüphaneyi başlatır. API key, provider (claude/openai/gemini), model ve timeout ayarlarını alır.
3
- // Eksik bilgi girilirse hata fırlatır.
4
- // EN: Initializes the library. Takes API key, provider (claude/openai/gemini), model and timeout settings.
5
- // Throws an error if required fields are missing.
6
- constructor(config) {
7
- if (!config.apiKey) {
8
- throw new Error('API key zorunlu!')
9
- }
10
- if (!config.provider) {
11
- throw new Error('Provider zorunlu! claude, openai veya gemini kullan.')
12
- }
13
- this.provider = config.provider.toLowerCase().trim()
14
- this.apiKey = config.apiKey.trim()
15
- this.model = config.model ? config.model.trim() : null
16
- this.memory = []
17
- this.timeout = typeof config.timeout === 'number' && config.timeout > 0
18
- ? config.timeout
19
- : 30000
20
- }
21
-
22
- // TR: Kullanıcının mesajını seçili yapay zekaya gönderir ve cevabı döndürür.
23
- // Konuşma geçmişini (memory) otomatik yönetir. Hata olursa memory'i temizler.
24
- // EN: Sends the user's message to the selected AI and returns the response.
25
- // Automatically manages conversation history (memory). Clears memory on error.
26
- async send(message) {
27
- if (!message || typeof message !== 'string' || message.trim() === '') {
28
- throw new Error('Mesaj boş olamaz!')
1
+ export class VeloxAI {
2
+ // TR: Kütüphaneyi başlatır. API key, provider (claude/openai/gemini), model ve timeout ayarlarını alır.
3
+ // Eksik bilgi girilirse hata fırlatır.
4
+ // EN: Initializes the library. Takes API key, provider (claude/openai/gemini), model and timeout settings.
5
+ // Throws an error if required fields are missing.
6
+ constructor(config) {
7
+ if (!config.apiKey) {
8
+ throw new Error('API key zorunlu!')
9
+ }
10
+ if (!config.provider) {
11
+ throw new Error('Provider zorunlu! claude, openai veya gemini kullan.')
12
+ }
13
+ this.provider = config.provider.toLowerCase().trim()
14
+ this.apiKey = config.apiKey.trim()
15
+ this.model = config.model ? config.model.trim() : null
16
+ this.memory = []
17
+ this.memoryLimit = config.memoryLimit || null
18
+ this.timeout = typeof config.timeout === 'number' && config.timeout > 0
19
+ ? config.timeout
20
+ : 30000
29
21
  }
30
22
 
31
- this.memory.push({ role: 'user', content: message })
23
+ // TR: Kullanıcının mesajını seçili yapay zekaya gönderir ve cevabı döndürür.
24
+ // Konuşma geçmişini (memory) otomatik yönetir. Hata olursa memory'i temizler.
25
+ // EN: Sends the user's message to the selected AI and returns the response.
26
+ // Automatically manages conversation history (memory). Clears memory on error.
27
+ async send(message) {
28
+ if (!message || typeof message !== 'string' || message.trim() === '') {
29
+ throw new Error('Mesaj boş olamaz!')
30
+ }
32
31
 
33
- const timeoutPromise = new Promise((_, reject) =>
34
- setTimeout(() => reject(new Error('Zaman aşımı! AI cevap vermedi.')), this.timeout)
35
- )
32
+ this.memory.push({ role: 'user', content: message })
36
33
 
37
- let cevap
38
- try {
39
- if (this.provider === 'claude') {
40
- cevap = await Promise.race([this._sendClaude(this.memory), timeoutPromise])
41
- } else if (this.provider === 'openai') {
42
- cevap = await Promise.race([this._sendOpenAI(this.memory), timeoutPromise])
43
- } else if (this.provider === 'gemini') {
44
- cevap = await Promise.race([this._sendGemini(this.memory), timeoutPromise])
45
- } else {
46
- throw new Error('Geçersiz provider. claude, openai veya gemini kullan.')
34
+ if (this.memoryLimit && this.memory.length > this.memoryLimit) {
35
+ this.memory = this.memory.slice(-this.memoryLimit)
47
36
  }
48
- } catch (err) {
49
- this.memory.pop()
50
- throw err
51
- }
52
37
 
53
- this.memory.push({ role: 'assistant', content: cevap })
54
- return cevap
55
- }
38
+ const timeoutPromise = new Promise((_, reject) =>
39
+ setTimeout(() => reject(new Error('Zaman aşımı! AI cevap vermedi.')), this.timeout)
40
+ )
56
41
 
57
- // TR: Mesajı gönderir, hata olursa belirtilen sayıda tekrar dener (varsayılan 3 kez).
58
- // Her deneme arasında 1 saniye bekler. Tüm denemeler başarısız olursa hatayı fırlatır.
59
- // EN: Sends the message and retries on failure up to the specified number of times (default 3).
60
- // Waits 1 second between retries. Throws the error if all attempts fail.
61
- async sendWithRetry(message, retries = 3) {
62
- for (let i = 0; i < retries; i++) {
42
+ let cevap
63
43
  try {
64
- return await this.send(message)
44
+ if (this.provider === 'claude') {
45
+ cevap = await Promise.race([this._sendClaude(this.memory), timeoutPromise])
46
+ } else if (this.provider === 'openai') {
47
+ cevap = await Promise.race([this._sendOpenAI(this.memory), timeoutPromise])
48
+ } else if (this.provider === 'gemini') {
49
+ cevap = await Promise.race([this._sendGemini(this.memory), timeoutPromise])
50
+ } else {
51
+ throw new Error('Geçersiz provider. claude, openai veya gemini kullan.')
52
+ }
65
53
  } catch (err) {
66
54
  this.memory.pop()
67
- if (i === retries - 1) throw err
68
- await new Promise(r => setTimeout(r, 1000))
55
+ throw err
69
56
  }
57
+
58
+ this.memory.push({ role: 'assistant', content: cevap })
59
+ return cevap
70
60
  }
71
- }
72
61
 
73
- // TR: Mesajı Anthropic Claude API'sine gönderir ve metin cevabı döndürür.
74
- // Dahili metottur, doğrudan çağrılmamalıdır.
75
- // EN: Sends the message to Anthropic Claude API and returns the text response.
76
- // Internal method, should not be called directly.
77
- async _sendClaude(memory) {
78
- const response = await fetch('https://api.anthropic.com/v1/messages', {
79
- method: 'POST',
80
- headers: {
81
- 'Content-Type': 'application/json',
82
- 'x-api-key': this.apiKey,
83
- 'anthropic-version': '2023-06-01'
84
- },
85
- body: JSON.stringify({
86
- model: this.model || 'claude-3-5-sonnet-20241022',
87
- max_tokens: 1024,
88
- messages: memory
62
+ // TR: Mesajı gönderir, hata olursa belirtilen sayıda tekrar dener (varsayılan 3 kez).
63
+ // Her deneme arasında 1 saniye bekler. Tüm denemeler başarısız olursa hatayı fırlatır.
64
+ // EN: Sends the message and retries on failure up to the specified number of times (default 3).
65
+ // Waits 1 second between retries. Throws the error if all attempts fail.
66
+ async sendWithRetry(message, retries = 3) {
67
+ for (let i = 0; i < retries; i++) {
68
+ try {
69
+ return await this.send(message)
70
+ } catch (err) {
71
+ this.memory.pop()
72
+ if (i === retries - 1) throw err
73
+ await new Promise(r => setTimeout(r, 1000))
74
+ }
75
+ }
76
+ }
77
+
78
+ // TR: Konuşma geçmişini temizler. Yeni bir konuşma başlatmak için kullanılır.
79
+ // EN: Clears the conversation history. Used to start a new conversation.
80
+ clearMemory() {
81
+ this.memory = []
82
+ }
83
+
84
+ // TR: Mevcut konuşma geçmişini döndürür.
85
+ // EN: Returns the current conversation history.
86
+ getMemory() {
87
+ return this.memory
88
+ }
89
+
90
+ // TR: Mesajı Anthropic Claude API'sine gönderir ve metin cevabı döndürür.
91
+ // Dahili metottur, doğrudan çağrılmamalıdır.
92
+ // EN: Sends the message to Anthropic Claude API and returns the text response.
93
+ // Internal method, should not be called directly.
94
+ async _sendClaude(memory) {
95
+ const response = await fetch('https://api.anthropic.com/v1/messages', {
96
+ method: 'POST',
97
+ headers: {
98
+ 'Content-Type': 'application/json',
99
+ 'x-api-key': this.apiKey,
100
+ 'anthropic-version': '2023-06-01'
101
+ },
102
+ body: JSON.stringify({
103
+ model: this.model || 'claude-3-5-sonnet-20241022',
104
+ max_tokens: 1024,
105
+ messages: memory
106
+ })
89
107
  })
90
- })
91
- const data = await response.json()
92
- if (!response.ok) {
93
- throw new Error(`Claude hata: ${data.error?.message || 'Bilinmeyen hata'}`)
108
+ const data = await response.json()
109
+ if (!response.ok) {
110
+ throw new Error(`Claude hata: ${data.error?.message || 'Bilinmeyen hata'}`)
111
+ }
112
+ return data.content[0].text
94
113
  }
95
- return data.content[0].text
96
- }
97
114
 
98
- // TR: Mesajı OpenAI API'sine gönderir ve metin cevabı döndürür.
99
- // Dahili metottur, doğrudan çağrılmamalıdır.
100
- // EN: Sends the message to OpenAI API and returns the text response.
101
- // Internal method, should not be called directly.
102
- async _sendOpenAI(memory) {
103
- const response = await fetch('https://api.openai.com/v1/chat/completions', {
104
- method: 'POST',
105
- headers: {
106
- 'Content-Type': 'application/json',
107
- 'Authorization': `Bearer ${this.apiKey}`
108
- },
109
- body: JSON.stringify({
110
- model: this.model || 'gpt-4o-mini',
111
- messages: memory
115
+ // TR: Mesajı OpenAI API'sine gönderir ve metin cevabı döndürür.
116
+ // Dahili metottur, doğrudan çağrılmamalıdır.
117
+ // EN: Sends the message to OpenAI API and returns the text response.
118
+ // Internal method, should not be called directly.
119
+ async _sendOpenAI(memory) {
120
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
121
+ method: 'POST',
122
+ headers: {
123
+ 'Content-Type': 'application/json',
124
+ 'Authorization': `Bearer ${this.apiKey}`
125
+ },
126
+ body: JSON.stringify({
127
+ model: this.model || 'gpt-4o-mini',
128
+ messages: memory
129
+ })
112
130
  })
113
- })
114
- const data = await response.json()
115
- if (!response.ok) {
116
- throw new Error(`OpenAI hata: ${data.error?.message || 'Bilinmeyen hata'}`)
131
+ const data = await response.json()
132
+ if (!response.ok) {
133
+ throw new Error(`OpenAI hata: ${data.error?.message || 'Bilinmeyen hata'}`)
134
+ }
135
+ return data.choices[0].message.content
117
136
  }
118
- return data.choices[0].message.content
119
- }
120
137
 
121
- // TR: Mesajı Google Gemini API'sine gönderir ve metin cevabı döndürür.
122
- // Konuşma geçmişini Gemini'nin beklediği formata dönüştürür.
123
- // EN: Sends the message to Google Gemini API and returns the text response.
124
- // Converts conversation history into the format expected by Gemini.
125
- async _sendGemini(memory) {
126
- const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${this.apiKey}`
127
- const contents = memory.map(m => ({
128
- role: m.role === 'assistant' ? 'model' : 'user',
129
- parts: [{ text: m.content }]
130
- }))
138
+ // TR: Mesajı Google Gemini API'sine gönderir ve metin cevabı döndürür.
139
+ // Konuşma geçmişini Gemini'nin beklediği formata dönüştürür.
140
+ // EN: Sends the message to Google Gemini API and returns the text response.
141
+ // Converts conversation history into the format expected by Gemini.
142
+ async _sendGemini(memory) {
143
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${this.apiKey}`
144
+ const contents = memory.map(m => ({
145
+ role: m.role === 'assistant' ? 'model' : 'user',
146
+ parts: [{ text: m.content }]
147
+ }))
131
148
 
132
- const response = await fetch(url, {
133
- method: 'POST',
134
- headers: { 'Content-Type': 'application/json' },
135
- body: JSON.stringify({ contents })
136
- })
137
- const data = await response.json()
138
- if (!response.ok) {
139
- throw new Error(`Gemini hata: ${data.error?.message || 'Bilinmeyen hata'}`)
149
+ const response = await fetch(url, {
150
+ method: 'POST',
151
+ headers: { 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({ contents })
153
+ })
154
+ const data = await response.json()
155
+ if (!response.ok) {
156
+ throw new Error(`Gemini hata: ${data.error?.message || 'Bilinmeyen hata'}`)
157
+ }
158
+ return data.candidates[0].content.parts[0].text
140
159
  }
141
- return data.candidates[0].content.parts[0].text
142
- }
143
- }
160
+ }
package/test.js CHANGED
@@ -1,9 +1,31 @@
1
+ // -------------------------------V1.8 VE ÖNCESİ İÇİNDİR--------------------------------
2
+ // import { VeloxAI } from './src/index.js'
3
+
4
+ // const ai = new VeloxAI({
5
+ // provider: 'claude',
6
+ // apiKey: 'BURAYA-API-KEY-GELECEK'
7
+ // })
8
+
9
+ // const cevap = await ai.send('merhaba')
10
+ // console.log(cevap)
11
+
12
+ //----------------------------------------V1.9 VE SONRASI İÇİNDİR-----------------------
1
13
  import { VeloxAI } from './src/index.js'
2
14
 
3
15
  const ai = new VeloxAI({
4
- provider: 'claude',
5
- apiKey: 'BURAYA-API-KEY-GELECEK'
16
+ provider: 'gemini',
17
+ apiKey: 'BURAYA-API-KEY-GELECEK',
18
+ memoryLimit: 10,
19
+ timeout: 15000
6
20
  })
7
21
 
22
+ // Mesaj gönder
8
23
  const cevap = await ai.send('merhaba')
9
- console.log(cevap)
24
+ console.log('Cevap:', cevap)
25
+
26
+ // Memory görüntüle
27
+ console.log('Memory:', ai.getMemory())
28
+
29
+ // Memory temizle
30
+ ai.clearMemory()
31
+ console.log('Memory temizlendi:', ai.getMemory())