@derogab/llm-proxy 0.3.0 → 0.3.2

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,9 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generate = generate;
1
4
  // Dependencies.
2
- import axios from 'axios';
3
- import * as dotenv from 'dotenv';
4
- import { getLlama, LlamaChatSession } from "node-llama-cpp";
5
- import { Ollama } from 'ollama';
6
- import OpenAI from 'openai';
5
+ const axios_1 = require("axios");
6
+ const dotenv = require("dotenv");
7
+ const ollama_1 = require("ollama");
8
+ const openai_1 = require("openai");
7
9
  // Configs.
8
10
  dotenv.config();
9
11
  /**
@@ -14,7 +16,7 @@ dotenv.config();
14
16
  */
15
17
  async function generate_openai(messages) {
16
18
  // Create a new instance of the OpenAI class.
17
- const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, baseURL: process.env.OPENAI_BASE_URL });
19
+ const openai = new openai_1.default({ apiKey: process.env.OPENAI_API_KEY, baseURL: process.env.OPENAI_BASE_URL });
18
20
  // Call the OpenAI API.
19
21
  const chatCompletion = await openai.chat.completions.create({
20
22
  messages: messages,
@@ -31,7 +33,7 @@ async function generate_openai(messages) {
31
33
  */
32
34
  async function generate_ollama(messages) {
33
35
  // Create a new instance of the OpenAI class.
34
- const ollama = new Ollama({ host: process.env.OLLAMA_URI || 'http://localhost:11434' });
36
+ const ollama = new ollama_1.Ollama({ host: process.env.OLLAMA_URI || 'http://localhost:11434' });
35
37
  // Call the Ollama API.
36
38
  const response = await ollama.chat({
37
39
  model: process.env.OLLAMA_MODEL || 'llama3.1',
@@ -77,6 +79,8 @@ function convert_messages_to_chat_history(messages) {
77
79
  * @returns the response string.
78
80
  */
79
81
  async function generate_llama_cpp(messages) {
82
+ // Dynamically import node-llama-cpp only when needed.
83
+ const { getLlama, LlamaChatSession } = await Promise.resolve().then(() => require('node-llama-cpp'));
80
84
  // Create a new instance of the Llama.cpp class.
81
85
  const llama = await getLlama();
82
86
  // Set model to use.
@@ -110,7 +114,7 @@ async function generate_cloudflare(messages) {
110
114
  // Generate API URL based on the environment variables.
111
115
  const model_url = 'https://api.cloudflare.com/client/v4/accounts/' + process.env.CLOUDFLARE_ACCOUNT_ID + '/ai/run/' + process.env.CLOUDFLARE_MODEL;
112
116
  // Call the Cloudflare AI API.
113
- const response = await axios({
117
+ const response = await (0, axios_1.default)({
114
118
  method: 'post',
115
119
  url: model_url,
116
120
  headers: {
@@ -132,7 +136,7 @@ async function generate_cloudflare(messages) {
132
136
  * @param messages the messages to be sent to the LLM.
133
137
  * @returns the response string.
134
138
  */
135
- export async function generate(messages) {
139
+ async function generate(messages) {
136
140
  // Check what LLM to use, based on the environment variables.
137
141
  if (process.env.OPENAI_API_KEY) {
138
142
  // If openai key is available, use openai.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAyJA,4BAsBC;AA/KD,gBAAgB;AAChB,iCAA0B;AAC1B,iCAAiC;AACjC,mCAAgC;AAChC,mCAA4B;AAa5B,WAAW;AACX,MAAM,CAAC,MAAM,EAAE,CAAC;AAEhB;;;;;GAKG;AACH,KAAK,UAAU,eAAe,CAAC,QAAsC;IACnE,6CAA6C;IAC7C,MAAM,MAAM,GAAG,IAAI,gBAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC,CAAC;IACxG,uBAAuB;IACvB,MAAM,cAAc,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;QAC1D,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,aAAa;KACjD,CAAC,CAAC;IACH,uBAAuB;IACvB,OAAO,cAAc,EAAE,OAAO,CAAC,CAAC,CAAC,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@
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 __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.generate = generate;
40
+ // Dependencies.
41
+ const axios_1 = __importDefault(require("axios"));
42
+ const dotenv = __importStar(require("dotenv"));
43
+ const ollama_1 = require("ollama");
44
+ const openai_1 = __importDefault(require("openai"));
45
+ // Configs.
46
+ dotenv.config();
47
+ /**
48
+ * Generate a response from the OpenAI API.
49
+ *
50
+ * @param messages the messages to be sent to the OpenAI API.
51
+ * @returns the response string from the OpenAI API.
52
+ */
53
+ async function generate_openai(messages) {
54
+ // Create a new instance of the OpenAI class.
55
+ const openai = new openai_1.default({ apiKey: process.env.OPENAI_API_KEY, baseURL: process.env.OPENAI_BASE_URL });
56
+ // Call the OpenAI API.
57
+ const chatCompletion = await openai.chat.completions.create({
58
+ messages: messages,
59
+ model: process.env.OPENAI_MODEL || 'gpt-4o-mini',
60
+ });
61
+ // Return the response.
62
+ return chatCompletion?.choices[0]?.message;
63
+ }
64
+ /**
65
+ * Generate a response using Ollama Local API.
66
+ *
67
+ * @param messages the messages to be sent to Ollama.
68
+ * @returns the response string.
69
+ */
70
+ async function generate_ollama(messages) {
71
+ // Create a new instance of the OpenAI class.
72
+ const ollama = new ollama_1.Ollama({ host: process.env.OLLAMA_URI || 'http://localhost:11434' });
73
+ // Call the Ollama API.
74
+ const response = await ollama.chat({
75
+ model: process.env.OLLAMA_MODEL || 'llama3.1',
76
+ messages: messages,
77
+ });
78
+ // Return the response.
79
+ return response['message'];
80
+ }
81
+ /**
82
+ * Convert messages to chat history.
83
+ *
84
+ * Llama.cpp expects the chat history in a custom format.
85
+ * Convert the default messages format to the Llama.cpp format.
86
+ *
87
+ * @param messages the messages to be sent to Llama.cpp.
88
+ * @returns the same messages in the Llama.cpp format.
89
+ */
90
+ function convert_messages_to_chat_history(messages) {
91
+ // Init chat history.
92
+ const chat_history = [];
93
+ // Loop through messages.
94
+ for (const message of messages) {
95
+ if (message.role === 'system' || message.role === 'user') {
96
+ chat_history.push({
97
+ type: message.role,
98
+ text: message.content
99
+ });
100
+ }
101
+ else if (message.role === 'assistant') {
102
+ chat_history.push({
103
+ type: "model",
104
+ response: [message.content]
105
+ });
106
+ }
107
+ }
108
+ // Return the chat history.
109
+ return chat_history;
110
+ }
111
+ /**
112
+ * Generate a response using Llama.cpp Local Model.
113
+ *
114
+ * @param messages the messages to be sent to Llama.cpp.
115
+ * @returns the response string.
116
+ */
117
+ async function generate_llama_cpp(messages) {
118
+ // Dynamically import node-llama-cpp only when needed.
119
+ const { getLlama, LlamaChatSession } = await import('node-llama-cpp');
120
+ // Create a new instance of the Llama.cpp class.
121
+ const llama = await getLlama();
122
+ // Set model to use.
123
+ const modelPath = process.env.LLAMA_CPP_MODEL_PATH;
124
+ if (!modelPath) {
125
+ throw new Error('LLAMA_CPP_MODEL_PATH is not set.');
126
+ }
127
+ const model = await llama.loadModel({
128
+ modelPath: modelPath,
129
+ });
130
+ // Import history into the context.
131
+ const context = await model.createContext();
132
+ const session = new LlamaChatSession({
133
+ contextSequence: context.getSequence()
134
+ });
135
+ if (messages.length > 1)
136
+ session.setChatHistory(convert_messages_to_chat_history(messages.slice(0, -1)));
137
+ // Generate and return the response.
138
+ return {
139
+ role: 'assistant',
140
+ content: await session.prompt(messages[messages.length - 1]?.content || ''),
141
+ };
142
+ }
143
+ /**
144
+ * Generate a response using Cloudflare AI API.
145
+ *
146
+ * @param messages the messages to be sent to Cloudflare AI.
147
+ * @returns the response string.
148
+ */
149
+ async function generate_cloudflare(messages) {
150
+ // Generate API URL based on the environment variables.
151
+ const model_url = 'https://api.cloudflare.com/client/v4/accounts/' + process.env.CLOUDFLARE_ACCOUNT_ID + '/ai/run/' + process.env.CLOUDFLARE_MODEL;
152
+ // Call the Cloudflare AI API.
153
+ const response = await (0, axios_1.default)({
154
+ method: 'post',
155
+ url: model_url,
156
+ headers: {
157
+ 'Authorization': 'Bearer ' + process.env.CLOUDFLARE_AUTH_KEY,
158
+ 'Content-Type': 'application/json',
159
+ },
160
+ data: {
161
+ messages: messages,
162
+ },
163
+ });
164
+ // Extract the response message.
165
+ const msg = response.data.success ? response.data.result.response : '';
166
+ // Return the response.
167
+ return { role: 'assistant', content: msg };
168
+ }
169
+ /**
170
+ * Generate a response using an LLM.
171
+ *
172
+ * @param messages the messages to be sent to the LLM.
173
+ * @returns the response string.
174
+ */
175
+ async function generate(messages) {
176
+ // Check what LLM to use, based on the environment variables.
177
+ if (process.env.OPENAI_API_KEY) {
178
+ // If openai key is available, use openai.
179
+ return await generate_openai(messages);
180
+ }
181
+ else if (process.env.CLOUDFLARE_ACCOUNT_ID && process.env.CLOUDFLARE_AUTH_KEY && process.env.CLOUDFLARE_MODEL) {
182
+ // If cloudflare keys are available, use cloudflare.
183
+ return await generate_cloudflare(messages);
184
+ }
185
+ else if (process.env.OLLAMA_URI) {
186
+ // If ollama is available, use ollama.
187
+ return await generate_ollama(messages);
188
+ }
189
+ else if (process.env.LLAMA_CPP_MODEL_PATH) {
190
+ // If llama_cpp is available, use llama_cpp.
191
+ return await generate_llama_cpp(messages);
192
+ }
193
+ else {
194
+ // Throw an error if no LLM is available.
195
+ throw new Error('No available LLM found.');
196
+ }
197
+ }
198
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyJA,4BAsBC;AA/KD,gBAAgB;AAChB,kDAA0B;AAC1B,+CAAiC;AACjC,mCAAgC;AAChC,oDAA4B;AAa5B,WAAW;AACX,MAAM,CAAC,MAAM,EAAE,CAAC;AAEhB;;;;;GAKG;AACH,KAAK,UAAU,eAAe,CAAC,QAAsC;IACnE,6CAA6C;IAC7C,MAAM,MAAM,GAAG,IAAI,gBAAM,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC,CAAC;IACxG,uBAAuB;IACvB,MAAM,cAAc,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;QAC1D,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,IAAI,aAAa;KACjD,CAAC,CAAC;IACH,uBAAuB;IACvB,OAAO,cAAc,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAqC,CAAC;AAC3E,CAAC;AAED;;;;;GAKG;AACH,KAAK,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ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEtC,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,0BAA0B,GAAG,OAAO,GAAG,iBAAiB,CAAC;AAoIzF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAsBxF"}
package/package.json CHANGED
@@ -1,19 +1,37 @@
1
1
  {
2
2
  "name": "@derogab/llm-proxy",
3
3
  "description": "A simple and lightweight proxy for seamless integration with multiple LLM providers including OpenAI, Ollama, and Cloudflare AI",
4
- "version": "0.3.0",
4
+ "version": "0.3.2",
5
5
  "author": "derogab",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "https://github.com/derogab/llm-proxy.git"
10
10
  },
11
- "main": "dist/index.js",
12
- "types": "dist/index.d.ts",
13
- "type": "module",
11
+ "main": "./dist/cjs/index.js",
12
+ "module": "./dist/esm/index.js",
13
+ "types": "./dist/types/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/types/index.d.ts",
18
+ "default": "./dist/esm/index.js"
19
+ },
20
+ "require": {
21
+ "types": "./dist/types/index.d.ts",
22
+ "default": "./dist/cjs/index.js"
23
+ }
24
+ }
25
+ },
14
26
  "scripts": {
15
- "build": "tsc"
27
+ "build": "npm run build:cjs && npm run build:esm && npm run build:types",
28
+ "build:cjs": "tsc -p tsconfig.cjs.json",
29
+ "build:esm": "tsc -p tsconfig.esm.json",
30
+ "build:types": "tsc -p tsconfig.types.json"
16
31
  },
32
+ "files": [
33
+ "dist"
34
+ ],
17
35
  "keywords": [
18
36
  "LLM",
19
37
  "proxy",
@@ -24,10 +42,10 @@
24
42
  "typescript": "5.9.2"
25
43
  },
26
44
  "dependencies": {
27
- "axios": "1.11.0",
28
- "dotenv": "17.2.1",
45
+ "axios": "1.12.2",
46
+ "dotenv": "17.2.2",
29
47
  "node-llama-cpp": "3.13.0",
30
- "ollama": "0.5.17",
31
- "openai": "5.16.0"
48
+ "ollama": "0.6.0",
49
+ "openai": "5.23.1"
32
50
  }
33
51
  }
@@ -1 +0,0 @@
1
- * @derogab
@@ -1,27 +0,0 @@
1
- # Dependabot Configuration:
2
- # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
3
-
4
- version: 2
5
- updates:
6
-
7
- # Maintain dependencies for GitHub Actions
8
- - package-ecosystem: 'github-actions'
9
- directory: '/'
10
- target-branch: 'master'
11
- schedule:
12
- interval: 'monthly'
13
- assignees:
14
- - 'derogab'
15
- labels:
16
- - 'dependencies'
17
-
18
- # Maintain dependencies for NPM
19
- - package-ecosystem: 'npm'
20
- directory: '/'
21
- target-branch: 'master'
22
- schedule:
23
- interval: 'monthly'
24
- assignees:
25
- - 'derogab'
26
- labels:
27
- - 'dependencies'
@@ -1,121 +0,0 @@
1
- name: Release and publish package to NPM
2
-
3
- on:
4
- push:
5
- # Publish `v1.2.3` tags as releases.
6
- tags:
7
- - v*
8
-
9
- jobs:
10
- # Release the TAG to GitHub.
11
- release:
12
- name: Release pushed tag
13
- if: startsWith(github.ref, 'refs/tags/')
14
- permissions:
15
- contents: write
16
- runs-on: ubuntu-latest
17
- steps:
18
- - name: Create release
19
- env:
20
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
21
- tag: ${{ github.ref_name }}
22
- run: |
23
- gh release create "$tag" \
24
- --repo="$GITHUB_REPOSITORY" \
25
- --title="v${tag#v}" \
26
- --generate-notes
27
- # Publish the package.
28
- publish-npm:
29
- name: Publish Package on NPM
30
- needs: release
31
- runs-on: ubuntu-latest
32
- permissions:
33
- contents: read
34
- id-token: write
35
- steps:
36
- - name: Checkout
37
- uses: actions/checkout@v5
38
- - name: Setup Node
39
- uses: actions/setup-node@v4
40
- with:
41
- node-version: '20.x'
42
- cache: 'npm'
43
- registry-url: 'https://registry.npmjs.org'
44
- always-auth: true
45
- - name: Install dependencies (clean)
46
- run: npm ci
47
- - name: Type check
48
- run: npx tsc -p tsconfig.json --noEmit
49
- - name: Run tests
50
- run: npm test --if-present
51
- - name: Build
52
- run: |
53
- if npm run | grep -q "build"; then
54
- npm run build
55
- else
56
- # Fall back to a standard TS build if no script is defined
57
- npx tsc -p tsconfig.json
58
- fi
59
- - name: Verify tag matches package.json version
60
- run: |
61
- PKG_VERSION="$(node -p "require('./package.json').version")"
62
- TAG_VERSION="${GITHUB_REF_NAME#v}" # supports tags like v1.2.3
63
- echo "package.json: $PKG_VERSION"
64
- echo "release tag: $TAG_VERSION"
65
- if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then
66
- echo "Release tag ($TAG_VERSION) does not match package.json version ($PKG_VERSION)."
67
- exit 1
68
- fi
69
- - name: Show publish contents (dry run)
70
- run: npm pack --dry-run
71
- - name: Publish to npm (with provenance)
72
- env:
73
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
74
- run: npm publish --provenance --access public
75
- publish-github:
76
- name: Publish Package on GitHub
77
- needs: release
78
- runs-on: ubuntu-latest
79
- permissions:
80
- contents: read
81
- id-token: write
82
- steps:
83
- - name: Checkout
84
- uses: actions/checkout@v5
85
- - name: Setup Node
86
- uses: actions/setup-node@v4
87
- with:
88
- node-version: '20.x'
89
- cache: 'npm'
90
- registry-url: 'https://npm.pkg.github.com'
91
- always-auth: true
92
- - name: Install dependencies (clean)
93
- run: npm ci
94
- - name: Type check
95
- run: npx tsc -p tsconfig.json --noEmit
96
- - name: Run tests
97
- run: npm test --if-present
98
- - name: Build
99
- run: |
100
- if npm run | grep -q "build"; then
101
- npm run build
102
- else
103
- # Fall back to a standard TS build if no script is defined
104
- npx tsc -p tsconfig.json
105
- fi
106
- - name: Verify tag matches package.json version
107
- run: |
108
- PKG_VERSION="$(node -p "require('./package.json').version")"
109
- TAG_VERSION="${GITHUB_REF_NAME#v}" # supports tags like v1.2.3
110
- echo "package.json: $PKG_VERSION"
111
- echo "release tag: $TAG_VERSION"
112
- if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then
113
- echo "Release tag ($TAG_VERSION) does not match package.json version ($PKG_VERSION)."
114
- exit 1
115
- fi
116
- - name: Show publish contents (dry run)
117
- run: npm pack --dry-run
118
- - name: Publish to npm (with provenance)
119
- env:
120
- NODE_AUTH_TOKEN: ${{ secrets.NPM_GITHUB_TOKEN }}
121
- run: npm publish --provenance --access public
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAEnE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEtC,MAAM,MAAM,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,0BAA0B,GAAG,OAAO,GAAG,iBAAiB,CAAC;AAiIzF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAsBxF"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,gBAAgB;AAChB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,QA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CAAC,gBAAgB,EAAE,CAAC;QAChH,oDAAoD;QACpD,OAAO,MAAM,mBAAmB,CAAC,QAA+B,CAAC,CAAC;IAEpE,CAAC;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC;QAClC,sCAAsC;QACtC,OAAO,MAAM,eAAe,CAAC,QAAqB,CAAC,CAAC;IAEtD,CAAC;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,CAAC;QAC5C,4CAA4C;QAC5C,OAAO,MAAM,kBAAkB,CAAC,QAAqB,CAAC,CAAC;IAEzD,CAAC;SAAM,CAAC;QACN,yCAAyC;QACzC,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC"}
package/src/index.ts DELETED
@@ -1,175 +0,0 @@
1
- // Dependencies.
2
- import axios from 'axios';
3
- import * as dotenv from 'dotenv';
4
- import { getLlama, LlamaChatSession } from "node-llama-cpp";
5
- import { Ollama } from 'ollama';
6
- import OpenAI from 'openai';
7
-
8
- // Types.
9
- import type { ChatCompletionMessageParam } from 'openai/resources';
10
- import type { ChatHistoryItem } from 'node-llama-cpp';
11
- import type { Message } from 'ollama';
12
-
13
- export type CloudflareMessage = {
14
- role: string;
15
- content: string;
16
- };
17
-
18
- export type MessageInputParam = ChatCompletionMessageParam | Message | CloudflareMessage;
19
-
20
- // Configs.
21
- dotenv.config();
22
-
23
- /**
24
- * Generate a response from the OpenAI API.
25
- *
26
- * @param messages the messages to be sent to the OpenAI API.
27
- * @returns the response string from the OpenAI API.
28
- */
29
- async function generate_openai(messages: ChatCompletionMessageParam[]): Promise<ChatCompletionMessageParam> {
30
- // Create a new instance of the OpenAI class.
31
- const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, baseURL: process.env.OPENAI_BASE_URL });
32
- // Call the OpenAI API.
33
- const chatCompletion = await openai.chat.completions.create({
34
- messages: messages,
35
- model: process.env.OPENAI_MODEL || 'gpt-4o-mini',
36
- });
37
- // Return the response.
38
- return chatCompletion?.choices[0]?.message as ChatCompletionMessageParam;
39
- }
40
-
41
- /**
42
- * Generate a response using Ollama Local API.
43
- *
44
- * @param messages the messages to be sent to Ollama.
45
- * @returns the response string.
46
- */
47
- async function generate_ollama(messages: Message[]): Promise<Message> {
48
- // Create a new instance of the OpenAI class.
49
- const ollama = new Ollama({ host: process.env.OLLAMA_URI || 'http://localhost:11434' });
50
- // Call the Ollama API.
51
- const response = await ollama.chat({
52
- model: process.env.OLLAMA_MODEL || 'llama3.1',
53
- messages: messages,
54
- });
55
- // Return the response.
56
- return response['message'];
57
- }
58
-
59
- /**
60
- * Convert messages to chat history.
61
- *
62
- * Llama.cpp expects the chat history in a custom format.
63
- * Convert the default messages format to the Llama.cpp format.
64
- *
65
- * @param messages the messages to be sent to Llama.cpp.
66
- * @returns the same messages in the Llama.cpp format.
67
- */
68
- function convert_messages_to_chat_history(messages: Message[]): ChatHistoryItem[] {
69
- // Init chat history.
70
- const chat_history: ChatHistoryItem[] = [];
71
- // Loop through messages.
72
- for (const message of messages) {
73
- if (message.role === 'system' || message.role === 'user') {
74
- chat_history.push({
75
- type: message.role,
76
- text: message.content
77
- });
78
- } else if (message.role === 'assistant') {
79
- chat_history.push({
80
- type: "model",
81
- response: [message.content]
82
- });
83
- }
84
- }
85
- // Return the chat history.
86
- return chat_history;
87
- }
88
-
89
- /**
90
- * Generate a response using Llama.cpp Local Model.
91
- *
92
- * @param messages the messages to be sent to Llama.cpp.
93
- * @returns the response string.
94
- */
95
- async function generate_llama_cpp(messages: Message[]): Promise<Message> {
96
- // Create a new instance of the Llama.cpp class.
97
- const llama = await getLlama();
98
- // Set model to use.
99
- const modelPath = process.env.LLAMA_CPP_MODEL_PATH;
100
- if (!modelPath) {
101
- throw new Error('LLAMA_CPP_MODEL_PATH is not set.');
102
- }
103
- const model = await llama.loadModel({
104
- modelPath: modelPath,
105
- });
106
- // Import history into the context.
107
- const context = await model.createContext();
108
- const session = new LlamaChatSession({
109
- contextSequence: context.getSequence()
110
- });
111
- if (messages.length > 1) session.setChatHistory(convert_messages_to_chat_history(messages.slice(0, -1)));
112
-
113
- // Generate and return the response.
114
- return {
115
- role: 'assistant',
116
- content: await session.prompt(messages[messages.length - 1]?.content || ''),
117
- };
118
- }
119
-
120
- /**
121
- * Generate a response using Cloudflare AI API.
122
- *
123
- * @param messages the messages to be sent to Cloudflare AI.
124
- * @returns the response string.
125
- */
126
- async function generate_cloudflare(messages: CloudflareMessage[]): Promise<CloudflareMessage> {
127
- // Generate API URL based on the environment variables.
128
- const model_url = 'https://api.cloudflare.com/client/v4/accounts/' + process.env.CLOUDFLARE_ACCOUNT_ID + '/ai/run/' + process.env.CLOUDFLARE_MODEL;
129
- // Call the Cloudflare AI API.
130
- const response = await axios({
131
- method: 'post',
132
- url: model_url,
133
- headers: {
134
- 'Authorization': 'Bearer ' + process.env.CLOUDFLARE_AUTH_KEY,
135
- 'Content-Type' : 'application/json',
136
- },
137
- data: {
138
- messages: messages,
139
- },
140
- });
141
- // Extract the response message.
142
- const msg = response.data.success ? response.data.result.response : '';
143
- // Return the response.
144
- return { role: 'assistant', content: msg };
145
- }
146
-
147
- /**
148
- * Generate a response using an LLM.
149
- *
150
- * @param messages the messages to be sent to the LLM.
151
- * @returns the response string.
152
- */
153
- export async function generate(messages: MessageInputParam[]): Promise<MessageInputParam> {
154
- // Check what LLM to use, based on the environment variables.
155
- if (process.env.OPENAI_API_KEY) {
156
- // If openai key is available, use openai.
157
- return await generate_openai(messages as ChatCompletionMessageParam[]);
158
-
159
- } else if (process.env.CLOUDFLARE_ACCOUNT_ID && process.env.CLOUDFLARE_AUTH_KEY && process.env.CLOUDFLARE_MODEL) {
160
- // If cloudflare keys are available, use cloudflare.
161
- return await generate_cloudflare(messages as CloudflareMessage[]);
162
-
163
- } else if (process.env.OLLAMA_URI) {
164
- // If ollama is available, use ollama.
165
- return await generate_ollama(messages as Message[]);
166
-
167
- } else if (process.env.LLAMA_CPP_MODEL_PATH) {
168
- // If llama_cpp is available, use llama_cpp.
169
- return await generate_llama_cpp(messages as Message[]);
170
-
171
- } else {
172
- // Throw an error if no LLM is available.
173
- throw new Error('No available LLM found.');
174
- }
175
- }
package/tsconfig.json DELETED
@@ -1,44 +0,0 @@
1
- {
2
- // Visit https://aka.ms/tsconfig to read more about this file
3
- "compilerOptions": {
4
- // File Layout
5
- "rootDir": "./src",
6
- "outDir": "./dist",
7
-
8
- // Environment Settings
9
- // See also https://aka.ms/tsconfig/module
10
- "module": "nodenext",
11
- "target": "esnext",
12
- "types": [],
13
- // For nodejs:
14
- // "lib": ["esnext"],
15
- // "types": ["node"],
16
- // and npm install -D @types/node
17
-
18
- // Other Outputs
19
- "sourceMap": true,
20
- "declaration": true,
21
- "declarationMap": true,
22
-
23
- // Stricter Typechecking Options
24
- "noUncheckedIndexedAccess": true,
25
- "exactOptionalPropertyTypes": true,
26
-
27
- // Style Options
28
- // "noImplicitReturns": true,
29
- // "noImplicitOverride": true,
30
- // "noUnusedLocals": true,
31
- // "noUnusedParameters": true,
32
- // "noFallthroughCasesInSwitch": true,
33
- // "noPropertyAccessFromIndexSignature": true,
34
-
35
- // Recommended Options
36
- "strict": true,
37
- "jsx": "react-jsx",
38
- "verbatimModuleSyntax": true,
39
- "isolatedModules": true,
40
- "noUncheckedSideEffectImports": true,
41
- "moduleDetection": "force",
42
- "skipLibCheck": true,
43
- }
44
- }
File without changes