@zero1llm/sdk 0.0.1 → 0.1.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Zero1LLM
3
+ Copyright (c) 2026 Zeronex Systems Private Limited
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,5 +1,144 @@
1
1
  # @zero1llm/sdk
2
2
 
3
- The official Zero1LLM SDK, coming soon, see https://www.zero1llm.ai
3
+ Use the models in [Zero1LLM](https://www.zero1llm.ai) from your own code: local models on your computer and the cloud
4
+ models you've set up in the app. Works with Node 20+, Bun and Deno. No dependencies.
4
5
 
5
- This 0.0.1 release is a placeholder that holds the name. It contains no code.
6
+ ```bash
7
+ npm install @zero1llm/sdk # or: pnpm add / yarn add / bun add
8
+ ```
9
+
10
+ ## Before you start
11
+
12
+ 1. Open Zero1LLM → **Settings → Local API** and turn on **Local API server**.
13
+ 2. Choose **Show key** and set it as `ZERO1LLM_API_KEY` (or pass `{ apiKey }`).
14
+
15
+ The SDK finds the running app by itself. To point it elsewhere, set `ZERO1LLM_BASE_URL` or pass `{ baseURL }`.
16
+
17
+ ## Chat
18
+
19
+ ```ts
20
+ import { Zero1LLM } from '@zero1llm/sdk';
21
+
22
+ const z = new Zero1LLM();
23
+
24
+ const reply = await z.chat.respond({ model: 'local/gemma-4-e2b-it-q4', messages: 'What is the meaning of life?' });
25
+ console.log(reply.content);
26
+ ```
27
+
28
+ `messages` is a question, or a conversation in OpenAI's format (`[{ role: 'user', content: '…' }]`). Options:
29
+ `temperature`, `maxTokens`, `think` (let a model that can think do so first), `tools`, `schema`, `signal`.
30
+
31
+ ## Streaming
32
+
33
+ ```ts
34
+ for await (const part of z.chat.stream({ model: 'local/gemma-4-e2b-it-q4', messages: 'Tell me a story.' })) {
35
+ process.stdout.write(part.text);
36
+ }
37
+ ```
38
+
39
+ Each part has `text` (the answer) and `reasoning` (the thinking, when `think` is on).
40
+
41
+ ## JSON in a shape you choose
42
+
43
+ ```ts
44
+ const invoice = await z.chat.respond({
45
+ model: 'local/gemma-4-e2b-it-q4',
46
+ messages: 'Invoice: 3 items at 12.50 EUR each. What is the total?',
47
+ schema: { type: 'object', properties: { total: { type: 'number' }, currency: { type: 'string' } }, required: ['total', 'currency'] },
48
+ });
49
+ console.log(invoice.parsed); // { total: 37.5, currency: 'EUR' }
50
+ ```
51
+
52
+ Local and cloud models (not Bedrock models yet).
53
+
54
+ ## Tools
55
+
56
+ ```ts
57
+ const reply = await z.chat.respond({
58
+ model: 'local/gemma-4-e2b-it-q4',
59
+ messages: 'What is the weather in Paris?',
60
+ tools: [{ type: 'function', function: { name: 'get_weather', parameters: { type: 'object', properties: { city: { type: 'string' } } } } }],
61
+ });
62
+ for (const call of reply.toolCalls) console.log(call.function.name, JSON.parse(call.function.arguments));
63
+ ```
64
+
65
+ ## Models
66
+
67
+ ```ts
68
+ await z.models.list(); // every model: local/… and cloud/…
69
+ await z.models.local(); // models on this computer: size, state, how well each runs here
70
+ await z.models.load('qwen3.5-9b'); // load one (waits until ready)
71
+ await z.models.eject('qwen3.5-9b'); // free its memory
72
+
73
+ // Loading a big model takes a while: hear how far it is.
74
+ await z.models.load('qwen3.5-9b', { onProgress: p => console.log(p.stage, p.percent ?? '') });
75
+ ```
76
+
77
+ ## Your own functions as tools
78
+
79
+ `chat.act` runs the model, calls your functions when it asks, gives it the results, and repeats until it answers:
80
+
81
+ ```ts
82
+ const reply = await z.chat.act({
83
+ model: 'local/gemma-4-e2b-it-q4',
84
+ messages: 'What is the weather in Paris?',
85
+ tools: [{ name: 'get_weather', description: 'Weather for a city', parameters: { type: 'object', properties: { city: { type: 'string' } } }, run: ({ city }) => ({ temp: 18, sky: 'sunny', city }) }],
86
+ });
87
+ console.log(reply.content); // It is sunny and 18°C in Paris.
88
+ ```
89
+
90
+ Your function may be async. If it throws, the model is told the error. `maxRounds` (default 10) caps the rounds.
91
+
92
+ ## Pictures and videos
93
+
94
+ ```ts
95
+ import { writeFileSync } from 'node:fs';
96
+
97
+ const pic = await z.images.create({ prompt: 'A red fox in snow', shape: '16:9' });
98
+ writeFileSync('fox.png', pic.bytes);
99
+
100
+ const clip = await z.videos.create({ prompt: 'Waves at sunset', seconds: 3 });
101
+ writeFileSync('waves.webm', clip.bytes);
102
+ ```
103
+
104
+ Pictures are made where the app makes them (this computer, or Zero1LLM Cloud when chosen in Settings); videos on
105
+ this computer. Nothing is kept in the app.
106
+
107
+ ## The app's own chat
108
+
109
+ Chat as if you typed in Zero1LLM: web search, thinking, memory, your connectors' tools (you decide Allow / Deny) and
110
+ pictures. The chat is saved in the app's sidebar.
111
+
112
+ ```ts
113
+ const chat = z.assistant.send({ text: 'What is the latest Node release?', web: true });
114
+ for await (const ev of chat) {
115
+ if (ev.type === 'answer' && ev.entry.status === 'asking') await chat.decide(true); // a tool asks to run
116
+ if (ev.type === 'answer' && ev.entry.status === 'done') console.log(ev.entry.text);
117
+ if (ev.type === 'picture') console.log('picture:', ev.url.slice(0, 40));
118
+ }
119
+ // Continue the same chat: z.assistant.send({ chatId: chat.chatId, text: 'And the one before?' })
120
+ ```
121
+
122
+ Each `answer` event is the answer so far. `model` picks the model (default: the chat's, else the app's).
123
+ Also: `z.assistant.chats()`, `open(chatId)`, `delete(chatId)`, and `chat.answer([...])` when the AI asks questions.
124
+ `save: false` keeps a chat out of the sidebar (in the app's memory only, until it closes).
125
+
126
+ ## Errors
127
+
128
+ Failures throw `Zero1LLMError` with a `code`: `NOT_RUNNING` (the app is closed or its local API is off),
129
+ `UNAUTHORIZED`, `MODEL_NOT_FOUND`, `NOT_LOADED`, `NO_ROOM`, `ONE_AT_A_TIME`, `BAD_REQUEST`, `NOT_SUPPORTED`.
130
+
131
+ ```ts
132
+ import { Zero1LLMError } from '@zero1llm/sdk';
133
+
134
+ try {
135
+ await z.chat.respond({ model: 'local/big-model', messages: 'Hi' });
136
+ } catch (e) {
137
+ if (e instanceof Zero1LLMError && e.code === 'NO_ROOM') console.log('Not enough memory right now.');
138
+ }
139
+ ```
140
+
141
+ ## Already using OpenAI's or Anthropic's SDK?
142
+
143
+ They work too: point them at `http://127.0.0.1:47820/v1` (OpenAI) or `http://127.0.0.1:47820` (Anthropic) with your
144
+ key. See the [Local API guide](https://www.zero1llm.ai/docs/local-api).
@@ -0,0 +1,299 @@
1
+ /** As `APP_NAME` and the app identifier in Zero1LLM's brand (a test checks they match; a rename edits both). */
2
+ export declare const APP_NAME = "Zero1LLM";
3
+ /** The local API version this SDK speaks. */
4
+ export declare const API_VERSION = 1;
5
+ export interface ClientOptions {
6
+ /** The key from Settings → Local API; default `ZERO1LLM_API_KEY`. */
7
+ apiKey?: string;
8
+ /** Default `ZERO1LLM_BASE_URL`, else the running app's address, else http://127.0.0.1:47820. */
9
+ baseURL?: string;
10
+ }
11
+ /** A message in OpenAI's format. `content` may be parts, e.g. a picture as `{ type: 'image_url', image_url: { url: 'data:…' } }`. */
12
+ export interface Message {
13
+ role: 'system' | 'user' | 'assistant' | 'tool';
14
+ content: string | null | Array<Record<string, unknown>>;
15
+ tool_calls?: ToolCall[];
16
+ tool_call_id?: string;
17
+ }
18
+ /** A function the model may call (OpenAI's format). */
19
+ export interface Tool {
20
+ type: 'function';
21
+ function: {
22
+ name: string;
23
+ description?: string;
24
+ parameters?: Record<string, unknown>;
25
+ };
26
+ }
27
+ export interface ToolCall {
28
+ id: string;
29
+ type: 'function';
30
+ function: {
31
+ name: string;
32
+ arguments: string;
33
+ };
34
+ }
35
+ export interface ChatOptions {
36
+ /** `local/<model>` or `cloud/<connection>/<model>`: see `models.list()`. */
37
+ model: string;
38
+ /** The conversation, or just the question. */
39
+ messages: Message[] | string;
40
+ temperature?: number;
41
+ maxTokens?: number;
42
+ /** Let a model that can think do so first (off by default; it then needs more `maxTokens`). */
43
+ think?: boolean;
44
+ /** A JSON Schema the answer must follow; the reply's `parsed` holds the object. Not Bedrock models yet. */
45
+ schema?: Record<string, unknown>;
46
+ tools?: Tool[];
47
+ signal?: AbortSignal;
48
+ }
49
+ /** One of your functions the model may call; `chat.act` runs it and gives the model what it returns. */
50
+ export interface FunctionTool {
51
+ name: string;
52
+ description?: string;
53
+ /** A JSON Schema of the arguments. */
54
+ parameters?: Record<string, unknown>;
55
+ run: (args: any) => unknown;
56
+ }
57
+ export interface ActOptions extends Omit<ChatOptions, 'tools' | 'schema'> {
58
+ tools: FunctionTool[];
59
+ /** Model answers at most (default 10): each may call tools; then `TOO_MANY_ROUNDS`. */
60
+ maxRounds?: number;
61
+ /** Told of each call and what it returned, as it happens. */
62
+ onToolCall?: (call: {
63
+ name: string;
64
+ args: unknown;
65
+ result: unknown;
66
+ }) => void;
67
+ }
68
+ /** Loading progress: the engine set up (first time only), then the model read (`percent` when known). */
69
+ export interface LoadProgress {
70
+ stage: 'engine' | 'loading';
71
+ percent?: number;
72
+ }
73
+ export interface Usage {
74
+ promptTokens: number;
75
+ completionTokens: number;
76
+ }
77
+ export interface Reply {
78
+ content: string;
79
+ /** What the model thought first, when it did. */
80
+ reasoning?: string;
81
+ toolCalls: ToolCall[];
82
+ finishReason: string | null;
83
+ usage?: Usage;
84
+ /** With `schema`: the answer as an object. */
85
+ parsed?: unknown;
86
+ }
87
+ /** One piece of a streamed answer: words of the answer (`text`) or of the thinking (`reasoning`). */
88
+ export interface Part {
89
+ text: string;
90
+ reasoning: string;
91
+ }
92
+ export interface Model {
93
+ id: string;
94
+ name: string;
95
+ /** Who serves it: Zero1LLM for local models, the connection's name for cloud ones. */
96
+ ownedBy: string;
97
+ local: boolean;
98
+ /** Local models: running now. */
99
+ loaded?: boolean;
100
+ }
101
+ export interface LocalModel {
102
+ id: string;
103
+ name: string;
104
+ sizeGB: number;
105
+ state: 'loaded' | 'loading' | 'not-loaded' | 'error';
106
+ contextSize?: number;
107
+ vision?: boolean;
108
+ /** How well it runs on this computer, as the app rates it. */
109
+ fit: string | null;
110
+ }
111
+ /** The app's answer so far, as its chat shows it. */
112
+ export interface AssistantEntry {
113
+ /** `asking`: a tool waits for Allow / Deny (`ask` says what); `question`: the AI asks `questions`. */
114
+ status: 'preparing' | 'asking' | 'question' | 'waiting' | 'streaming' | 'done' | 'stopped' | 'error';
115
+ text: string;
116
+ thinking?: string;
117
+ error?: string;
118
+ ask?: string;
119
+ questions?: Array<{
120
+ question: string;
121
+ header?: string;
122
+ options: Array<{
123
+ label: string;
124
+ description?: string;
125
+ }>;
126
+ multiSelect?: boolean;
127
+ }>;
128
+ sources?: Array<{
129
+ n: number;
130
+ title: string;
131
+ url: string;
132
+ }>;
133
+ /** Ids of the pictures, videos and the names of documents made (each also comes once as its own event). */
134
+ pictures?: string[];
135
+ videos?: string[];
136
+ files?: string[];
137
+ model?: string;
138
+ [key: string]: unknown;
139
+ }
140
+ /** One event of an answer from the app's chat. */
141
+ export type AssistantEvent = {
142
+ type: 'answer';
143
+ entry: AssistantEntry;
144
+ } | {
145
+ type: 'picture' | 'video' | 'file';
146
+ id: string;
147
+ url: string;
148
+ name?: string;
149
+ } | {
150
+ type: 'progress';
151
+ text: string;
152
+ }
153
+ /** Which model answers, and the models on this computer (first and last). */
154
+ | {
155
+ type: 'status';
156
+ status: Record<string, unknown>;
157
+ };
158
+ export interface AssistantOptions {
159
+ text: string;
160
+ /** Continue this chat; a new one when left out (the chat's id is `chatId` on what `send` returns). */
161
+ chatId?: string;
162
+ /** A model from `models.list()`; default the chat's model, else the one the app chose last. */
163
+ model?: string;
164
+ /** Search the web first. */
165
+ web?: boolean;
166
+ think?: boolean;
167
+ /** `false`: kept in the app's memory only, not in its sidebar (gone when the app closes). Default saved. */
168
+ save?: boolean;
169
+ /** Files, read as if attached in the app (up to 10, 10 MB in all). */
170
+ attachments?: Array<{
171
+ name: string;
172
+ data: Uint8Array;
173
+ }>;
174
+ signal?: AbortSignal;
175
+ }
176
+ /** An answer being written: its events, and the chat's Allow / Deny and answers to the AI's questions. */
177
+ export interface AssistantChat extends AsyncIterable<AssistantEvent> {
178
+ chatId: string;
179
+ /** Allow (`true`), deny (`false`) or always allow the tool waiting in this chat. */
180
+ decide(answer: boolean | 'always'): Promise<void>;
181
+ /** Answers the AI's questions: the chosen options for each, in order; none skips them. */
182
+ answer(answers?: Array<{
183
+ chosen: string[];
184
+ }>): Promise<void>;
185
+ }
186
+ /** A picture or video the app made: `url` is a data URL, `bytes` the file (PNG or WebM) to save. */
187
+ export interface Made {
188
+ url: string;
189
+ bytes: Uint8Array;
190
+ width: number;
191
+ height: number;
192
+ seed: number;
193
+ model: string;
194
+ /** Videos: frames and frames per second. */
195
+ frames?: number;
196
+ fps?: number;
197
+ }
198
+ export interface SavedChat {
199
+ id: string;
200
+ title: string;
201
+ updatedAt: number;
202
+ }
203
+ /**
204
+ * Why a request failed. `code`: `NOT_RUNNING` (the app is closed or its local API is off), `UNAUTHORIZED`,
205
+ * `MODEL_NOT_FOUND`, `NOT_LOADED`, `NO_ROOM`, `ONE_AT_A_TIME`, `BAD_REQUEST`, `NOT_SUPPORTED`, or another the app sends.
206
+ */
207
+ export declare class Zero1LLMError extends Error {
208
+ readonly code: string;
209
+ readonly status?: number | undefined;
210
+ constructor(message: string, code: string, status?: number | undefined);
211
+ }
212
+ /** The running app's address, from the file it writes while its local API runs; undefined when none runs. */
213
+ export declare function discover(files?: string[]): string | undefined;
214
+ export declare class Zero1LLM {
215
+ readonly baseURL: string;
216
+ private readonly apiKey;
217
+ readonly models: {
218
+ /** Every model you can use: local ones and the cloud ones the app offers. */
219
+ list: () => Promise<Model[]>;
220
+ /** The models on this computer, with size, state and how well each runs here. */
221
+ local: () => Promise<LocalModel[]>;
222
+ /** Loads a model on this computer (waits until it's ready); `onProgress` hears how far it is. */
223
+ load: (model: string, options?: {
224
+ onProgress?: (p: LoadProgress) => void;
225
+ signal?: AbortSignal;
226
+ }) => Promise<LocalModel>;
227
+ /** Stops a running model, freeing its memory. */
228
+ eject: (model: string) => Promise<LocalModel>;
229
+ };
230
+ readonly chat: {
231
+ /** The whole answer at once. */
232
+ respond: (options: ChatOptions) => Promise<Reply>;
233
+ /** The answer as it is written, piece by piece. */
234
+ stream: (options: ChatOptions) => AsyncIterable<Part>;
235
+ /**
236
+ * Lets the model use your functions: each call it makes is run here and the result given back, until it answers
237
+ * without calling one. The reply's `messages` is the whole conversation, to continue it.
238
+ */
239
+ act: (options: ActOptions) => Promise<Reply & {
240
+ messages: Message[];
241
+ }>;
242
+ };
243
+ /**
244
+ * The app's own chat (D230), as if typed in the app: web search, thinking, memory, the user's connectors' tools with
245
+ * Allow / Deny, pictures. Chats are saved in the app's sidebar.
246
+ */
247
+ readonly assistant: {
248
+ send: (options: AssistantOptions) => AssistantChat;
249
+ decide: (chatId: string, answer: boolean | 'always') => Promise<void>;
250
+ answer: (chatId: string, answers?: Array<{
251
+ chosen: string[];
252
+ }>) => Promise<void>;
253
+ /** The chats saved in the app, newest first. */
254
+ chats: () => Promise<SavedChat[]>;
255
+ /** A saved chat's messages: `{ role: 'user', text }` and `{ role: 'assistant', entry }`. */
256
+ open: (chatId: string) => Promise<Array<{
257
+ role: 'user';
258
+ text: string;
259
+ attachments?: string[];
260
+ } | {
261
+ role: 'assistant';
262
+ entry: AssistantEntry;
263
+ }>>;
264
+ delete: (chatId: string) => Promise<void>;
265
+ };
266
+ /** Pictures, made where and as large as the app's chat would make them (this computer or the cloud). */
267
+ readonly images: {
268
+ /** `shape`: '1:1', '16:9', '9:16', '4:3', '3:4' or '4:5'; default the one set in the app. */
269
+ create: (options: {
270
+ prompt: string;
271
+ shape?: string;
272
+ signal?: AbortSignal;
273
+ }) => Promise<Made>;
274
+ };
275
+ /** Short videos, made on this computer. */
276
+ readonly videos: {
277
+ create: (options: {
278
+ prompt: string;
279
+ seconds?: number;
280
+ shape?: 'landscape' | 'portrait';
281
+ signal?: AbortSignal;
282
+ }) => Promise<Made>;
283
+ };
284
+ constructor(options?: ClientOptions);
285
+ private request;
286
+ private json;
287
+ private events;
288
+ /** The app chat's JSON lines as events; an error line throws. */
289
+ private assistantEvents;
290
+ /** A JSON-lines answer, line by line; a whole JSON answer (a call with no lines) as its one line. */
291
+ private lines;
292
+ /**
293
+ * A long job (a load, a picture, a video) as JSON lines, which the app keeps alive while it works, so no client
294
+ * timeout cuts it off: progress lines go to `onProgress`, an error line throws, the first other line is the result.
295
+ */
296
+ private job;
297
+ /** Field `key` of the first line that has it. */
298
+ private assistantLine;
299
+ }
package/dist/index.js ADDED
@@ -0,0 +1,362 @@
1
+ // @zero1llm/sdk — use the models in Zero1LLM from Node, Bun or Deno (docs/SDK_PLAN.md §4). A thin client of the app's
2
+ // local API (Settings → Local API): no AI runs here, only HTTP, streaming, types and errors. Finds the app by itself
3
+ // through the file it writes while the API runs; the key comes from ZERO1LLM_API_KEY or the options.
4
+ import { readFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ /** As `APP_NAME` and the app identifier in Zero1LLM's brand (a test checks they match; a rename edits both). */
8
+ export const APP_NAME = 'Zero1LLM';
9
+ const APP_ID = 'ai.zero1llm.desktop';
10
+ const DEFAULT_URL = 'http://127.0.0.1:47820';
11
+ /** The local API version this SDK speaks. */
12
+ export const API_VERSION = 1;
13
+ /**
14
+ * Why a request failed. `code`: `NOT_RUNNING` (the app is closed or its local API is off), `UNAUTHORIZED`,
15
+ * `MODEL_NOT_FOUND`, `NOT_LOADED`, `NO_ROOM`, `ONE_AT_A_TIME`, `BAD_REQUEST`, `NOT_SUPPORTED`, or another the app sends.
16
+ */
17
+ export class Zero1LLMError extends Error {
18
+ code;
19
+ status;
20
+ constructor(message, code, status) {
21
+ super(message);
22
+ this.code = code;
23
+ this.status = status;
24
+ this.name = 'Zero1LLMError';
25
+ }
26
+ }
27
+ /** Where the app keeps its data (Tauri's app data folder): the production app first, then test and development builds. */
28
+ function discoveryFiles() {
29
+ const home = homedir();
30
+ const base = process.platform === 'darwin'
31
+ ? join(home, 'Library', 'Application Support')
32
+ : process.platform === 'win32'
33
+ ? (process.env.APPDATA ?? join(home, 'AppData', 'Roaming'))
34
+ : (process.env.XDG_DATA_HOME ?? join(home, '.local', 'share'));
35
+ return [APP_ID, `${APP_ID}.test`, `${APP_ID}.dev`].map(id => join(base, id, 'local-api.json'));
36
+ }
37
+ const alive = (pid) => {
38
+ if (typeof pid !== 'number')
39
+ return false;
40
+ try {
41
+ process.kill(pid, 0);
42
+ return true;
43
+ }
44
+ catch (e) {
45
+ // Running as another user: there, but not ours to signal.
46
+ return e.code === 'EPERM';
47
+ }
48
+ };
49
+ /** The running app's address, from the file it writes while its local API runs; undefined when none runs. */
50
+ export function discover(files = discoveryFiles()) {
51
+ for (const f of files) {
52
+ try {
53
+ const d = JSON.parse(readFileSync(f, 'utf8'));
54
+ if (typeof d.host === 'string' && typeof d.port === 'number' && alive(d.pid))
55
+ return `http://${d.host}:${d.port}`;
56
+ }
57
+ catch {
58
+ // not there, or being written
59
+ }
60
+ }
61
+ return undefined;
62
+ }
63
+ export class Zero1LLM {
64
+ baseURL;
65
+ apiKey;
66
+ models = {
67
+ /** Every model you can use: local ones and the cloud ones the app offers. */
68
+ list: async () => {
69
+ const r = (await this.json('GET', '/v1/models'));
70
+ return r.data.map(m => ({
71
+ id: String(m.id),
72
+ name: String(m.name ?? m.id),
73
+ ownedBy: String(m.owned_by ?? ''),
74
+ local: String(m.id).startsWith('local/'),
75
+ ...(typeof m.loaded === 'boolean' ? { loaded: m.loaded } : {}),
76
+ }));
77
+ },
78
+ /** The models on this computer, with size, state and how well each runs here. */
79
+ local: async () => (await this.json('GET', '/api/v1/models')).data,
80
+ /** Loads a model on this computer (waits until it's ready); `onProgress` hears how far it is. */
81
+ load: async (model, options = {}) => {
82
+ const { model: loaded } = await this.job('/api/v1/models/load', { model: localId(model) }, 'LOAD_FAILED', options.signal, options.onProgress);
83
+ if (!loaded)
84
+ throw new Zero1LLMError('The app stopped before it was done.', 'LOAD_FAILED');
85
+ return loaded;
86
+ },
87
+ /** Stops a running model, freeing its memory. */
88
+ eject: async (model) => (await this.json('POST', '/api/v1/models/eject', { model: localId(model) })),
89
+ };
90
+ chat = {
91
+ /** The whole answer at once. */
92
+ respond: async (options) => {
93
+ const r = (await this.json('POST', '/v1/chat/completions', chatBody(options, false), options.signal));
94
+ const choice = r.choices?.[0];
95
+ const content = choice?.message?.content ?? '';
96
+ const reply = {
97
+ content,
98
+ toolCalls: choice?.message?.tool_calls ?? [],
99
+ finishReason: choice?.finish_reason ?? null,
100
+ ...(choice?.message?.reasoning_content ? { reasoning: choice.message.reasoning_content } : {}),
101
+ ...(r.usage ? { usage: { promptTokens: r.usage.prompt_tokens, completionTokens: r.usage.completion_tokens } } : {}),
102
+ };
103
+ if (options.schema) {
104
+ try {
105
+ reply.parsed = JSON.parse(content);
106
+ }
107
+ catch {
108
+ throw new Zero1LLMError('The answer was not valid JSON for the schema (it may have been cut off: give it more maxTokens).', 'BAD_ANSWER');
109
+ }
110
+ }
111
+ return reply;
112
+ },
113
+ /** The answer as it is written, piece by piece. */
114
+ stream: (options) => this.events(chatBody(options, true), options.signal),
115
+ /**
116
+ * Lets the model use your functions: each call it makes is run here and the result given back, until it answers
117
+ * without calling one. The reply's `messages` is the whole conversation, to continue it.
118
+ */
119
+ act: async (options) => {
120
+ const { tools, maxRounds = 10, onToolCall, ...rest } = options;
121
+ const defs = tools.map(t => ({ type: 'function', function: { name: t.name, ...(t.description ? { description: t.description } : {}), ...(t.parameters ? { parameters: t.parameters } : {}) } }));
122
+ const messages = typeof rest.messages === 'string' ? [{ role: 'user', content: rest.messages }] : [...rest.messages];
123
+ for (let round = 0; round < maxRounds; round++) {
124
+ const reply = await this.chat.respond({ ...rest, messages, tools: defs });
125
+ if (!reply.toolCalls.length)
126
+ return { ...reply, messages: [...messages, { role: 'assistant', content: reply.content }] };
127
+ messages.push({ role: 'assistant', content: reply.content || null, tool_calls: reply.toolCalls });
128
+ for (const call of reply.toolCalls) {
129
+ const result = await runTool(tools, call);
130
+ onToolCall?.({ name: call.function.name, args: result.args, result: result.value });
131
+ messages.push({ role: 'tool', tool_call_id: call.id, content: typeof result.value === 'string' ? result.value : JSON.stringify(result.value) ?? 'null' });
132
+ }
133
+ }
134
+ throw new Zero1LLMError(`The model was still calling tools after ${maxRounds} rounds.`, 'TOO_MANY_ROUNDS');
135
+ },
136
+ };
137
+ /**
138
+ * The app's own chat (D230), as if typed in the app: web search, thinking, memory, the user's connectors' tools with
139
+ * Allow / Deny, pictures. Chats are saved in the app's sidebar.
140
+ */
141
+ assistant = {
142
+ send: (options) => {
143
+ const chatId = options.chatId ?? crypto.randomUUID();
144
+ const body = {
145
+ call: 'send',
146
+ chatId,
147
+ text: options.text,
148
+ web: options.web === true,
149
+ think: options.think === true,
150
+ ...(options.model ? { model: options.model } : {}),
151
+ ...(options.save === false ? { save: false } : {}),
152
+ ...(options.attachments?.length ? { attachments: options.attachments.map(a => ({ name: a.name, data: Buffer.from(a.data).toString('base64') })) } : {}),
153
+ };
154
+ return {
155
+ chatId,
156
+ [Symbol.asyncIterator]: () => this.assistantEvents(body, options.signal)[Symbol.asyncIterator](),
157
+ decide: answer => this.assistant.decide(chatId, answer),
158
+ answer: answers => this.assistant.answer(chatId, answers),
159
+ };
160
+ },
161
+ decide: async (chatId, answer) => void (await this.json('POST', '/api/v1/assistant', { call: 'decide', chatId, answer })),
162
+ answer: async (chatId, answers) => void (await this.json('POST', '/api/v1/assistant', { call: 'answer', chatId, ...(answers ? { answers } : {}) })),
163
+ /** The chats saved in the app, newest first. */
164
+ chats: async () => (await this.assistantLine({ call: 'chats' }, 'chats')) ?? [],
165
+ /** A saved chat's messages: `{ role: 'user', text }` and `{ role: 'assistant', entry }`. */
166
+ open: async (chatId) => (await this.assistantLine({ call: 'open', chatId }, 'messages')) ?? [],
167
+ delete: async (chatId) => void (await this.assistantLine({ call: 'delete', chatId }, 'chats')),
168
+ };
169
+ /** Pictures, made where and as large as the app's chat would make them (this computer or the cloud). */
170
+ images = {
171
+ /** `shape`: '1:1', '16:9', '9:16', '4:3', '3:4' or '4:5'; default the one set in the app. */
172
+ create: async (options) => made(await this.job('/api/v1/images', { prompt: options.prompt, ...(options.shape ? { shape: options.shape } : {}) }, 'MEDIA_FAILED', options.signal)),
173
+ };
174
+ /** Short videos, made on this computer. */
175
+ videos = {
176
+ create: async (options) => made(await this.job('/api/v1/videos', { prompt: options.prompt, ...(options.seconds ? { seconds: options.seconds } : {}), ...(options.shape ? { shape: options.shape } : {}) }, 'MEDIA_FAILED', options.signal)),
177
+ };
178
+ constructor(options = {}) {
179
+ this.apiKey = options.apiKey ?? process.env.ZERO1LLM_API_KEY;
180
+ this.baseURL = (options.baseURL ?? process.env.ZERO1LLM_BASE_URL ?? discover() ?? DEFAULT_URL).replace(/\/+$/, '').replace(/\/v1$/, '');
181
+ }
182
+ async request(method, path, body, signal) {
183
+ if (!this.apiKey)
184
+ throw new Zero1LLMError(`Set ZERO1LLM_API_KEY, or pass { apiKey }: copy the key from ${APP_NAME} → Settings → Local API.`, 'UNAUTHORIZED');
185
+ let res;
186
+ try {
187
+ res = await fetch(this.baseURL + path, {
188
+ method,
189
+ headers: { authorization: `Bearer ${this.apiKey}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },
190
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
191
+ ...(signal ? { signal } : {}),
192
+ });
193
+ }
194
+ catch (e) {
195
+ if (e.name === 'AbortError')
196
+ throw e;
197
+ // Node's fetch waits 5 minutes for the status; the app is running, just slow.
198
+ if (e.cause?.code === 'UND_ERR_HEADERS_TIMEOUT')
199
+ throw new Zero1LLMError(`${APP_NAME} took too long to answer.`, 'TIMEOUT');
200
+ throw new Zero1LLMError(`${APP_NAME} isn't running at ${this.baseURL}, or its local API is off: open ${APP_NAME} → Settings → Local API.`, 'NOT_RUNNING');
201
+ }
202
+ if (!res.ok) {
203
+ const text = await res.text();
204
+ let err = {};
205
+ try {
206
+ const j = JSON.parse(text);
207
+ err = { message: j.error?.message, code: j.error?.code ?? j.error?.type };
208
+ }
209
+ catch {
210
+ // not JSON
211
+ }
212
+ throw new Zero1LLMError(err.message ?? (text || `HTTP ${res.status}`), err.code ?? `HTTP_${res.status}`, res.status);
213
+ }
214
+ return res;
215
+ }
216
+ async json(method, path, body, signal) {
217
+ return (await this.request(method, path, body, signal)).json();
218
+ }
219
+ async *events(body, signal) {
220
+ const res = await this.request('POST', '/v1/chat/completions', body, signal);
221
+ for await (const line of textLines(res)) {
222
+ if (!line.startsWith('data:'))
223
+ continue;
224
+ const data = line.slice(5).trim();
225
+ if (data === '[DONE]')
226
+ return;
227
+ const chunk = JSON.parse(data);
228
+ if (chunk.error)
229
+ throw new Zero1LLMError(chunk.error.message ?? 'The answer broke off.', 'STREAM_ERROR');
230
+ const delta = chunk.choices?.[0]?.delta;
231
+ const part = { text: delta?.content ?? '', reasoning: delta?.reasoning_content ?? '' };
232
+ if (part.text || part.reasoning)
233
+ yield part;
234
+ }
235
+ }
236
+ /** The app chat's JSON lines as events; an error line throws. */
237
+ async *assistantEvents(body, signal) {
238
+ for await (const line of this.lines('/api/v1/assistant', body, signal))
239
+ yield toEvent(line);
240
+ }
241
+ /** A JSON-lines answer, line by line; a whole JSON answer (a call with no lines) as its one line. */
242
+ async *lines(path, body, signal) {
243
+ const res = await this.request('POST', path, body, signal);
244
+ if (!res.headers.get('content-type')?.includes('ndjson')) {
245
+ yield (await res.json());
246
+ return;
247
+ }
248
+ for await (const text of textLines(res))
249
+ if (text.trim())
250
+ yield JSON.parse(text);
251
+ }
252
+ /**
253
+ * A long job (a load, a picture, a video) as JSON lines, which the app keeps alive while it works, so no client
254
+ * timeout cuts it off: progress lines go to `onProgress`, an error line throws, the first other line is the result.
255
+ */
256
+ async job(path, body, failed, signal, onProgress) {
257
+ for await (const line of this.lines(path, { ...body, progress: true }, signal)) {
258
+ if (typeof line.error === 'string')
259
+ throw new Zero1LLMError(line.error, typeof line.code === 'string' ? line.code : failed);
260
+ if (line.progress)
261
+ onProgress?.(line.progress);
262
+ else
263
+ return line;
264
+ }
265
+ throw new Zero1LLMError('The app stopped before it was done.', failed);
266
+ }
267
+ /** Field `key` of the first line that has it. */
268
+ async assistantLine(body, key) {
269
+ for await (const ev of this.assistantEvents(body))
270
+ if (ev.type === 'status' && key in ev.status)
271
+ return ev.status[key];
272
+ return undefined;
273
+ }
274
+ }
275
+ /** A streamed answer's lines, the last one too when it has no newline. */
276
+ async function* textLines(res) {
277
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
278
+ let buffer = '';
279
+ // Where the newline search goes on from: a picture comes as one long line over many reads.
280
+ let scanned = 0;
281
+ try {
282
+ for (;;) {
283
+ let read;
284
+ try {
285
+ read = await reader.read();
286
+ }
287
+ catch (e) {
288
+ if (e.name === 'AbortError')
289
+ throw e;
290
+ throw new Zero1LLMError(`The answer broke off: ${APP_NAME} stopped or the connection closed.`, 'STREAM_ERROR');
291
+ }
292
+ const { value, done } = read;
293
+ if (value)
294
+ buffer += value;
295
+ let end;
296
+ while ((end = buffer.indexOf('\n', scanned)) >= 0) {
297
+ yield buffer.slice(0, end);
298
+ buffer = buffer.slice(end + 1);
299
+ scanned = 0;
300
+ }
301
+ scanned = buffer.length;
302
+ if (done) {
303
+ if (buffer)
304
+ yield buffer;
305
+ return;
306
+ }
307
+ }
308
+ }
309
+ finally {
310
+ // A caller that stops early (`[DONE]`, a `break`) closes the connection, so the app stops writing.
311
+ await reader.cancel().catch(() => undefined);
312
+ }
313
+ }
314
+ function made(r) {
315
+ const m = r;
316
+ return { ...m, bytes: Buffer.from(m.url.slice(m.url.indexOf(',') + 1), 'base64') };
317
+ }
318
+ /** Runs the function a tool call names; a missing function, bad arguments or a throw become the result the model sees. */
319
+ async function runTool(tools, call) {
320
+ const tool = tools.find(t => t.name === call.function.name);
321
+ if (!tool)
322
+ return { args: undefined, value: `Error: there is no tool named ${call.function.name}.` };
323
+ let args;
324
+ try {
325
+ args = JSON.parse(call.function.arguments || '{}');
326
+ }
327
+ catch {
328
+ return { args: call.function.arguments, value: 'Error: the arguments were not valid JSON.' };
329
+ }
330
+ try {
331
+ return { args, value: await tool.run(args) };
332
+ }
333
+ catch (e) {
334
+ return { args, value: `Error: ${e.message ?? String(e)}` };
335
+ }
336
+ }
337
+ function toEvent(line) {
338
+ if (typeof line.error === 'string')
339
+ throw new Zero1LLMError(line.error, typeof line.code === 'string' ? line.code : 'APP_ERROR');
340
+ if (line.entry)
341
+ return { type: 'answer', entry: line.entry };
342
+ for (const type of ['picture', 'video', 'file'])
343
+ if (line[type])
344
+ return { type, ...line[type] };
345
+ if (typeof line.progress === 'string')
346
+ return { type: 'progress', text: line.progress };
347
+ return { type: 'status', status: line };
348
+ }
349
+ /** A bare model name means a local one. */
350
+ const localId = (model) => (model.startsWith('local/') || model.startsWith('cloud/') ? model : `local/${model}`);
351
+ function chatBody(o, stream) {
352
+ return {
353
+ model: o.model,
354
+ messages: typeof o.messages === 'string' ? [{ role: 'user', content: o.messages }] : o.messages,
355
+ stream,
356
+ ...(o.temperature !== undefined ? { temperature: o.temperature } : {}),
357
+ ...(o.maxTokens !== undefined ? { max_tokens: o.maxTokens } : {}),
358
+ ...(o.think ? { reasoning_effort: 'medium' } : {}),
359
+ ...(o.schema ? { response_format: { type: 'json_schema', json_schema: { name: 'response', strict: true, schema: o.schema } } } : {}),
360
+ ...(o.tools?.length ? { tools: o.tools } : {}),
361
+ };
362
+ }
package/package.json CHANGED
@@ -1,11 +1,23 @@
1
1
  {
2
2
  "name": "@zero1llm/sdk",
3
- "version": "0.0.1",
4
- "description": "The official Zero1LLM SDK, coming soon. Placeholder, no code yet.",
3
+ "version": "0.1.0",
4
+ "description": "Use the models in Zero1LLM from your own code: chat, streaming, structured output, tools, and loading models.",
5
5
  "license": "MIT",
6
- "homepage": "https://www.zero1llm.ai",
7
- "author": "Zero1LLM",
8
- "keywords": ["zero1llm", "llm", "ai"],
9
- "files": ["README.md", "LICENSE"],
10
- "publishConfig": { "access": "public" }
6
+ "repository": { "type": "git", "url": "git+https://github.com/THE01X-Zeronex/Zero1LLM.git", "directory": "packages/sdk" },
7
+ "type": "module",
8
+ "homepage": "https://www.zero1llm.ai/docs/local-api",
9
+ "keywords": ["zero1llm", "llm", "local", "ai", "sdk", "openai-compatible"],
10
+ "engines": { "node": ">=20" },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": ["dist", "README.md"],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "typecheck": "tsc -p tsconfig.test.json --noEmit",
21
+ "test": "tsc -p tsconfig.test.json && node --test \"out/test/**/*.test.js\""
22
+ }
11
23
  }