huxy-llm-api 1.0.0-beta.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 yiru
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,212 @@
1
+ # huxy-llm-api
2
+
3
+ 一个简洁、易用的用于简化 Ollama 和 OpenAI API 调用的 Node.js 库。支持流式响应和自定义配置,适用于快速集成大语言模型服务。
4
+
5
+ ## 特性
6
+
7
+ - **统一接口**:提供一致的 API 调用方式,支持 Ollama 和 OpenAI 两种服务
8
+ - **流式支持**:内置流式响应处理,支持实时回调
9
+ - **灵活配置**:支持自定义模型参数和 API 配置
10
+ - **错误处理**:内置参数验证和错误处理机制
11
+ - **多功能支持**:支持聊天、文本生成、响应处理等多种 AI 功能
12
+ - **自定义 Fetch**:使用 `Undici` 实现高性能 HTTP 请求
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ npm install huxy-llm-api
18
+ # 或
19
+ pnpm add huxy-llm-api
20
+ # 或
21
+ yarn add huxy-llm-api
22
+ ```
23
+
24
+ ## 快速开始
25
+
26
+ ### 基本用法
27
+
28
+ ```javascript
29
+ import startApi from 'huxy-llm-api';
30
+
31
+ // 初始化 Ollama API
32
+ const ollamaApi = startApi('ollama', {
33
+ apiKey: 'your-api-key',
34
+ host: 'http://localhost:11434',
35
+ });
36
+
37
+ // 初始化 OpenAI API
38
+ const openaiApi = startApi('openai', {
39
+ apiKey: 'your-api-key',
40
+ baseURL: 'https://api.openai.com/v1',
41
+ });
42
+ ```
43
+
44
+ ### 调用示例
45
+
46
+ #### Ollama - 生成文本
47
+
48
+ ```javascript
49
+ const result = await ollamaApi.generate('你好', {
50
+ model: 'qwen3-vl',
51
+ stream: false,
52
+ options: {
53
+ temperature: 0.15,
54
+ top_p: 0.9,
55
+ },
56
+ }, (message) => {
57
+ console.log('实时响应:', message);
58
+ });
59
+
60
+ console.log('最终结果:', result);
61
+ ```
62
+
63
+ #### OpenAI - 聊天对话
64
+
65
+ ```javascript
66
+ const response = await openaiApi.chat('你是谁', {
67
+ model: 'gpt-3.5-turbo',
68
+ temperature: 0.7,
69
+ stream: true,
70
+ }, (message, rawResponse) => {
71
+ console.log('实时消息:', message);
72
+ console.log('原始响应:', rawResponse);
73
+ });
74
+
75
+ console.log('对话结果:', response);
76
+ ```
77
+
78
+ ## API 文档
79
+
80
+ ### `startApi(apiType, userConfig)`
81
+
82
+ 初始化 LLM API 客户端。
83
+
84
+ **参数:**
85
+
86
+ - `apiType`: `'ollama'` 或 `'openai'` - 指定要使用的 API 类型
87
+ - `userConfig`: 对象 - 自定义配置,会覆盖默认配置
88
+
89
+ **返回:** API 客户端实例,包含以下方法:
90
+
91
+ ### Ollama 方法
92
+
93
+ - `generate(prompt, configs, callback)`: 文本生成
94
+ - `chat(prompt, configs, callback)`: 聊天对话
95
+ - `responses(prompt, configs, callback)`: 结构化响应
96
+
97
+ ### OpenAI 方法
98
+
99
+ - `chat(prompt, configs, callback)`: 聊天对话
100
+ - `responses(prompt, configs, callback)`: 结构化响应
101
+
102
+ ### 通用参数
103
+
104
+ - `prompt`: 字符串或消息数组 - 输入提示
105
+ - `configs`: 对象 - 模型参数配置
106
+ - `model`: 模型名称
107
+ - `stream`: 是否流式响应(默认: false)
108
+ - `system`: 系统提示(聊天模式)
109
+ - `options`: 其他模型参数
110
+ - `temperature`: 生成温度(0-1)
111
+ - `top_p`: 核采样概率
112
+ - `callback`: 函数 - 流式响应回调
113
+
114
+ ## 配置
115
+
116
+ ### 默认配置
117
+
118
+ 项目提供了默认配置,可以通过环境变量或参数覆盖:
119
+
120
+ **Ollama 默认配置:**
121
+
122
+ ```javascript
123
+ {
124
+ apiKey: process.env.OLLM_API_KEY || 'huxy@zys',
125
+ host: process.env.OLLM_API_HOST || 'http://192.168.0.111:11434',
126
+ params: {
127
+ model: 'qwen3-vl:latest',
128
+ keep_alive: -1,
129
+ },
130
+ options: {
131
+ temperature: 0.6,
132
+ num_ctx: 4096,
133
+ top_k: 20,
134
+ top_p: 0.9,
135
+ repeat_penalty: 1.15,
136
+ }
137
+ }
138
+ ```
139
+
140
+ **OpenAI 默认配置:**
141
+
142
+ ```javascript
143
+ {
144
+ apiKey: process.env.LLM_API_KEY || 'huxy@zys',
145
+ baseURL: process.env.LLM_API_BASEURL || 'http://192.168.0.111:11434/v1',
146
+ timeout: 3 * 60 * 60 * 1000,
147
+ maxRetries: 3,
148
+ params: {
149
+ model: 'qwen3-vl:latest',
150
+ temperature: 0.15,
151
+ max_tokens: 4096,
152
+ top_p: 0.9,
153
+ presence_penalty: 0.5,
154
+ frequency_penalty: 0.5,
155
+ },
156
+ options: {
157
+ top_k: 20,
158
+ repeat_penalty: 1.15,
159
+ thinking: true,
160
+ }
161
+ }
162
+ ```
163
+
164
+ ## 高级用法
165
+
166
+ ### 自定义 Fetch
167
+
168
+ 项目使用 Undici 实现高性能 HTTP 请求,并支持自定义超时:
169
+
170
+ ```javascript
171
+ import customFetch from 'huxy-llm-api/customFetch';
172
+
173
+ // 自定义请求
174
+ const response = await customFetch('https://api.example.com', {
175
+ method: 'POST',
176
+ headers: {
177
+ 'Content-Type': 'application/json',
178
+ },
179
+ body: JSON.stringify({prompt: 'Hello'}),
180
+ });
181
+ ```
182
+
183
+ ### 环境变量
184
+
185
+ 支持通过环境变量配置 API 密钥和地址:
186
+
187
+ ```bash
188
+ # Ollama
189
+ export OLLM_API_KEY="your-key"
190
+ export OLLM_API_HOST="http://localhost:11434"
191
+
192
+ # OpenAI
193
+ export LLM_API_KEY="your-key"
194
+ export LLM_API_BASEURL="https://api.openai.com/v1"
195
+ ```
196
+
197
+ ## 示例
198
+
199
+ 查看 [example.js](./example.js) 了解完整用法示例。
200
+
201
+ ## 贡献
202
+
203
+ 欢迎提交 Issue 和 Pull Request。
204
+
205
+ ## 许可证
206
+
207
+ MIT License © [ahyiru](https://github.com/ahyiru)
208
+
209
+ ## 联系
210
+
211
+ - GitHub: [https://github.com/ahyiru/huxy-llm-api](https://github.com/ahyiru/huxy-llm-api)
212
+ - Issues: [https://github.com/ahyiru/huxy-llm-api/issues](https://github.com/ahyiru/huxy-llm-api/issues)
package/example.js ADDED
@@ -0,0 +1,43 @@
1
+ import startApi from './index.js';
2
+
3
+ const ollamaApi = startApi('ollama', {
4
+ apiKey: '123',
5
+ host: 'http://192.168.0.111:11434',
6
+ // headers
7
+ // fetch
8
+ });
9
+
10
+ const openaiApi = startApi('openai', {
11
+ apiKey: '123',
12
+ baseURL: 'http://192.168.0.111:11434/v1',
13
+ // headers
14
+ // fetch
15
+ });
16
+
17
+ const demo = async () => {
18
+ const ollamaResult = await ollamaApi.generate('你好', {
19
+ model: 'devstral-small-2',
20
+ stream: false,
21
+ options: {
22
+ temperature: 0.15,
23
+ top_p: 0.9,
24
+ },
25
+ }, (mesg) => {
26
+ console.log(mesg);
27
+ });
28
+ console.log(ollamaResult);
29
+
30
+ const openaiResult = await openaiApi.chat('你是谁', {
31
+ model: 'qwen3-vl',
32
+ temperature: 0.15,
33
+ stream: true,
34
+ extra_body: {
35
+ top_k: 20,
36
+ },
37
+ }, (mesg, resp) => {
38
+ console.log(mesg, resp);
39
+ });
40
+ console.log(openaiResult);
41
+ };
42
+
43
+ demo();
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "huxy-llm-api",
3
+ "version": "1.0.0-beta.0",
4
+ "description": "一个简洁、易用的用于简化 Ollama 和 OpenAI API 调用的 Node.js 库。",
5
+ "type": "module",
6
+ "module": "./src/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./src/index.js"
10
+ },
11
+ "./*": {
12
+ "import": "./src/*.js"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "start": "node ./example.js"
17
+ },
18
+ "keywords": [
19
+ "nodejs",
20
+ "esm",
21
+ "ollama",
22
+ "openai",
23
+ "llm",
24
+ "api"
25
+ ],
26
+ "author": "ahyiru",
27
+ "license": "MIT",
28
+ "bugs": {
29
+ "url": "https://github.com/ahyiru/huxy-llm-api/issues"
30
+ },
31
+ "homepage": "https://github.com/ahyiru/huxy-llm-apir#readme",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/ahyiru/huxy-llm-api.git"
35
+ },
36
+ "dependencies": {
37
+ "ollama": "^0.6.3",
38
+ "openai": "^6.15.0",
39
+ "undici": "^7.16.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=20.0.0"
43
+ }
44
+ }
package/src/index.js ADDED
@@ -0,0 +1,164 @@
1
+ import {Ollama as T} from 'ollama';
2
+ import E from 'openai';
3
+ import {fetch as I, Agent as L} from 'undici';
4
+ var P = 300 * 60 * 1e3,
5
+ k = (t, a) => I(t, {...a, dispatcher: new L({headersTimeout: P})}),
6
+ x = k;
7
+ var v = {
8
+ config: {
9
+ apiKey: process.env.LLM_API_KEY || 'ah.yiru@gmail.com',
10
+ baseURL: process.env.LLM_API_BASEURL || 'http://192.168.0.111:11434/v1',
11
+ timeout: process.env.LLM_API_TIMEOUT || 108e5,
12
+ maxRetries: 3,
13
+ },
14
+ params: {model: 'qwen3-vl:latest', temperature: 0.15, max_tokens: 4096, top_p: 0.9, presence_penalty: 0.5, frequency_penalty: 0.5},
15
+ options: {top_k: 20, repeat_penalty: 1.15, thinking: !0},
16
+ },
17
+ h = v;
18
+ var C = {
19
+ config: {apiKey: process.env.OLLM_API_KEY || 'ah.yiru@gmail.com', host: process.env.OLLM_API_HOST || 'http://192.168.0.111:11434'},
20
+ params: {model: 'qwen3-vl:latest', keep_alive: -1},
21
+ options: {temperature: 0.6, num_ctx: 4096, top_k: 20, top_p: 0.9, repeat_penalty: 1.15},
22
+ },
23
+ g = C;
24
+ var _ = async (t, a, o) => {
25
+ if (a) {
26
+ let r = '',
27
+ e = '';
28
+ for await (let n of t) {
29
+ let {type: c, delta: i} = n;
30
+ (c === 'response.reasoning_text.delta' && (e += i), c === 'response.output_text.delta' && (r += i), o?.({content: r, reasoning: e}, n));
31
+ }
32
+ return {content: r, reasoning: e};
33
+ }
34
+ let [s = {}] = t.output ?? [];
35
+ return (o?.(t), {reasoning: s.content?.[0]?.text, content: t.output_text});
36
+ },
37
+ R = async (t, a, o) => {
38
+ if (a) {
39
+ let n = '',
40
+ c = '';
41
+ for await (let i of t) {
42
+ let {delta: p} = i.choices?.[0] ?? {},
43
+ {reasoning: u, content: f} = p ?? {};
44
+ (u && (c += u), f && (n += f), o?.({content: n, reasoning: c}, i));
45
+ }
46
+ return {content: n, reasoning: c};
47
+ }
48
+ let {message: s} = t.choices?.[0] ?? {},
49
+ {content: r, reasoning: e} = s;
50
+ return (o?.(t), {content: r, reasoning: e});
51
+ };
52
+ var d = async (t, a, o) => {
53
+ if (a) {
54
+ let r = '',
55
+ e = '';
56
+ for await (let n of t) {
57
+ let {type: c, delta: i} = n;
58
+ (c === 'response.reasoning_text.delta' && (e += i), c === 'response.output_text.delta' && (r += i), o?.({content: r, reasoning: e}, n));
59
+ }
60
+ return {content: r, reasoning: e};
61
+ }
62
+ let [s = {}] = t.output ?? [];
63
+ return (o?.(t), {reasoning: s.content?.[0]?.text, content: t.output_text});
64
+ },
65
+ A = async (t, a, o) => {
66
+ if (a) {
67
+ let e = '',
68
+ n = '';
69
+ for await (let c of t) {
70
+ let i = c.reasoning ?? c.thinking,
71
+ p = c.content ?? c.response;
72
+ (i && (n += i), p && (e += p), o?.({content: e, reasoning: n}, c));
73
+ }
74
+ return {content: e, reasoning: n};
75
+ }
76
+ let s = t.reasoning ?? t.thinking,
77
+ r = t.content ?? t.response;
78
+ return (o?.(t), {content: r, reasoning: s});
79
+ },
80
+ w = async (t, a, o) => {
81
+ if (a) {
82
+ let n = '',
83
+ c = '';
84
+ for await (let i of t) {
85
+ let {message: p} = i,
86
+ u = p.reasoning ?? p.thinking,
87
+ f = p.content ?? p.response;
88
+ (u && (c += u), f && (n += f), o?.({content: n, reasoning: c}, i));
89
+ }
90
+ return {content: n, reasoning: c};
91
+ }
92
+ let {message: s} = t,
93
+ r = s.reasoning ?? s.thinking,
94
+ e = s.content ?? s.response;
95
+ return (o?.(t), {content: e, reasoning: r});
96
+ };
97
+ var m = (t, a = {}, o = 'chat') => {
98
+ if (!t) throw Error('\u8BF7\u4F20\u5165\u4F60\u7684 prompt !');
99
+ if (o === 'chat') {
100
+ let n = Array.isArray(t) ? t : [{role: 'user', content: t}],
101
+ {system: c, ...i} = a;
102
+ return (c && (n = [{role: 'system', content: c}, ...n]), {messages: n, ...i});
103
+ }
104
+ let s = Array.isArray(t) ? t.slice(-1)[0]?.content : t,
105
+ {instructions: r, ...e} = a;
106
+ return (r || (e.instructions = e.system), {prompt: s, ...e});
107
+ },
108
+ l = ({options: t, extra_body: a, ...o}, s, r) => {
109
+ let e = {...s.params, ...o},
110
+ n = {...s.options, ...t};
111
+ return (r === 'openai' ? (e.extra_body = {...n, ...a}) : (e.options = n), e);
112
+ };
113
+ var y = {
114
+ openai: {
115
+ API: t => new E({...t, fetch: x}),
116
+ config: h,
117
+ llm: t => ({
118
+ chat: async (a, o = {}, s) => {
119
+ let r = R,
120
+ e = m(a, o, 'chat'),
121
+ n = await t.chat.completions.create(l(e, h, 'openai'));
122
+ return r(n, e.stream, s);
123
+ },
124
+ responses: async (a, o = {}, s) => {
125
+ let r = _,
126
+ e = m(a, o, 'responses'),
127
+ n = await t.responses.create(l(e, h, 'openai'));
128
+ return r(n, e.stream, s);
129
+ },
130
+ }),
131
+ },
132
+ ollama: {
133
+ API: t => new T({...t, fetch: x}),
134
+ config: g,
135
+ llm: t => ({
136
+ chat: async (a, o = {}, s) => {
137
+ let r = w,
138
+ e = m(a, o, 'chat'),
139
+ n = await t.chat(l(e, g, 'ollama'));
140
+ return r(n, e.stream, s);
141
+ },
142
+ generate: async (a, o = {}, s) => {
143
+ let r = A,
144
+ e = m(a, o, 'generate'),
145
+ n = await t.generate(l(e, g, 'ollama'));
146
+ return r(n, e.stream, s);
147
+ },
148
+ responses: async (a, o = {}, s) => {
149
+ let r = d,
150
+ e = m(a, o, 'responses'),
151
+ n = await t.responses(l(e, g, 'ollama'));
152
+ return r(n, e.stream, s);
153
+ },
154
+ }),
155
+ },
156
+ };
157
+ var K = (t = 'ollama', a) => {
158
+ let o = y[t] ?? y.ollama,
159
+ {API: s, config: r, llm: e} = o,
160
+ n = s({...r.config, ...a});
161
+ return e(n);
162
+ },
163
+ Q = K;
164
+ export {Q as default, K as startApi};