@agentic-kit/ollama 0.1.1 → 1.0.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/dist/index.js ADDED
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cross_fetch_1 = __importDefault(require("cross-fetch"));
7
+ // ─── Client ───────────────────────────────────────────────────────────────────
8
+ class OllamaClient {
9
+ baseUrl;
10
+ constructor(baseUrl = 'http://localhost:11434') {
11
+ this.baseUrl = baseUrl;
12
+ }
13
+ // ── Models ──────────────────────────────────────────────────────────────────
14
+ async listModels() {
15
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/tags`);
16
+ if (!res.ok) {
17
+ throw new Error(`listModels failed: ${res.status} ${res.statusText}`);
18
+ }
19
+ const data = await res.json();
20
+ if (data.models?.length)
21
+ return data.models.map((m) => m.name);
22
+ if (data.tags?.length)
23
+ return data.tags;
24
+ return [];
25
+ }
26
+ async pullModel(model) {
27
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/pull`, {
28
+ method: 'POST',
29
+ headers: { 'Content-Type': 'application/json' },
30
+ body: JSON.stringify({ name: model }),
31
+ });
32
+ if (!res.ok) {
33
+ throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
34
+ }
35
+ }
36
+ async deleteModel(model) {
37
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/delete`, {
38
+ method: 'DELETE',
39
+ headers: { 'Content-Type': 'application/json' },
40
+ body: JSON.stringify({ name: model }),
41
+ });
42
+ if (!res.ok) {
43
+ throw new Error(`deleteModel failed: ${res.status} ${res.statusText}`);
44
+ }
45
+ }
46
+ async generate(input, onChunk) {
47
+ if (input.messages) {
48
+ return this._chat(input, onChunk);
49
+ }
50
+ return this._generate(input, onChunk);
51
+ }
52
+ // ── Embeddings ──────────────────────────────────────────────────────────────
53
+ async generateEmbedding(text, model = 'nomic-embed-text') {
54
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/embeddings`, {
55
+ method: 'POST',
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: JSON.stringify({ model, prompt: text }),
58
+ });
59
+ if (!res.ok) {
60
+ throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
61
+ }
62
+ const data = await res.json();
63
+ return data.embedding;
64
+ }
65
+ // ── Private: /api/generate ──────────────────────────────────────────────────
66
+ async _generate(input, onChunk) {
67
+ const body = {
68
+ model: input.model,
69
+ prompt: input.prompt ?? '',
70
+ stream: !!onChunk,
71
+ };
72
+ if (input.system)
73
+ body.system = input.system;
74
+ if (input.temperature !== undefined)
75
+ body.temperature = input.temperature;
76
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/generate`, {
77
+ method: 'POST',
78
+ headers: { 'Content-Type': 'application/json' },
79
+ body: JSON.stringify(body),
80
+ });
81
+ if (!res.ok) {
82
+ const text = await res.text().catch(() => '');
83
+ throw new Error(`generate failed: ${res.status} ${res.statusText} — ${text}`);
84
+ }
85
+ if (onChunk) {
86
+ return this._streamResponse(res, (data) => data.response, onChunk);
87
+ }
88
+ const data = await res.json();
89
+ return data.response;
90
+ }
91
+ // ── Private: /api/chat ──────────────────────────────────────────────────────
92
+ async _chat(input, onChunk) {
93
+ const messages = [];
94
+ if (input.system) {
95
+ messages.push({ role: 'system', content: input.system });
96
+ }
97
+ messages.push(...(input.messages ?? []));
98
+ const body = {
99
+ model: input.model,
100
+ messages,
101
+ stream: !!onChunk,
102
+ };
103
+ if (input.temperature !== undefined)
104
+ body.temperature = input.temperature;
105
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/chat`, {
106
+ method: 'POST',
107
+ headers: { 'Content-Type': 'application/json' },
108
+ body: JSON.stringify(body),
109
+ });
110
+ if (!res.ok) {
111
+ const text = await res.text().catch(() => '');
112
+ throw new Error(`chat failed: ${res.status} ${res.statusText} — ${text}`);
113
+ }
114
+ if (onChunk) {
115
+ return this._streamResponse(res, (data) => data.message?.content ?? '', onChunk);
116
+ }
117
+ const data = await res.json();
118
+ return data.message?.content ?? '';
119
+ }
120
+ // ── Private: streaming reader ───────────────────────────────────────────────
121
+ async _streamResponse(res, extract, onChunk) {
122
+ const reader = res.body?.getReader();
123
+ if (!reader)
124
+ throw new Error('No response body reader');
125
+ const decoder = new TextDecoder();
126
+ while (true) {
127
+ const { done, value } = await reader.read();
128
+ if (done)
129
+ break;
130
+ const lines = decoder.decode(value).split('\n').filter(Boolean);
131
+ for (const line of lines) {
132
+ try {
133
+ const data = JSON.parse(line);
134
+ const chunk = extract(data);
135
+ if (chunk)
136
+ onChunk(chunk);
137
+ }
138
+ catch {
139
+ // partial line — skip
140
+ }
141
+ }
142
+ }
143
+ }
144
+ }
145
+ exports.default = OllamaClient;
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@agentic-kit/ollama",
3
+ "version": "0.1.2",
4
+ "author": "Dan Lynch <pyramation@gmail.com>",
5
+ "description": "Ollama",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/agentic-kit",
10
+ "license": "SEE LICENSE IN LICENSE",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/agentic-kit"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/agentic-kit/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "build": "makage build",
25
+ "build:dev": "makage build --dev",
26
+ "lint": "eslint . --fix",
27
+ "test": "jest",
28
+ "test:watch": "jest --watch"
29
+ },
30
+ "keywords": [],
31
+ "dependencies": {
32
+ "cross-fetch": "^4.1.0"
33
+ }
34
+ }
package/jest.config.js ADDED
@@ -0,0 +1,19 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ transform: {
6
+ '^.+\\.tsx?$': [
7
+ 'ts-jest',
8
+ {
9
+ babelConfig: false,
10
+ tsconfig: 'tsconfig.json',
11
+ },
12
+ ],
13
+ },
14
+ transformIgnorePatterns: [`/node_modules/*`],
15
+ testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
16
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
17
+ modulePathIgnorePatterns: ['dist/*'],
18
+ setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
19
+ };
package/jest.setup.js ADDED
@@ -0,0 +1,4 @@
1
+ global.TextEncoder = require('util').TextEncoder;
2
+ global.TextDecoder = require('util').TextDecoder;
3
+
4
+ jest.mock('cross-fetch', () => jest.fn());
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@agentic-kit/ollama",
3
- "version": "0.1.1",
3
+ "version": "1.0.0",
4
4
  "author": "Dan Lynch <pyramation@gmail.com>",
5
5
  "description": "Ollama",
6
6
  "main": "index.js",
7
7
  "module": "esm/index.js",
8
8
  "types": "index.d.ts",
9
- "homepage": "https://github.com/hyperweb-io/agentic-kit",
9
+ "homepage": "https://github.com/constructive-io/agentic-kit",
10
10
  "license": "SEE LICENSE IN LICENSE",
11
11
  "publishConfig": {
12
12
  "access": "public",
@@ -14,17 +14,15 @@
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "https://github.com/hyperweb-io/agentic-kit"
17
+ "url": "https://github.com/constructive-io/agentic-kit"
18
18
  },
19
19
  "bugs": {
20
- "url": "https://github.com/hyperweb-io/agentic-kit/issues"
20
+ "url": "https://github.com/constructive-io/agentic-kit/issues"
21
21
  },
22
22
  "scripts": {
23
- "copy": "copyfiles -f ../../LICENSE README.md package.json dist",
24
- "clean": "rimraf dist/**",
25
- "prepare": "npm run build",
26
- "build": "npm run clean; tsc; tsc -p tsconfig.esm.json; npm run copy",
27
- "build:dev": "npm run clean; tsc --declarationMap; tsc -p tsconfig.esm.json; npm run copy",
23
+ "clean": "makage clean",
24
+ "build": "makage build",
25
+ "build:dev": "makage build --dev",
28
26
  "lint": "eslint . --fix",
29
27
  "test": "jest",
30
28
  "test:watch": "jest --watch"
@@ -32,6 +30,5 @@
32
30
  "keywords": [],
33
31
  "dependencies": {
34
32
  "cross-fetch": "^4.1.0"
35
- },
36
- "gitHead": "0204aa87ae43833af29965684146ff22ebf77564"
33
+ }
37
34
  }
package/src/index.ts ADDED
@@ -0,0 +1,224 @@
1
+ import fetch from 'cross-fetch';
2
+
3
+ // ─── Types ────────────────────────────────────────────────────────────────────
4
+
5
+ export interface ChatMessage {
6
+ role: 'system' | 'user' | 'assistant';
7
+ content: string;
8
+ }
9
+
10
+ export interface GenerateInput {
11
+ model: string;
12
+ /** Single-shot prompt — routes to /api/generate */
13
+ prompt?: string;
14
+ /** Multi-turn messages — routes to /api/chat (takes precedence over prompt) */
15
+ messages?: ChatMessage[];
16
+ /** System prompt — injected into /api/generate or prepended to /api/chat messages */
17
+ system?: string;
18
+ stream?: boolean;
19
+ temperature?: number;
20
+ maxTokens?: number;
21
+ }
22
+
23
+ interface OllamaGenerateResponse {
24
+ model: string;
25
+ created_at: string;
26
+ response: string;
27
+ done: boolean;
28
+ }
29
+
30
+ interface OllamaChatResponse {
31
+ model: string;
32
+ created_at: string;
33
+ message: { role: string; content: string };
34
+ done: boolean;
35
+ }
36
+
37
+ interface OllamaEmbeddingResponse {
38
+ embedding: number[];
39
+ }
40
+
41
+ interface OllamaTagsResponse {
42
+ models?: Array<{
43
+ name: string;
44
+ model: string;
45
+ modified_at: string;
46
+ size: number;
47
+ digest: string;
48
+ }>;
49
+ tags?: string[];
50
+ }
51
+
52
+ // ─── Client ───────────────────────────────────────────────────────────────────
53
+
54
+ export default class OllamaClient {
55
+ private baseUrl: string;
56
+
57
+ constructor(baseUrl: string = 'http://localhost:11434') {
58
+ this.baseUrl = baseUrl;
59
+ }
60
+
61
+ // ── Models ──────────────────────────────────────────────────────────────────
62
+
63
+ async listModels(): Promise<string[]> {
64
+ const res = await fetch(`${this.baseUrl}/api/tags`);
65
+ if (!res.ok) {
66
+ throw new Error(`listModels failed: ${res.status} ${res.statusText}`);
67
+ }
68
+ const data: OllamaTagsResponse = await res.json();
69
+ if (data.models?.length) return data.models.map((m) => m.name);
70
+ if (data.tags?.length) return data.tags;
71
+ return [];
72
+ }
73
+
74
+ async pullModel(model: string): Promise<void> {
75
+ const res = await fetch(`${this.baseUrl}/api/pull`, {
76
+ method: 'POST',
77
+ headers: { 'Content-Type': 'application/json' },
78
+ body: JSON.stringify({ name: model }),
79
+ });
80
+ if (!res.ok) {
81
+ throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
82
+ }
83
+ }
84
+
85
+ async deleteModel(model: string): Promise<void> {
86
+ const res = await fetch(`${this.baseUrl}/api/delete`, {
87
+ method: 'DELETE',
88
+ headers: { 'Content-Type': 'application/json' },
89
+ body: JSON.stringify({ name: model }),
90
+ });
91
+ if (!res.ok) {
92
+ throw new Error(`deleteModel failed: ${res.status} ${res.statusText}`);
93
+ }
94
+ }
95
+
96
+ // ── Generate (single-shot or multi-turn) ────────────────────────────────────
97
+
98
+ async generate(input: GenerateInput): Promise<string>;
99
+ async generate(input: GenerateInput, onChunk: (chunk: string) => void): Promise<void>;
100
+ async generate(
101
+ input: GenerateInput,
102
+ onChunk?: (chunk: string) => void
103
+ ): Promise<string | void> {
104
+ if (input.messages) {
105
+ return this._chat(input, onChunk);
106
+ }
107
+ return this._generate(input, onChunk);
108
+ }
109
+
110
+ // ── Embeddings ──────────────────────────────────────────────────────────────
111
+
112
+ async generateEmbedding(text: string, model = 'nomic-embed-text'): Promise<number[]> {
113
+ const res = await fetch(`${this.baseUrl}/api/embeddings`, {
114
+ method: 'POST',
115
+ headers: { 'Content-Type': 'application/json' },
116
+ body: JSON.stringify({ model, prompt: text }),
117
+ });
118
+ if (!res.ok) {
119
+ throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
120
+ }
121
+ const data: OllamaEmbeddingResponse = await res.json();
122
+ return data.embedding;
123
+ }
124
+
125
+ // ── Private: /api/generate ──────────────────────────────────────────────────
126
+
127
+ private async _generate(
128
+ input: GenerateInput,
129
+ onChunk?: (chunk: string) => void
130
+ ): Promise<string | void> {
131
+ const body: Record<string, unknown> = {
132
+ model: input.model,
133
+ prompt: input.prompt ?? '',
134
+ stream: !!onChunk,
135
+ };
136
+ if (input.system) body.system = input.system;
137
+ if (input.temperature !== undefined) body.temperature = input.temperature;
138
+
139
+ const res = await fetch(`${this.baseUrl}/api/generate`, {
140
+ method: 'POST',
141
+ headers: { 'Content-Type': 'application/json' },
142
+ body: JSON.stringify(body),
143
+ });
144
+ if (!res.ok) {
145
+ const text = await res.text().catch(() => '');
146
+ throw new Error(`generate failed: ${res.status} ${res.statusText} — ${text}`);
147
+ }
148
+
149
+ if (onChunk) {
150
+ return this._streamResponse(res, (data: OllamaGenerateResponse) => data.response, onChunk);
151
+ }
152
+
153
+ const data: OllamaGenerateResponse = await res.json();
154
+ return data.response;
155
+ }
156
+
157
+ // ── Private: /api/chat ──────────────────────────────────────────────────────
158
+
159
+ private async _chat(
160
+ input: GenerateInput,
161
+ onChunk?: (chunk: string) => void
162
+ ): Promise<string | void> {
163
+ const messages: ChatMessage[] = [];
164
+ if (input.system) {
165
+ messages.push({ role: 'system', content: input.system });
166
+ }
167
+ messages.push(...(input.messages ?? []));
168
+
169
+ const body: Record<string, unknown> = {
170
+ model: input.model,
171
+ messages,
172
+ stream: !!onChunk,
173
+ };
174
+ if (input.temperature !== undefined) body.temperature = input.temperature;
175
+
176
+ const res = await fetch(`${this.baseUrl}/api/chat`, {
177
+ method: 'POST',
178
+ headers: { 'Content-Type': 'application/json' },
179
+ body: JSON.stringify(body),
180
+ });
181
+ if (!res.ok) {
182
+ const text = await res.text().catch(() => '');
183
+ throw new Error(`chat failed: ${res.status} ${res.statusText} — ${text}`);
184
+ }
185
+
186
+ if (onChunk) {
187
+ return this._streamResponse(
188
+ res,
189
+ (data: OllamaChatResponse) => data.message?.content ?? '',
190
+ onChunk
191
+ );
192
+ }
193
+
194
+ const data: OllamaChatResponse = await res.json();
195
+ return data.message?.content ?? '';
196
+ }
197
+
198
+ // ── Private: streaming reader ───────────────────────────────────────────────
199
+
200
+ private async _streamResponse<T>(
201
+ res: Response,
202
+ extract: (data: T) => string,
203
+ onChunk: (chunk: string) => void
204
+ ): Promise<void> {
205
+ const reader = res.body?.getReader();
206
+ if (!reader) throw new Error('No response body reader');
207
+
208
+ const decoder = new TextDecoder();
209
+ while (true) {
210
+ const { done, value } = await reader.read();
211
+ if (done) break;
212
+ const lines = decoder.decode(value).split('\n').filter(Boolean);
213
+ for (const line of lines) {
214
+ try {
215
+ const data: T = JSON.parse(line);
216
+ const chunk = extract(data);
217
+ if (chunk) onChunk(chunk);
218
+ } catch {
219
+ // partial line — skip
220
+ }
221
+ }
222
+ }
223
+ }
224
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist/esm",
5
+ "module": "es2022",
6
+ "rootDir": "src/",
7
+ "declaration": false
8
+ }
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src/"
6
+ },
7
+ "include": ["src/**/*.ts"],
8
+ "exclude": ["dist", "node_modules", "**/*.spec.*", "**/*.test.*"]
9
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Interweb, Inc. <developers@hyperweb.io>
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/esm/index.js DELETED
@@ -1,162 +0,0 @@
1
- import fetch from 'cross-fetch';
2
- export default class OllamaClient {
3
- baseUrl;
4
- constructor(baseUrl = 'http://localhost:11434') {
5
- this.baseUrl = baseUrl;
6
- }
7
- async listModels() {
8
- const response = await fetch(`${this.baseUrl}/api/tags`);
9
- if (!response.ok) {
10
- throw new Error(`Failed to list models: ${response.status} ${response.statusText}`);
11
- }
12
- const data = await response.json();
13
- return data.tags;
14
- }
15
- async generate(input, onChunk) {
16
- if (input.stream && onChunk) {
17
- return this.generateStreamingResponse(input.prompt, onChunk);
18
- }
19
- const response = await fetch(`${this.baseUrl}/api/generate`, {
20
- method: 'POST',
21
- headers: { 'Content-Type': 'application/json' },
22
- body: JSON.stringify({
23
- ...input,
24
- stream: input.stream || false
25
- }),
26
- });
27
- if (!response.ok) {
28
- let errorText;
29
- try {
30
- const errorData = await response.json();
31
- errorText = errorData.message ?? JSON.stringify(errorData);
32
- }
33
- catch {
34
- errorText = await response.text();
35
- }
36
- throw new Error(`Generate request failed: ${response.status} ${response.statusText} - ${errorText}`);
37
- }
38
- const data = await response.json();
39
- return data.text;
40
- }
41
- async pullModel(model) {
42
- const response = await fetch(`${this.baseUrl}/api/pull`, {
43
- method: 'POST',
44
- headers: { 'Content-Type': 'application/json' },
45
- body: JSON.stringify({ name: model }),
46
- });
47
- if (!response.ok) {
48
- let errorText;
49
- try {
50
- const errorData = await response.json();
51
- errorText = errorData.message ?? JSON.stringify(errorData);
52
- }
53
- catch {
54
- errorText = await response.text();
55
- }
56
- throw new Error(`Pull model failed: ${response.status} ${response.statusText} - ${errorText}`);
57
- }
58
- }
59
- async deleteModel(model) {
60
- const response = await fetch(`${this.baseUrl}/api/delete`, {
61
- method: 'DELETE',
62
- headers: { 'Content-Type': 'application/json' },
63
- body: JSON.stringify({ name: model }),
64
- });
65
- if (!response.ok) {
66
- let errorText;
67
- try {
68
- const errorData = await response.json();
69
- errorText = errorData.message ?? JSON.stringify(errorData);
70
- }
71
- catch {
72
- errorText = await response.text();
73
- }
74
- throw new Error(`Delete model failed: ${response.status} ${response.statusText} - ${errorText}`);
75
- }
76
- }
77
- async generateEmbedding(text) {
78
- const response = await fetch(`${this.baseUrl}/api/embeddings`, {
79
- method: 'POST',
80
- headers: {
81
- 'Content-Type': 'application/json',
82
- },
83
- body: JSON.stringify({
84
- model: 'mistral',
85
- prompt: text,
86
- }),
87
- });
88
- if (!response.ok) {
89
- throw new Error(`Failed to generate embedding: ${response.statusText}`);
90
- }
91
- const data = await response.json();
92
- return data.embedding;
93
- }
94
- async generateResponse(prompt, context) {
95
- const fullPrompt = context
96
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
97
- : prompt;
98
- const response = await fetch(`${this.baseUrl}/api/generate`, {
99
- method: 'POST',
100
- headers: {
101
- 'Content-Type': 'application/json',
102
- },
103
- body: JSON.stringify({
104
- model: 'mistral',
105
- prompt: fullPrompt,
106
- stream: false,
107
- }),
108
- });
109
- if (!response.ok) {
110
- throw new Error(`Failed to generate response: ${response.statusText}`);
111
- }
112
- const data = await response.json();
113
- return data.response;
114
- }
115
- async generateStreamingResponse(prompt, onChunk, context) {
116
- const fullPrompt = context
117
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
118
- : prompt;
119
- const response = await fetch(`${this.baseUrl}/api/generate`, {
120
- method: 'POST',
121
- headers: {
122
- 'Content-Type': 'application/json',
123
- },
124
- body: JSON.stringify({
125
- model: 'mistral',
126
- prompt: fullPrompt,
127
- stream: true,
128
- }),
129
- });
130
- if (!response.ok) {
131
- throw new Error(`Failed to generate streaming response: ${response.statusText}`);
132
- }
133
- const reader = response.body?.getReader();
134
- if (!reader) {
135
- throw new Error('Failed to get response reader');
136
- }
137
- const decoder = new TextDecoder();
138
- let done = false;
139
- while (!done) {
140
- const result = await reader.read();
141
- done = result.done;
142
- if (done)
143
- break;
144
- const value = result.value;
145
- if (value) {
146
- const chunk = decoder.decode(value);
147
- const lines = chunk.split('\n').filter(Boolean);
148
- for (const line of lines) {
149
- try {
150
- const data = JSON.parse(line);
151
- if (data.response) {
152
- onChunk(data.response);
153
- }
154
- }
155
- catch (error) {
156
- console.error('Error parsing chunk:', error);
157
- }
158
- }
159
- }
160
- }
161
- }
162
- }