@agentic-kit/ollama 0.1.2 β†’ 1.0.3

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 CHANGED
@@ -1,6 +1,7 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024 Interweb, Inc. <developers@hyperweb.io>
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
5
 
5
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,4 +1,16 @@
1
- # Ollama Client
1
+ # @agentic-kit/ollama
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/agentic-kit/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/@agentic-kit/ollama"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/agentic-kit?filename=packages%2Follama%2Fpackage.json"/></a>
13
+ </p>
2
14
 
3
15
  A JavaScript/TypeScript client for the Ollama LLM server, supporting model listing, text generation, streaming responses, embeddings, and model management.
4
16
 
@@ -6,10 +18,9 @@ A JavaScript/TypeScript client for the Ollama LLM server, supporting model listi
6
18
 
7
19
  ```bash
8
20
  npm install @agentic-kit/ollama
9
- # or
10
- yarn add @agentic-kit/ollama
11
21
  ```
12
22
 
23
+
13
24
  ## Usage
14
25
 
15
26
  ```typescript
@@ -75,42 +86,39 @@ interface GenerateInput {
75
86
 
76
87
  ## Contributing
77
88
 
78
- Please open issues or pull requests on [GitHub](https://github.com/hyperweb-io/agentic-kit).
79
-
80
- ## API Response Format
81
-
82
- The Ollama `/api/tags` endpoint returns the following JSON structure:
83
-
84
- ```json
85
- {
86
- "models": [
87
- {
88
- "name": "mistral:latest",
89
- "model": "mistral:latest",
90
- "modified_at": "2025-06-09T04:48:21.588888008Z",
91
- "size": 4113301824,
92
- "digest": "...",
93
- "details": {
94
- "parent_model": "",
95
- "format": "gguf",
96
- "family": "llama",
97
- "families": ["llama"],
98
- "parameter_size": "7.2B",
99
- "quantization_level": "Q4_0"
100
- }
101
- }
102
- ]
103
- }
104
- ```
89
+ Please open issues or pull requests on [GitHub](https://github.com/constructive-io/agentic-kit).
105
90
 
106
- The `listModels()` method extracts and returns just the model names:
91
+ ---
107
92
 
108
- ```ts
109
- const client = new OllamaClient('http://localhost:11434');
110
- const models = await client.listModels();
111
- console.log(models); // ["mistral:latest", "llama2:latest", ...]
112
- ```
93
+ ## Related Constructive Tooling
113
94
 
114
- ---
95
+ ### πŸ€– AI & Agent Development
96
+
97
+ * [agentic-kit](https://github.com/constructive-io/agentic-kit): **🧰 Provider-agnostic LLM adapter** with streaming and multi-turn support. Swap between Anthropic, OpenAI, Ollama, and any OpenAI-compatible endpoint.
98
+
99
+ ### πŸ“¦ Package Management
100
+
101
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **πŸ–₯️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
102
+
103
+ ### πŸ§ͺ Testing
104
+
105
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **πŸ“Š Isolated testing environments** with per-test transaction rollbacksβ€”ideal for integration tests, complex migrations, and RLS simulation.
106
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
107
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **πŸ§ͺ Supabase-native test harness** preconfigured for the local Supabase stackβ€”per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
108
+
109
+ ### 🧠 Parsing & AST
110
+
111
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **πŸ”„ SQL conversion engine** that interprets and converts PostgreSQL syntax.
112
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **πŸŒ‰ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
113
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **πŸ“ Type definitions** for PostgreSQL AST nodes in TypeScript.
114
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **πŸ› οΈ AST utilities** for constructing and transforming PostgreSQL syntax trees.
115
+
116
+ ## Credits
117
+
118
+ **πŸ›  Built by the [Constructive](https://constructive.io) team β€” creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
119
+
120
+ ## Disclaimer
121
+
122
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
115
123
 
116
- Β© Hyperweb (formerly Cosmology). See LICENSE for full licensing and disclaimer.
124
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js CHANGED
@@ -1,168 +1,137 @@
1
1
  import fetch from 'cross-fetch';
2
+ // ─── Client ───────────────────────────────────────────────────────────────────
2
3
  export default class OllamaClient {
3
4
  baseUrl;
4
5
  constructor(baseUrl = 'http://localhost:11434') {
5
6
  this.baseUrl = baseUrl;
6
7
  }
8
+ // ── Models ──────────────────────────────────────────────────────────────────
7
9
  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}`);
10
+ const res = await fetch(`${this.baseUrl}/api/tags`);
11
+ if (!res.ok) {
12
+ throw new Error(`listModels failed: ${res.status} ${res.statusText}`);
11
13
  }
12
- const data = await response.json();
13
- // Handle actual API response format (models array)
14
- if (data.models && Array.isArray(data.models)) {
15
- return data.models.map(model => model.name);
16
- }
17
- // Fallback to documented format (tags array) for backwards compatibility
18
- if (data.tags && Array.isArray(data.tags)) {
14
+ const data = await res.json();
15
+ if (data.models?.length)
16
+ return data.models.map((m) => m.name);
17
+ if (data.tags?.length)
19
18
  return data.tags;
20
- }
21
19
  return [];
22
20
  }
23
- async generate(input, onChunk) {
24
- if (input.stream && onChunk) {
25
- return this.generateStreamingResponse(input.prompt, onChunk);
26
- }
27
- const response = await fetch(`${this.baseUrl}/api/generate`, {
28
- method: 'POST',
29
- headers: { 'Content-Type': 'application/json' },
30
- body: JSON.stringify({
31
- ...input,
32
- stream: input.stream || false
33
- }),
34
- });
35
- if (!response.ok) {
36
- let errorText;
37
- try {
38
- const errorData = await response.json();
39
- errorText = errorData.message ?? JSON.stringify(errorData);
40
- }
41
- catch {
42
- errorText = await response.text();
43
- }
44
- throw new Error(`Generate request failed: ${response.status} ${response.statusText} - ${errorText}`);
45
- }
46
- const data = await response.json();
47
- return data.text;
48
- }
49
21
  async pullModel(model) {
50
- const response = await fetch(`${this.baseUrl}/api/pull`, {
22
+ const res = await fetch(`${this.baseUrl}/api/pull`, {
51
23
  method: 'POST',
52
24
  headers: { 'Content-Type': 'application/json' },
53
25
  body: JSON.stringify({ name: model }),
54
26
  });
55
- if (!response.ok) {
56
- let errorText;
57
- try {
58
- const errorData = await response.json();
59
- errorText = errorData.message ?? JSON.stringify(errorData);
60
- }
61
- catch {
62
- errorText = await response.text();
63
- }
64
- throw new Error(`Pull model failed: ${response.status} ${response.statusText} - ${errorText}`);
27
+ if (!res.ok) {
28
+ throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
65
29
  }
66
30
  }
67
31
  async deleteModel(model) {
68
- const response = await fetch(`${this.baseUrl}/api/delete`, {
32
+ const res = await fetch(`${this.baseUrl}/api/delete`, {
69
33
  method: 'DELETE',
70
34
  headers: { 'Content-Type': 'application/json' },
71
35
  body: JSON.stringify({ name: model }),
72
36
  });
73
- if (!response.ok) {
74
- let errorText;
75
- try {
76
- const errorData = await response.json();
77
- errorText = errorData.message ?? JSON.stringify(errorData);
78
- }
79
- catch {
80
- errorText = await response.text();
81
- }
82
- throw new Error(`Delete model failed: ${response.status} ${response.statusText} - ${errorText}`);
37
+ if (!res.ok) {
38
+ throw new Error(`deleteModel failed: ${res.status} ${res.statusText}`);
39
+ }
40
+ }
41
+ async generate(input, onChunk) {
42
+ if (input.messages) {
43
+ return this._chat(input, onChunk);
83
44
  }
45
+ return this._generate(input, onChunk);
84
46
  }
85
- async generateEmbedding(text) {
86
- const response = await fetch(`${this.baseUrl}/api/embeddings`, {
47
+ // ── Embeddings ──────────────────────────────────────────────────────────────
48
+ async generateEmbedding(text, model = 'nomic-embed-text') {
49
+ const res = await fetch(`${this.baseUrl}/api/embeddings`, {
87
50
  method: 'POST',
88
- headers: {
89
- 'Content-Type': 'application/json',
90
- },
91
- body: JSON.stringify({
92
- model: 'mistral',
93
- prompt: text,
94
- }),
51
+ headers: { 'Content-Type': 'application/json' },
52
+ body: JSON.stringify({ model, prompt: text }),
95
53
  });
96
- if (!response.ok) {
97
- throw new Error(`Failed to generate embedding: ${response.statusText}`);
54
+ if (!res.ok) {
55
+ throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
98
56
  }
99
- const data = await response.json();
57
+ const data = await res.json();
100
58
  return data.embedding;
101
59
  }
102
- async generateResponse(prompt, context) {
103
- const fullPrompt = context
104
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
105
- : prompt;
106
- const response = await fetch(`${this.baseUrl}/api/generate`, {
60
+ // ── Private: /api/generate ──────────────────────────────────────────────────
61
+ async _generate(input, onChunk) {
62
+ const body = {
63
+ model: input.model,
64
+ prompt: input.prompt ?? '',
65
+ stream: !!onChunk,
66
+ };
67
+ if (input.system)
68
+ body.system = input.system;
69
+ if (input.temperature !== undefined)
70
+ body.temperature = input.temperature;
71
+ const res = await fetch(`${this.baseUrl}/api/generate`, {
107
72
  method: 'POST',
108
- headers: {
109
- 'Content-Type': 'application/json',
110
- },
111
- body: JSON.stringify({
112
- model: 'mistral',
113
- prompt: fullPrompt,
114
- stream: false,
115
- }),
73
+ headers: { 'Content-Type': 'application/json' },
74
+ body: JSON.stringify(body),
116
75
  });
117
- if (!response.ok) {
118
- throw new Error(`Failed to generate response: ${response.statusText}`);
76
+ if (!res.ok) {
77
+ const text = await res.text().catch(() => '');
78
+ throw new Error(`generate failed: ${res.status} ${res.statusText} β€” ${text}`);
79
+ }
80
+ if (onChunk) {
81
+ return this._streamResponse(res, (data) => data.response, onChunk);
119
82
  }
120
- const data = await response.json();
83
+ const data = await res.json();
121
84
  return data.response;
122
85
  }
123
- async generateStreamingResponse(prompt, onChunk, context) {
124
- const fullPrompt = context
125
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
126
- : prompt;
127
- const response = await fetch(`${this.baseUrl}/api/generate`, {
86
+ // ── Private: /api/chat ──────────────────────────────────────────────────────
87
+ async _chat(input, onChunk) {
88
+ const messages = [];
89
+ if (input.system) {
90
+ messages.push({ role: 'system', content: input.system });
91
+ }
92
+ messages.push(...(input.messages ?? []));
93
+ const body = {
94
+ model: input.model,
95
+ messages,
96
+ stream: !!onChunk,
97
+ };
98
+ if (input.temperature !== undefined)
99
+ body.temperature = input.temperature;
100
+ const res = await fetch(`${this.baseUrl}/api/chat`, {
128
101
  method: 'POST',
129
- headers: {
130
- 'Content-Type': 'application/json',
131
- },
132
- body: JSON.stringify({
133
- model: 'mistral',
134
- prompt: fullPrompt,
135
- stream: true,
136
- }),
102
+ headers: { 'Content-Type': 'application/json' },
103
+ body: JSON.stringify(body),
137
104
  });
138
- if (!response.ok) {
139
- throw new Error(`Failed to generate streaming response: ${response.statusText}`);
105
+ if (!res.ok) {
106
+ const text = await res.text().catch(() => '');
107
+ throw new Error(`chat failed: ${res.status} ${res.statusText} β€” ${text}`);
140
108
  }
141
- const reader = response.body?.getReader();
142
- if (!reader) {
143
- throw new Error('Failed to get response reader');
109
+ if (onChunk) {
110
+ return this._streamResponse(res, (data) => data.message?.content ?? '', onChunk);
144
111
  }
112
+ const data = await res.json();
113
+ return data.message?.content ?? '';
114
+ }
115
+ // ── Private: streaming reader ───────────────────────────────────────────────
116
+ async _streamResponse(res, extract, onChunk) {
117
+ const reader = res.body?.getReader();
118
+ if (!reader)
119
+ throw new Error('No response body reader');
145
120
  const decoder = new TextDecoder();
146
- let done = false;
147
- while (!done) {
148
- const result = await reader.read();
149
- done = result.done;
121
+ while (true) {
122
+ const { done, value } = await reader.read();
150
123
  if (done)
151
124
  break;
152
- const value = result.value;
153
- if (value) {
154
- const chunk = decoder.decode(value);
155
- const lines = chunk.split('\n').filter(Boolean);
156
- for (const line of lines) {
157
- try {
158
- const data = JSON.parse(line);
159
- if (data.response) {
160
- onChunk(data.response);
161
- }
162
- }
163
- catch (error) {
164
- console.error('Error parsing chunk:', error);
165
- }
125
+ const lines = decoder.decode(value).split('\n').filter(Boolean);
126
+ for (const line of lines) {
127
+ try {
128
+ const data = JSON.parse(line);
129
+ const chunk = extract(data);
130
+ if (chunk)
131
+ onChunk(chunk);
132
+ }
133
+ catch {
134
+ // partial line β€” skip
166
135
  }
167
136
  }
168
137
  }
package/index.d.ts CHANGED
@@ -1,17 +1,29 @@
1
+ export interface ChatMessage {
2
+ role: 'system' | 'user' | 'assistant';
3
+ content: string;
4
+ }
1
5
  export interface GenerateInput {
2
6
  model: string;
3
- prompt: string;
7
+ /** Single-shot prompt β€” routes to /api/generate */
8
+ prompt?: string;
9
+ /** Multi-turn messages β€” routes to /api/chat (takes precedence over prompt) */
10
+ messages?: ChatMessage[];
11
+ /** System prompt β€” injected into /api/generate or prepended to /api/chat messages */
12
+ system?: string;
4
13
  stream?: boolean;
14
+ temperature?: number;
15
+ maxTokens?: number;
5
16
  }
6
17
  export default class OllamaClient {
7
18
  private baseUrl;
8
19
  constructor(baseUrl?: string);
9
20
  listModels(): Promise<string[]>;
10
- generate(input: GenerateInput): Promise<string>;
11
- generate(input: GenerateInput, onChunk: (chunk: string) => void): Promise<string | void>;
12
21
  pullModel(model: string): Promise<void>;
13
22
  deleteModel(model: string): Promise<void>;
14
- generateEmbedding(text: string): Promise<number[]>;
15
- generateResponse(prompt: string, context?: string): Promise<string>;
16
- generateStreamingResponse(prompt: string, onChunk: (chunk: string) => void, context?: string): Promise<void>;
23
+ generate(input: GenerateInput): Promise<string>;
24
+ generate(input: GenerateInput, onChunk: (chunk: string) => void): Promise<void>;
25
+ generateEmbedding(text: string, model?: string): Promise<number[]>;
26
+ private _generate;
27
+ private _chat;
28
+ private _streamResponse;
17
29
  }
package/index.js CHANGED
@@ -4,170 +4,139 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const cross_fetch_1 = __importDefault(require("cross-fetch"));
7
+ // ─── Client ───────────────────────────────────────────────────────────────────
7
8
  class OllamaClient {
8
9
  baseUrl;
9
10
  constructor(baseUrl = 'http://localhost:11434') {
10
11
  this.baseUrl = baseUrl;
11
12
  }
13
+ // ── Models ──────────────────────────────────────────────────────────────────
12
14
  async listModels() {
13
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/tags`);
14
- if (!response.ok) {
15
- throw new Error(`Failed to list models: ${response.status} ${response.statusText}`);
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}`);
16
18
  }
17
- const data = await response.json();
18
- // Handle actual API response format (models array)
19
- if (data.models && Array.isArray(data.models)) {
20
- return data.models.map(model => model.name);
21
- }
22
- // Fallback to documented format (tags array) for backwards compatibility
23
- if (data.tags && Array.isArray(data.tags)) {
19
+ const data = await res.json();
20
+ if (data.models?.length)
21
+ return data.models.map((m) => m.name);
22
+ if (data.tags?.length)
24
23
  return data.tags;
25
- }
26
24
  return [];
27
25
  }
28
- async generate(input, onChunk) {
29
- if (input.stream && onChunk) {
30
- return this.generateStreamingResponse(input.prompt, onChunk);
31
- }
32
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/generate`, {
33
- method: 'POST',
34
- headers: { 'Content-Type': 'application/json' },
35
- body: JSON.stringify({
36
- ...input,
37
- stream: input.stream || false
38
- }),
39
- });
40
- if (!response.ok) {
41
- let errorText;
42
- try {
43
- const errorData = await response.json();
44
- errorText = errorData.message ?? JSON.stringify(errorData);
45
- }
46
- catch {
47
- errorText = await response.text();
48
- }
49
- throw new Error(`Generate request failed: ${response.status} ${response.statusText} - ${errorText}`);
50
- }
51
- const data = await response.json();
52
- return data.text;
53
- }
54
26
  async pullModel(model) {
55
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/pull`, {
27
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/pull`, {
56
28
  method: 'POST',
57
29
  headers: { 'Content-Type': 'application/json' },
58
30
  body: JSON.stringify({ name: model }),
59
31
  });
60
- if (!response.ok) {
61
- let errorText;
62
- try {
63
- const errorData = await response.json();
64
- errorText = errorData.message ?? JSON.stringify(errorData);
65
- }
66
- catch {
67
- errorText = await response.text();
68
- }
69
- throw new Error(`Pull model failed: ${response.status} ${response.statusText} - ${errorText}`);
32
+ if (!res.ok) {
33
+ throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
70
34
  }
71
35
  }
72
36
  async deleteModel(model) {
73
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/delete`, {
37
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/delete`, {
74
38
  method: 'DELETE',
75
39
  headers: { 'Content-Type': 'application/json' },
76
40
  body: JSON.stringify({ name: model }),
77
41
  });
78
- if (!response.ok) {
79
- let errorText;
80
- try {
81
- const errorData = await response.json();
82
- errorText = errorData.message ?? JSON.stringify(errorData);
83
- }
84
- catch {
85
- errorText = await response.text();
86
- }
87
- throw new Error(`Delete model failed: ${response.status} ${response.statusText} - ${errorText}`);
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);
88
49
  }
50
+ return this._generate(input, onChunk);
89
51
  }
90
- async generateEmbedding(text) {
91
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/embeddings`, {
52
+ // ── Embeddings ──────────────────────────────────────────────────────────────
53
+ async generateEmbedding(text, model = 'nomic-embed-text') {
54
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/embeddings`, {
92
55
  method: 'POST',
93
- headers: {
94
- 'Content-Type': 'application/json',
95
- },
96
- body: JSON.stringify({
97
- model: 'mistral',
98
- prompt: text,
99
- }),
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: JSON.stringify({ model, prompt: text }),
100
58
  });
101
- if (!response.ok) {
102
- throw new Error(`Failed to generate embedding: ${response.statusText}`);
59
+ if (!res.ok) {
60
+ throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
103
61
  }
104
- const data = await response.json();
62
+ const data = await res.json();
105
63
  return data.embedding;
106
64
  }
107
- async generateResponse(prompt, context) {
108
- const fullPrompt = context
109
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
110
- : prompt;
111
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/generate`, {
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`, {
112
77
  method: 'POST',
113
- headers: {
114
- 'Content-Type': 'application/json',
115
- },
116
- body: JSON.stringify({
117
- model: 'mistral',
118
- prompt: fullPrompt,
119
- stream: false,
120
- }),
78
+ headers: { 'Content-Type': 'application/json' },
79
+ body: JSON.stringify(body),
121
80
  });
122
- if (!response.ok) {
123
- throw new Error(`Failed to generate response: ${response.statusText}`);
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);
124
87
  }
125
- const data = await response.json();
88
+ const data = await res.json();
126
89
  return data.response;
127
90
  }
128
- async generateStreamingResponse(prompt, onChunk, context) {
129
- const fullPrompt = context
130
- ? `Context: ${context}\n\nQuestion: ${prompt}\n\nAnswer:`
131
- : prompt;
132
- const response = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/generate`, {
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`, {
133
106
  method: 'POST',
134
- headers: {
135
- 'Content-Type': 'application/json',
136
- },
137
- body: JSON.stringify({
138
- model: 'mistral',
139
- prompt: fullPrompt,
140
- stream: true,
141
- }),
107
+ headers: { 'Content-Type': 'application/json' },
108
+ body: JSON.stringify(body),
142
109
  });
143
- if (!response.ok) {
144
- throw new Error(`Failed to generate streaming response: ${response.statusText}`);
110
+ if (!res.ok) {
111
+ const text = await res.text().catch(() => '');
112
+ throw new Error(`chat failed: ${res.status} ${res.statusText} β€” ${text}`);
145
113
  }
146
- const reader = response.body?.getReader();
147
- if (!reader) {
148
- throw new Error('Failed to get response reader');
114
+ if (onChunk) {
115
+ return this._streamResponse(res, (data) => data.message?.content ?? '', onChunk);
149
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');
150
125
  const decoder = new TextDecoder();
151
- let done = false;
152
- while (!done) {
153
- const result = await reader.read();
154
- done = result.done;
126
+ while (true) {
127
+ const { done, value } = await reader.read();
155
128
  if (done)
156
129
  break;
157
- const value = result.value;
158
- if (value) {
159
- const chunk = decoder.decode(value);
160
- const lines = chunk.split('\n').filter(Boolean);
161
- for (const line of lines) {
162
- try {
163
- const data = JSON.parse(line);
164
- if (data.response) {
165
- onChunk(data.response);
166
- }
167
- }
168
- catch (error) {
169
- console.error('Error parsing chunk:', error);
170
- }
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
171
140
  }
172
141
  }
173
142
  }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@agentic-kit/ollama",
3
- "version": "0.1.2",
3
+ "version": "1.0.3",
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,16 @@
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
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
28
27
  "lint": "eslint . --fix",
29
28
  "test": "jest",
30
29
  "test:watch": "jest --watch"
@@ -33,5 +32,5 @@
33
32
  "dependencies": {
34
33
  "cross-fetch": "^4.1.0"
35
34
  },
36
- "gitHead": "957a378bb3b08f3be63cce7b72d741f1f044ae95"
35
+ "gitHead": "cbd1f7833d4a107f6fcc897ac7d0df9041cabbdd"
37
36
  }