llmjs2 1.6.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +116 -18
  2. package/dist/index.d.mts +146 -0
  3. package/dist/index.d.ts +146 -0
  4. package/dist/index.js +1242 -0
  5. package/dist/index.mjs +1211 -0
  6. package/package.json +32 -55
  7. package/chain/AGENT_STEP_README.md +0 -102
  8. package/chain/README.md +0 -257
  9. package/chain/WORKFLOW_README.md +0 -85
  10. package/chain/agent-step-example.js +0 -232
  11. package/chain/docs/AGENT.md +0 -126
  12. package/chain/docs/GRAPH.md +0 -490
  13. package/chain/examples.js +0 -314
  14. package/chain/index.js +0 -31
  15. package/chain/lib/agent.js +0 -338
  16. package/chain/lib/flow/agent-step.js +0 -119
  17. package/chain/lib/flow/edge.js +0 -24
  18. package/chain/lib/flow/flow.js +0 -76
  19. package/chain/lib/flow/graph.js +0 -331
  20. package/chain/lib/flow/index.js +0 -7
  21. package/chain/lib/flow/step.js +0 -63
  22. package/chain/lib/memory/in-memory.js +0 -117
  23. package/chain/lib/memory/index.js +0 -36
  24. package/chain/lib/memory/lance-memory.js +0 -225
  25. package/chain/lib/memory/sqlite-memory.js +0 -309
  26. package/chain/simple-agent-step-example.js +0 -168
  27. package/chain/workflow-example-usage.js +0 -70
  28. package/chain/workflow-example.json +0 -59
  29. package/core/README.md +0 -485
  30. package/core/cli.js +0 -275
  31. package/core/config.yaml +0 -149
  32. package/core/docs/BASIC_USAGE.md +0 -62
  33. package/core/docs/CLI.md +0 -104
  34. package/core/docs/GET_STARTED.md +0 -129
  35. package/core/docs/GUARDRAILS_GUIDE.md +0 -734
  36. package/core/docs/README.md +0 -47
  37. package/core/docs/ROUTER_GUIDE.md +0 -199
  38. package/core/docs/SERVER_MODE.md +0 -358
  39. package/core/index.js +0 -115
  40. package/core/logger.js +0 -115
  41. package/core/providers/ollama.js +0 -128
  42. package/core/providers/openai.js +0 -112
  43. package/core/providers/openrouter.js +0 -121
  44. package/core/router.js +0 -252
  45. package/core/server.js +0 -203
package/README.md CHANGED
@@ -1,31 +1,129 @@
1
1
  # llmjs2
2
2
 
3
- llmjs2 is a unified Node.js library for OpenAI, Ollama, and OpenRouter with routing, guardrails, and an OpenAI-style server mode.
3
+ A lightweight Node.js library for LLM completions, routing and simple agent workflows.
4
4
 
5
- ## Quick Links
5
+ **Description**: A minimal toolkit to call multiple LLM providers (OpenAI, OpenRouter, Ollama, BigModel), route requests across model lists with optional guardrails, and run simple agent workflows with pluggable tools and memory backends.
6
6
 
7
- - Core README: core/README.md
8
- - CLI Guide: core/docs/CLI.md
9
- - Server Mode: core/docs/SERVER_MODE.md
10
- - Router Guide: core/docs/ROUTER_GUIDE.md
7
+ **Install**
11
8
 
12
- ## Install
9
+ Install from npm:
13
10
 
14
- ```bash
11
+ ```
15
12
  npm install llmjs2
16
13
  ```
17
14
 
18
- ## Basic Usage
15
+ **Build (from source)**
16
+
17
+ ```
18
+ npm run build
19
+ ```
20
+
21
+ **Quick Start**
22
+
23
+ - **Simple completion (string prompt)**: Returns the raw provider response object.
24
+
25
+ ```js
26
+ import { completion } from 'llmjs2';
27
+
28
+ const resp = await completion('Write a friendly greeting.');
29
+ console.log(resp);
30
+ ```
31
+
32
+ - **Full options**: Provide `model` in the form `provider/model_name` (e.g. `openai/gpt-4o-mini`).
33
+
34
+ ```js
35
+ import { completion } from 'llmjs2';
36
+
37
+ const resp = await completion({
38
+ model: 'openai/gpt-4o-mini',
39
+ messages: [{ role: 'user', content: 'Summarize Node.js event loop.' }],
40
+ });
41
+ ```
42
+
43
+ **Router (multi-route LLM routing)**
44
+
45
+ - Create a router from a config object or a path to a JSON/JS config file. The router selects a route (random or sequential) and applies optional guardrails.
46
+
47
+ ```js
48
+ import { router } from 'llmjs2';
49
+
50
+ const r = router({
51
+ routing: 'random',
52
+ model_list: [
53
+ { model_name: 'primary', llm_params: { model: 'openai/gpt-4o-mini' } },
54
+ { model_name: 'backup', llm_params: { model: 'openrouter/openai/gpt-4o-mini' } },
55
+ ],
56
+ });
57
+
58
+ const res = await r.completion({ messages: [{ role: 'user', content: 'Hello' }] });
59
+ ```
60
+
61
+ Guardrails can be provided to modify requests pre-call or post-call.
62
+
63
+ **Agent**
64
+
65
+ - The `Agent` wraps a routing instance, optional `Memory` backend, and optional `tools`. It supports multi-turn flows and tool-calls returned by models.
66
+
67
+ ```js
68
+ import { Agent, inMemory } from 'llmjs2';
69
+
70
+ const agent = new Agent({
71
+ instruction: 'You are a helpful assistant.',
72
+ route: router({ model_list: [{ model_name: 'r', llm_params: { model: 'openai/gpt-4o-mini' } }] }),
73
+ memory: inMemory(),
74
+ tools: [
75
+ {
76
+ name: 'echo',
77
+ description: 'Echoes input',
78
+ parameters: { text: { type: 'string', description: 'Text', required: true } },
79
+ execute: async (params) => `ECHO: ${params.text}`,
80
+ },
81
+ ],
82
+ });
83
+
84
+ const out = await agent.generate('Say hello and use the echo tool.');
85
+ console.log(out);
86
+ ```
87
+
88
+ **Memory**
89
+
90
+ - In-memory storage (ephemeral): `inMemory()`
91
+ - File-based storage: `fileMemory({ path: './memory.json' })`
92
+
93
+ Both implement: `save(resourceId, threadId, role, content)`, `list(resourceId, threadId, limit)`, `search(resourceId, query)`, `clear(resourceId, threadId)`.
19
94
 
20
- ```javascript
21
- const { completion } = require('llmjs2');
95
+ **Logging / Verbosity**
22
96
 
23
- (async () => {
24
- const result = await completion({
25
- model: 'openai/gpt-4',
26
- messages: [{ role: 'user', content: 'Say hello in one sentence.' }]
27
- });
97
+ Set verbosity with `verbose('debug'|'info'|'none')`:
28
98
 
29
- console.log(result);
30
- })();
99
+ ```js
100
+ import { verbose } from 'llmjs2';
101
+ verbose('debug');
31
102
  ```
103
+
104
+ **Configuration / Environment Variables**
105
+
106
+ - `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `OPENAI_DEFAULT_MODEL`
107
+ - `OPEN_ROUTER_API_KEY`, `OPEN_ROUTER_BASE_URL`, `OPEN_ROUTER_DEFAULT_MODEL`
108
+ - `BIGMODEL_API_KEY`, `BIGMODEL_BASE_URL`, `BIGMODEL_DEFAULT_MODEL`
109
+ - `OLLAMA_API_KEY`, `OLLAMA_BASE_URL`, `OLLAMA_DEFAULT_MODEL`
110
+ - `LLM_DEFAULT_MODEL` — fallback model when none provided in options
111
+
112
+ The library reads these from `process.env` or via the `getConfig()` defaults.
113
+
114
+ **API Reference (exports)**
115
+
116
+ - `completion(promptOrOptions)` — single-call completion helper. Accepts a string or a `CompletionOptions` object.
117
+ - `router(configOrPath)` — build a router instance from config object or file path. Returns `{ completion(options) }`.
118
+ - `Agent` / `createAgent(config)` — agent class for multi-turn workflows and tool execution.
119
+ - `inMemory()` / `fileMemory({ path })` — memory backends.
120
+ - `verbose(level)` — set logger verbosity.
121
+
122
+ **Build & Publish Notes**
123
+
124
+ - The package builds to `dist/` via `npm run build` (uses `tsup`). The `prepublishOnly` script runs the build.
125
+ - Entry points: CommonJS `./dist/index.js`, ESM `./dist/index.mjs`, types at `./dist/index.d.ts`.
126
+
127
+ **License**
128
+
129
+ ISC
@@ -0,0 +1,146 @@
1
+ type MessageContent = string;
2
+ interface Message {
3
+ role: 'system' | 'user' | 'assistant' | 'tool';
4
+ content: MessageContent;
5
+ images?: string[];
6
+ tool_calls?: any[];
7
+ tool_call_id?: string;
8
+ }
9
+ interface ToolParameter {
10
+ type: string;
11
+ description: string;
12
+ required?: boolean;
13
+ }
14
+ interface Tool {
15
+ name: string;
16
+ description?: string;
17
+ parameters: Record<string, ToolParameter>;
18
+ }
19
+ interface CompletionOptions {
20
+ model: string;
21
+ host?: string;
22
+ baseUrl?: string;
23
+ messages: Message[];
24
+ apiKey?: string;
25
+ tools?: Tool[];
26
+ }
27
+ type GuardrailMode = 'pre_call' | 'post_call';
28
+ interface PreCallInput {
29
+ model: string;
30
+ messages: Message[];
31
+ tools?: Tool[];
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+ type GuardrailHandler = (processId: string, payload: any) => any | Promise<any>;
35
+ interface GuardrailConfig {
36
+ name: string;
37
+ mode: GuardrailMode;
38
+ code: string | GuardrailHandler;
39
+ enabled?: boolean;
40
+ timeout_ms?: number;
41
+ }
42
+ type ProviderName = 'openai' | 'openrouter' | 'ollama' | 'bigmodel';
43
+ interface ProviderConfig {
44
+ apiKey?: string;
45
+ baseUrl?: string;
46
+ defaultModel?: string;
47
+ }
48
+ interface Config {
49
+ openai: ProviderConfig;
50
+ openrouter: ProviderConfig;
51
+ ollama: ProviderConfig;
52
+ bigmodel: ProviderConfig;
53
+ }
54
+
55
+ declare function completion(promptOrOptions: string | CompletionOptions): Promise<any>;
56
+
57
+ type RoutingStrategy = 'random' | 'sequential' | 'default';
58
+ interface RouterModelParams extends Omit<CompletionOptions, 'messages'> {
59
+ model: string;
60
+ api_key?: string;
61
+ api_base?: string;
62
+ }
63
+ interface RouterModelEntry {
64
+ model_name: string;
65
+ llm_params: RouterModelParams;
66
+ }
67
+ interface RouterConfig {
68
+ routing?: RoutingStrategy;
69
+ model_list: RouterModelEntry[];
70
+ guardrails?: GuardrailConfig[];
71
+ }
72
+ interface RouterRequestOptions extends Omit<CompletionOptions, 'model'> {
73
+ model?: string;
74
+ }
75
+ interface RouterInstance {
76
+ completion(options: RouterRequestOptions): Promise<any>;
77
+ }
78
+ declare function router(configOrPath: RouterConfig | string): RouterInstance;
79
+
80
+ type MemoryRole = 'user' | 'assistant';
81
+ interface Memory {
82
+ save(resourceId: string, threadId: string, role: MemoryRole, content: string): Promise<void>;
83
+ list(resourceId: string, threadId: string, limit?: number): Promise<Array<{
84
+ role: MemoryRole;
85
+ content: string;
86
+ }>>;
87
+ search(resourceId: string, query: string): Promise<Array<{
88
+ content: string;
89
+ threadId: string;
90
+ }>>;
91
+ clear(resourceId: string, threadId: string): Promise<void>;
92
+ }
93
+ declare function inMemory(): Memory;
94
+ declare function fileMemory(config: {
95
+ path: string;
96
+ }): Memory;
97
+
98
+ type memory_Memory = Memory;
99
+ declare const memory_fileMemory: typeof fileMemory;
100
+ declare const memory_inMemory: typeof inMemory;
101
+ declare namespace memory {
102
+ export { type memory_Memory as Memory, memory_fileMemory as fileMemory, memory_inMemory as inMemory };
103
+ }
104
+
105
+ interface AgentTool extends Tool {
106
+ execute: (params: Record<string, unknown>) => Promise<string>;
107
+ }
108
+ interface AgentConfig {
109
+ instruction: string;
110
+ route: RouterInstance;
111
+ memory?: Memory;
112
+ session?: boolean;
113
+ relevance?: boolean;
114
+ tools?: AgentTool[];
115
+ }
116
+ interface GenerateMemoryRequest {
117
+ resourceId: string;
118
+ threadId: string;
119
+ session?: boolean;
120
+ relevance?: boolean;
121
+ }
122
+ interface GenerateRequest {
123
+ userPrompt: string;
124
+ memory?: GenerateMemoryRequest;
125
+ attachments?: (string | Buffer)[];
126
+ }
127
+ interface ToolCallResponse {
128
+ content: string;
129
+ toolCalls: Array<{
130
+ name: string;
131
+ parameters: Record<string, unknown>;
132
+ result: string;
133
+ }>;
134
+ }
135
+ declare class Agent {
136
+ private config;
137
+ constructor(config: AgentConfig);
138
+ generate(request: string | GenerateRequest): Promise<string | ToolCallResponse>;
139
+ }
140
+ /** @deprecated Use `new Agent(config)` instead. */
141
+ declare function createAgent(config: AgentConfig): Agent;
142
+
143
+ type VerboseLevel = 'debug' | 'info' | 'none';
144
+ declare function verbose(level: VerboseLevel): void;
145
+
146
+ export { Agent, type AgentConfig, type AgentTool, type CompletionOptions, type Config, type GenerateMemoryRequest, type GenerateRequest, type GuardrailConfig, type GuardrailHandler, type GuardrailMode, memory as Memory, type Message, type MessageContent, type PreCallInput, type ProviderConfig, type ProviderName, type RouterConfig, type RouterInstance, type RouterModelEntry, type RouterModelParams, type RouterRequestOptions, type RoutingStrategy, type Tool, type ToolCallResponse, type ToolParameter, completion, createAgent, fileMemory, inMemory, router, verbose };
@@ -0,0 +1,146 @@
1
+ type MessageContent = string;
2
+ interface Message {
3
+ role: 'system' | 'user' | 'assistant' | 'tool';
4
+ content: MessageContent;
5
+ images?: string[];
6
+ tool_calls?: any[];
7
+ tool_call_id?: string;
8
+ }
9
+ interface ToolParameter {
10
+ type: string;
11
+ description: string;
12
+ required?: boolean;
13
+ }
14
+ interface Tool {
15
+ name: string;
16
+ description?: string;
17
+ parameters: Record<string, ToolParameter>;
18
+ }
19
+ interface CompletionOptions {
20
+ model: string;
21
+ host?: string;
22
+ baseUrl?: string;
23
+ messages: Message[];
24
+ apiKey?: string;
25
+ tools?: Tool[];
26
+ }
27
+ type GuardrailMode = 'pre_call' | 'post_call';
28
+ interface PreCallInput {
29
+ model: string;
30
+ messages: Message[];
31
+ tools?: Tool[];
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+ type GuardrailHandler = (processId: string, payload: any) => any | Promise<any>;
35
+ interface GuardrailConfig {
36
+ name: string;
37
+ mode: GuardrailMode;
38
+ code: string | GuardrailHandler;
39
+ enabled?: boolean;
40
+ timeout_ms?: number;
41
+ }
42
+ type ProviderName = 'openai' | 'openrouter' | 'ollama' | 'bigmodel';
43
+ interface ProviderConfig {
44
+ apiKey?: string;
45
+ baseUrl?: string;
46
+ defaultModel?: string;
47
+ }
48
+ interface Config {
49
+ openai: ProviderConfig;
50
+ openrouter: ProviderConfig;
51
+ ollama: ProviderConfig;
52
+ bigmodel: ProviderConfig;
53
+ }
54
+
55
+ declare function completion(promptOrOptions: string | CompletionOptions): Promise<any>;
56
+
57
+ type RoutingStrategy = 'random' | 'sequential' | 'default';
58
+ interface RouterModelParams extends Omit<CompletionOptions, 'messages'> {
59
+ model: string;
60
+ api_key?: string;
61
+ api_base?: string;
62
+ }
63
+ interface RouterModelEntry {
64
+ model_name: string;
65
+ llm_params: RouterModelParams;
66
+ }
67
+ interface RouterConfig {
68
+ routing?: RoutingStrategy;
69
+ model_list: RouterModelEntry[];
70
+ guardrails?: GuardrailConfig[];
71
+ }
72
+ interface RouterRequestOptions extends Omit<CompletionOptions, 'model'> {
73
+ model?: string;
74
+ }
75
+ interface RouterInstance {
76
+ completion(options: RouterRequestOptions): Promise<any>;
77
+ }
78
+ declare function router(configOrPath: RouterConfig | string): RouterInstance;
79
+
80
+ type MemoryRole = 'user' | 'assistant';
81
+ interface Memory {
82
+ save(resourceId: string, threadId: string, role: MemoryRole, content: string): Promise<void>;
83
+ list(resourceId: string, threadId: string, limit?: number): Promise<Array<{
84
+ role: MemoryRole;
85
+ content: string;
86
+ }>>;
87
+ search(resourceId: string, query: string): Promise<Array<{
88
+ content: string;
89
+ threadId: string;
90
+ }>>;
91
+ clear(resourceId: string, threadId: string): Promise<void>;
92
+ }
93
+ declare function inMemory(): Memory;
94
+ declare function fileMemory(config: {
95
+ path: string;
96
+ }): Memory;
97
+
98
+ type memory_Memory = Memory;
99
+ declare const memory_fileMemory: typeof fileMemory;
100
+ declare const memory_inMemory: typeof inMemory;
101
+ declare namespace memory {
102
+ export { type memory_Memory as Memory, memory_fileMemory as fileMemory, memory_inMemory as inMemory };
103
+ }
104
+
105
+ interface AgentTool extends Tool {
106
+ execute: (params: Record<string, unknown>) => Promise<string>;
107
+ }
108
+ interface AgentConfig {
109
+ instruction: string;
110
+ route: RouterInstance;
111
+ memory?: Memory;
112
+ session?: boolean;
113
+ relevance?: boolean;
114
+ tools?: AgentTool[];
115
+ }
116
+ interface GenerateMemoryRequest {
117
+ resourceId: string;
118
+ threadId: string;
119
+ session?: boolean;
120
+ relevance?: boolean;
121
+ }
122
+ interface GenerateRequest {
123
+ userPrompt: string;
124
+ memory?: GenerateMemoryRequest;
125
+ attachments?: (string | Buffer)[];
126
+ }
127
+ interface ToolCallResponse {
128
+ content: string;
129
+ toolCalls: Array<{
130
+ name: string;
131
+ parameters: Record<string, unknown>;
132
+ result: string;
133
+ }>;
134
+ }
135
+ declare class Agent {
136
+ private config;
137
+ constructor(config: AgentConfig);
138
+ generate(request: string | GenerateRequest): Promise<string | ToolCallResponse>;
139
+ }
140
+ /** @deprecated Use `new Agent(config)` instead. */
141
+ declare function createAgent(config: AgentConfig): Agent;
142
+
143
+ type VerboseLevel = 'debug' | 'info' | 'none';
144
+ declare function verbose(level: VerboseLevel): void;
145
+
146
+ export { Agent, type AgentConfig, type AgentTool, type CompletionOptions, type Config, type GenerateMemoryRequest, type GenerateRequest, type GuardrailConfig, type GuardrailHandler, type GuardrailMode, memory as Memory, type Message, type MessageContent, type PreCallInput, type ProviderConfig, type ProviderName, type RouterConfig, type RouterInstance, type RouterModelEntry, type RouterModelParams, type RouterRequestOptions, type RoutingStrategy, type Tool, type ToolCallResponse, type ToolParameter, completion, createAgent, fileMemory, inMemory, router, verbose };