@agentic-kit/ollama 1.0.0 → 1.2.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 +22 -0
- package/README.md +83 -12
- package/esm/index.js +477 -0
- package/esm/package.json +1 -0
- package/index.d.ts +182 -0
- package/index.js +482 -0
- package/package.json +14 -4
- package/CHANGELOG.md +0 -28
- package/__tests__/first.test.ts +0 -188
- package/dist/README.md +0 -123
- package/dist/esm/index.js +0 -139
- package/dist/index.d.ts +0 -29
- package/dist/index.js +0 -145
- package/dist/package.json +0 -34
- package/jest.config.js +0 -19
- package/jest.setup.js +0 -4
- package/src/index.ts +0 -224
- package/tsconfig.esm.json +0 -9
- package/tsconfig.json +0 -9
package/CHANGELOG.md
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
# Change Log
|
|
2
|
-
|
|
3
|
-
All notable changes to this project will be documented in this file.
|
|
4
|
-
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
-
|
|
6
|
-
# [1.0.0](https://github.com/constructive-io/agentic-kit/compare/@agentic-kit/ollama@0.1.2...@agentic-kit/ollama@1.0.0) (2026-02-28)
|
|
7
|
-
|
|
8
|
-
### Features
|
|
9
|
-
|
|
10
|
-
- add @agentic-kit/anthropic and @agentic-kit/openai packages ([3281fd3](https://github.com/constructive-io/agentic-kit/commit/3281fd39949a2094ee89e0da5ba639b61ff7abc5))
|
|
11
|
-
|
|
12
|
-
## [0.1.2](https://github.com/hyperweb-io/agentic-kit/compare/@agentic-kit/ollama@0.1.1...@agentic-kit/ollama@0.1.2) (2025-06-09)
|
|
13
|
-
|
|
14
|
-
**Note:** Version bump only for package @agentic-kit/ollama
|
|
15
|
-
|
|
16
|
-
## [0.1.1](https://github.com/hyperweb-io/agentic-kit/compare/@agentic-kit/ollama@0.1.0...@agentic-kit/ollama@0.1.1) (2025-06-09)
|
|
17
|
-
|
|
18
|
-
**Note:** Version bump only for package @agentic-kit/ollama
|
|
19
|
-
|
|
20
|
-
# [0.1.0](https://github.com/hyperweb-io/agentic-kit/compare/@agentic-kit/ollama@0.0.2...@agentic-kit/ollama@0.1.0) (2025-06-09)
|
|
21
|
-
|
|
22
|
-
### Features
|
|
23
|
-
|
|
24
|
-
- add streaming support to generate method and implement adapter pattern ([f363a07](https://github.com/hyperweb-io/agentic-kit/commit/f363a071b790ef8f032ad8bb23209cafe3a3cdb1))
|
|
25
|
-
|
|
26
|
-
## 0.0.2 (2025-06-09)
|
|
27
|
-
|
|
28
|
-
**Note:** Version bump only for package @agentic-kit/ollama
|
package/__tests__/first.test.ts
DELETED
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
import fetch from 'cross-fetch';
|
|
2
|
-
import { TextEncoder } from 'util';
|
|
3
|
-
|
|
4
|
-
import OllamaClient, { GenerateInput } from '../src';
|
|
5
|
-
|
|
6
|
-
describe('OllamaClient', () => {
|
|
7
|
-
let client: OllamaClient;
|
|
8
|
-
|
|
9
|
-
beforeEach(() => {
|
|
10
|
-
client = new OllamaClient('http://localhost:11434');
|
|
11
|
-
jest.clearAllMocks();
|
|
12
|
-
});
|
|
13
|
-
|
|
14
|
-
afterEach(() => {
|
|
15
|
-
jest.resetAllMocks();
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
// ── listModels ──────────────────────────────────────────────────────────────
|
|
19
|
-
|
|
20
|
-
it('listModels returns names from models array', async () => {
|
|
21
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
22
|
-
ok: true,
|
|
23
|
-
json: async () => ({
|
|
24
|
-
models: [{ name: 'model1' }, { name: 'model2' }],
|
|
25
|
-
}),
|
|
26
|
-
});
|
|
27
|
-
const models = await client.listModels();
|
|
28
|
-
expect(models).toEqual(['model1', 'model2']);
|
|
29
|
-
expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/tags');
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it('listModels falls back to tags array', async () => {
|
|
33
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
34
|
-
ok: true,
|
|
35
|
-
json: async () => ({ tags: ['model1', 'model2'] }),
|
|
36
|
-
});
|
|
37
|
-
const models = await client.listModels();
|
|
38
|
-
expect(models).toEqual(['model1', 'model2']);
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
// ── generate (single-shot, /api/generate) ───────────────────────────────────
|
|
42
|
-
|
|
43
|
-
it('generate returns response text', async () => {
|
|
44
|
-
const input: GenerateInput = { model: 'llama3', prompt: 'hello' };
|
|
45
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
46
|
-
ok: true,
|
|
47
|
-
json: async () => ({ response: 'hi there', done: true }),
|
|
48
|
-
});
|
|
49
|
-
const text = await client.generate(input);
|
|
50
|
-
expect(text).toBe('hi there');
|
|
51
|
-
expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/generate', {
|
|
52
|
-
method: 'POST',
|
|
53
|
-
headers: { 'Content-Type': 'application/json' },
|
|
54
|
-
body: JSON.stringify({ model: 'llama3', prompt: 'hello', stream: false }),
|
|
55
|
-
});
|
|
56
|
-
});
|
|
57
|
-
|
|
58
|
-
it('generate passes system prompt to /api/generate', async () => {
|
|
59
|
-
const input: GenerateInput = { model: 'llama3', prompt: 'hello', system: 'Be concise.' };
|
|
60
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
61
|
-
ok: true,
|
|
62
|
-
json: async () => ({ response: 'ok', done: true }),
|
|
63
|
-
});
|
|
64
|
-
await client.generate(input);
|
|
65
|
-
const body = JSON.parse((fetch as jest.Mock).mock.calls[0][1].body);
|
|
66
|
-
expect(body.system).toBe('Be concise.');
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it('generate streams via /api/generate', async () => {
|
|
70
|
-
const chunkData = JSON.stringify({ response: 'chunk1', done: false }) + '\n';
|
|
71
|
-
const encoded = new TextEncoder().encode(chunkData);
|
|
72
|
-
const mockReader = {
|
|
73
|
-
read: jest.fn()
|
|
74
|
-
.mockResolvedValueOnce({ done: false, value: encoded })
|
|
75
|
-
.mockResolvedValueOnce({ done: true, value: undefined }),
|
|
76
|
-
};
|
|
77
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
78
|
-
ok: true,
|
|
79
|
-
body: { getReader: () => mockReader },
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
const chunks: string[] = [];
|
|
83
|
-
await client.generate({ model: 'llama3', prompt: 'hello', stream: true }, (c) => chunks.push(c));
|
|
84
|
-
expect(chunks).toEqual(['chunk1']);
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
// ── generate (multi-turn, /api/chat) ────────────────────────────────────────
|
|
88
|
-
|
|
89
|
-
it('generate routes to /api/chat when messages provided', async () => {
|
|
90
|
-
const input: GenerateInput = {
|
|
91
|
-
model: 'llama3',
|
|
92
|
-
messages: [{ role: 'user', content: 'hello' }],
|
|
93
|
-
};
|
|
94
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
95
|
-
ok: true,
|
|
96
|
-
json: async () => ({
|
|
97
|
-
message: { role: 'assistant', content: 'hi!' },
|
|
98
|
-
done: true,
|
|
99
|
-
}),
|
|
100
|
-
});
|
|
101
|
-
const text = await client.generate(input);
|
|
102
|
-
expect(text).toBe('hi!');
|
|
103
|
-
expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/chat', expect.any(Object));
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
it('generate prepends system message in /api/chat', async () => {
|
|
107
|
-
const input: GenerateInput = {
|
|
108
|
-
model: 'llama3',
|
|
109
|
-
messages: [{ role: 'user', content: 'hello' }],
|
|
110
|
-
system: 'You are helpful.',
|
|
111
|
-
};
|
|
112
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
113
|
-
ok: true,
|
|
114
|
-
json: async () => ({ message: { role: 'assistant', content: 'sure' }, done: true }),
|
|
115
|
-
});
|
|
116
|
-
await client.generate(input);
|
|
117
|
-
const body = JSON.parse((fetch as jest.Mock).mock.calls[0][1].body);
|
|
118
|
-
expect(body.messages[0]).toEqual({ role: 'system', content: 'You are helpful.' });
|
|
119
|
-
expect(body.messages[1]).toEqual({ role: 'user', content: 'hello' });
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
it('generate streams via /api/chat', async () => {
|
|
123
|
-
const chunkData = JSON.stringify({ message: { content: 'chunk1' }, done: false }) + '\n';
|
|
124
|
-
const encoded = new TextEncoder().encode(chunkData);
|
|
125
|
-
const mockReader = {
|
|
126
|
-
read: jest.fn()
|
|
127
|
-
.mockResolvedValueOnce({ done: false, value: encoded })
|
|
128
|
-
.mockResolvedValueOnce({ done: true, value: undefined }),
|
|
129
|
-
};
|
|
130
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
131
|
-
ok: true,
|
|
132
|
-
body: { getReader: () => mockReader },
|
|
133
|
-
});
|
|
134
|
-
|
|
135
|
-
const chunks: string[] = [];
|
|
136
|
-
await client.generate(
|
|
137
|
-
{ model: 'llama3', messages: [{ role: 'user', content: 'hi' }] },
|
|
138
|
-
(c) => chunks.push(c)
|
|
139
|
-
);
|
|
140
|
-
expect(chunks).toEqual(['chunk1']);
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
// ── pullModel / deleteModel ──────────────────────────────────────────────────
|
|
144
|
-
|
|
145
|
-
it('pullModel resolves', async () => {
|
|
146
|
-
(fetch as jest.Mock).mockResolvedValueOnce({ ok: true });
|
|
147
|
-
await expect(client.pullModel('llama3')).resolves.toBeUndefined();
|
|
148
|
-
expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/pull', {
|
|
149
|
-
method: 'POST',
|
|
150
|
-
headers: { 'Content-Type': 'application/json' },
|
|
151
|
-
body: JSON.stringify({ name: 'llama3' }),
|
|
152
|
-
});
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
it('deleteModel resolves', async () => {
|
|
156
|
-
(fetch as jest.Mock).mockResolvedValueOnce({ ok: true });
|
|
157
|
-
await expect(client.deleteModel('llama3')).resolves.toBeUndefined();
|
|
158
|
-
expect(fetch).toHaveBeenCalledWith('http://localhost:11434/api/delete', {
|
|
159
|
-
method: 'DELETE',
|
|
160
|
-
headers: { 'Content-Type': 'application/json' },
|
|
161
|
-
body: JSON.stringify({ name: 'llama3' }),
|
|
162
|
-
});
|
|
163
|
-
});
|
|
164
|
-
|
|
165
|
-
// ── generateEmbedding ───────────────────────────────────────────────────────
|
|
166
|
-
|
|
167
|
-
it('generateEmbedding returns embedding with default model', async () => {
|
|
168
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
169
|
-
ok: true,
|
|
170
|
-
json: async () => ({ embedding: [0.1, 0.2, 0.3] }),
|
|
171
|
-
});
|
|
172
|
-
const embedding = await client.generateEmbedding('test text');
|
|
173
|
-
expect(embedding).toEqual([0.1, 0.2, 0.3]);
|
|
174
|
-
const body = JSON.parse((fetch as jest.Mock).mock.calls[0][1].body);
|
|
175
|
-
expect(body.model).toBe('nomic-embed-text');
|
|
176
|
-
expect(body.prompt).toBe('test text');
|
|
177
|
-
});
|
|
178
|
-
|
|
179
|
-
it('generateEmbedding accepts custom model', async () => {
|
|
180
|
-
(fetch as jest.Mock).mockResolvedValueOnce({
|
|
181
|
-
ok: true,
|
|
182
|
-
json: async () => ({ embedding: [1, 2, 3] }),
|
|
183
|
-
});
|
|
184
|
-
await client.generateEmbedding('text', 'mxbai-embed-large');
|
|
185
|
-
const body = JSON.parse((fetch as jest.Mock).mock.calls[0][1].body);
|
|
186
|
-
expect(body.model).toBe('mxbai-embed-large');
|
|
187
|
-
});
|
|
188
|
-
});
|
package/dist/README.md
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
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>
|
|
14
|
-
|
|
15
|
-
A JavaScript/TypeScript client for the Ollama LLM server, supporting model listing, text generation, streaming responses, embeddings, and model management.
|
|
16
|
-
|
|
17
|
-
## Installation
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npm install @agentic-kit/ollama
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
## Usage
|
|
24
|
-
|
|
25
|
-
```typescript
|
|
26
|
-
import OllamaClient, { GenerateInput } from '@agentic-kit/ollama';
|
|
27
|
-
|
|
28
|
-
// Create a client (default port 11434)
|
|
29
|
-
const client = new OllamaClient('http://localhost:11434');
|
|
30
|
-
|
|
31
|
-
// List available models
|
|
32
|
-
const models = await client.listModels();
|
|
33
|
-
console.log('Available models:', models);
|
|
34
|
-
|
|
35
|
-
// Non-streaming text generation
|
|
36
|
-
const output = await client.generate({ model: 'mistral', prompt: 'Hello, Ollama!' });
|
|
37
|
-
console.log(output);
|
|
38
|
-
|
|
39
|
-
// Streaming generation
|
|
40
|
-
await client.generate(
|
|
41
|
-
{ model: 'mistral', prompt: 'Hello, streaming!', stream: true },
|
|
42
|
-
(chunk) => {
|
|
43
|
-
console.log('Received chunk:', chunk);
|
|
44
|
-
}
|
|
45
|
-
);
|
|
46
|
-
|
|
47
|
-
// Pull a model to local cache
|
|
48
|
-
await client.pullModel('mistral');
|
|
49
|
-
|
|
50
|
-
// Generate embeddings
|
|
51
|
-
const embedding = await client.generateEmbedding('Compute embeddings');
|
|
52
|
-
console.log('Embedding vector length:', embedding.length);
|
|
53
|
-
|
|
54
|
-
// Generate a conversational response with context
|
|
55
|
-
const response = await client.generateResponse(
|
|
56
|
-
'What is the capital of France?',
|
|
57
|
-
'Geography trivia'
|
|
58
|
-
);
|
|
59
|
-
console.log(response);
|
|
60
|
-
|
|
61
|
-
// Delete a pulled model when done
|
|
62
|
-
await client.deleteModel('mistral');
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
## API Reference
|
|
66
|
-
|
|
67
|
-
- `new OllamaClient(baseUrl?: string)` – defaults to `http://localhost:11434`
|
|
68
|
-
- `.listModels(): Promise<string[]>`
|
|
69
|
-
- `.generate(input: GenerateInput, onChunk?: (chunk: string) => void): Promise<string | void>`
|
|
70
|
-
- `.generateStreamingResponse(prompt: string, onChunk: (chunk: string) => void, context?: string): Promise<void>`
|
|
71
|
-
- `.generateEmbedding(text: string): Promise<number[]>`
|
|
72
|
-
- `.generateResponse(prompt: string, context?: string): Promise<string>`
|
|
73
|
-
- `.pullModel(model: string): Promise<void>`
|
|
74
|
-
- `.deleteModel(model: string): Promise<void>`
|
|
75
|
-
|
|
76
|
-
## GenerateInput type
|
|
77
|
-
|
|
78
|
-
```ts
|
|
79
|
-
interface GenerateInput {
|
|
80
|
-
model: string;
|
|
81
|
-
prompt: string;
|
|
82
|
-
stream?: boolean;
|
|
83
|
-
}
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
## Contributing
|
|
87
|
-
|
|
88
|
-
Please open issues or pull requests on [GitHub](https://github.com/constructive-io/agentic-kit).
|
|
89
|
-
|
|
90
|
-
---
|
|
91
|
-
|
|
92
|
-
## Related Constructive Tooling
|
|
93
|
-
|
|
94
|
-
### 🤖 AI & Agent Development
|
|
95
|
-
|
|
96
|
-
* [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.
|
|
97
|
-
|
|
98
|
-
### 📦 Package Management
|
|
99
|
-
|
|
100
|
-
* [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.
|
|
101
|
-
|
|
102
|
-
### 🧪 Testing
|
|
103
|
-
|
|
104
|
-
* [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.
|
|
105
|
-
* [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.
|
|
106
|
-
* [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.
|
|
107
|
-
|
|
108
|
-
### 🧠 Parsing & AST
|
|
109
|
-
|
|
110
|
-
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
111
|
-
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
112
|
-
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
113
|
-
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
114
|
-
|
|
115
|
-
## Credits
|
|
116
|
-
|
|
117
|
-
**🛠 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).**
|
|
118
|
-
|
|
119
|
-
## Disclaimer
|
|
120
|
-
|
|
121
|
-
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
122
|
-
|
|
123
|
-
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/dist/esm/index.js
DELETED
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
import fetch from 'cross-fetch';
|
|
2
|
-
// ─── Client ───────────────────────────────────────────────────────────────────
|
|
3
|
-
export default class OllamaClient {
|
|
4
|
-
baseUrl;
|
|
5
|
-
constructor(baseUrl = 'http://localhost:11434') {
|
|
6
|
-
this.baseUrl = baseUrl;
|
|
7
|
-
}
|
|
8
|
-
// ── Models ──────────────────────────────────────────────────────────────────
|
|
9
|
-
async listModels() {
|
|
10
|
-
const res = await fetch(`${this.baseUrl}/api/tags`);
|
|
11
|
-
if (!res.ok) {
|
|
12
|
-
throw new Error(`listModels failed: ${res.status} ${res.statusText}`);
|
|
13
|
-
}
|
|
14
|
-
const data = await res.json();
|
|
15
|
-
if (data.models?.length)
|
|
16
|
-
return data.models.map((m) => m.name);
|
|
17
|
-
if (data.tags?.length)
|
|
18
|
-
return data.tags;
|
|
19
|
-
return [];
|
|
20
|
-
}
|
|
21
|
-
async pullModel(model) {
|
|
22
|
-
const res = await fetch(`${this.baseUrl}/api/pull`, {
|
|
23
|
-
method: 'POST',
|
|
24
|
-
headers: { 'Content-Type': 'application/json' },
|
|
25
|
-
body: JSON.stringify({ name: model }),
|
|
26
|
-
});
|
|
27
|
-
if (!res.ok) {
|
|
28
|
-
throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
async deleteModel(model) {
|
|
32
|
-
const res = await fetch(`${this.baseUrl}/api/delete`, {
|
|
33
|
-
method: 'DELETE',
|
|
34
|
-
headers: { 'Content-Type': 'application/json' },
|
|
35
|
-
body: JSON.stringify({ name: model }),
|
|
36
|
-
});
|
|
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);
|
|
44
|
-
}
|
|
45
|
-
return this._generate(input, onChunk);
|
|
46
|
-
}
|
|
47
|
-
// ── Embeddings ──────────────────────────────────────────────────────────────
|
|
48
|
-
async generateEmbedding(text, model = 'nomic-embed-text') {
|
|
49
|
-
const res = await fetch(`${this.baseUrl}/api/embeddings`, {
|
|
50
|
-
method: 'POST',
|
|
51
|
-
headers: { 'Content-Type': 'application/json' },
|
|
52
|
-
body: JSON.stringify({ model, prompt: text }),
|
|
53
|
-
});
|
|
54
|
-
if (!res.ok) {
|
|
55
|
-
throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
|
|
56
|
-
}
|
|
57
|
-
const data = await res.json();
|
|
58
|
-
return data.embedding;
|
|
59
|
-
}
|
|
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`, {
|
|
72
|
-
method: 'POST',
|
|
73
|
-
headers: { 'Content-Type': 'application/json' },
|
|
74
|
-
body: JSON.stringify(body),
|
|
75
|
-
});
|
|
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);
|
|
82
|
-
}
|
|
83
|
-
const data = await res.json();
|
|
84
|
-
return data.response;
|
|
85
|
-
}
|
|
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`, {
|
|
101
|
-
method: 'POST',
|
|
102
|
-
headers: { 'Content-Type': 'application/json' },
|
|
103
|
-
body: JSON.stringify(body),
|
|
104
|
-
});
|
|
105
|
-
if (!res.ok) {
|
|
106
|
-
const text = await res.text().catch(() => '');
|
|
107
|
-
throw new Error(`chat failed: ${res.status} ${res.statusText} — ${text}`);
|
|
108
|
-
}
|
|
109
|
-
if (onChunk) {
|
|
110
|
-
return this._streamResponse(res, (data) => data.message?.content ?? '', onChunk);
|
|
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');
|
|
120
|
-
const decoder = new TextDecoder();
|
|
121
|
-
while (true) {
|
|
122
|
-
const { done, value } = await reader.read();
|
|
123
|
-
if (done)
|
|
124
|
-
break;
|
|
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
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
package/dist/index.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export interface ChatMessage {
|
|
2
|
-
role: 'system' | 'user' | 'assistant';
|
|
3
|
-
content: string;
|
|
4
|
-
}
|
|
5
|
-
export interface GenerateInput {
|
|
6
|
-
model: 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;
|
|
13
|
-
stream?: boolean;
|
|
14
|
-
temperature?: number;
|
|
15
|
-
maxTokens?: number;
|
|
16
|
-
}
|
|
17
|
-
export default class OllamaClient {
|
|
18
|
-
private baseUrl;
|
|
19
|
-
constructor(baseUrl?: string);
|
|
20
|
-
listModels(): Promise<string[]>;
|
|
21
|
-
pullModel(model: string): Promise<void>;
|
|
22
|
-
deleteModel(model: 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;
|
|
29
|
-
}
|
package/dist/index.js
DELETED
|
@@ -1,145 +0,0 @@
|
|
|
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;
|