openkbs 0.0.51 → 0.0.53

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.
@@ -1,7 +1,6 @@
1
1
  import {getActions} from './actions.js';
2
2
 
3
3
  export const backendHandler = async (event) => {
4
- const maxSelfInvokeMessagesCount = 60;
5
4
  const lastMessage = event.payload.messages[event.payload.messages.length - 1];
6
5
  const actions = getActions();
7
6
 
@@ -13,23 +12,20 @@ export const backendHandler = async (event) => {
13
12
  return acc;
14
13
  }, []);
15
14
 
16
- // For Coding Agents: avoid unnecessary LLM reactions after job is finished
17
- const isJobFinished = /"JOB_COMPLETED"|"JOB_FAILED"/.test(lastMessage.content);
18
-
19
- const meta = {
20
- _meta_actions:
21
- (
22
- event?.payload?.messages?.length > maxSelfInvokeMessagesCount ||
23
- isJobFinished && lastMessage.role === 'system'
24
- )
25
- ? []
26
- : ["REQUEST_CHAT_MODEL"]
27
- }
15
+ const reachedMessageLimit = event?.payload?.messages?.length > 60;
28
16
 
29
17
  if (matchingActions.length > 0) {
30
18
  try {
31
19
  const results = await Promise.all(matchingActions);
32
20
 
21
+ // IMPORTANT: Actions returning JOB_COMPLETED or JOB_FAILED stop agent execution and return final result
22
+ const isOnlyJobCompletion = results.length === 1 &&
23
+ (results[0]?.type === 'JOB_COMPLETED' || results[0]?.type === 'JOB_FAILED');
24
+
25
+ const meta = {
26
+ _meta_actions: (reachedMessageLimit || isOnlyJobCompletion) ? [] : ["REQUEST_CHAT_MODEL"]
27
+ };
28
+
33
29
  if (results?.[0]?.data?.some?.(o => o?.type === 'image_url')) {
34
30
  return {
35
31
  ...results[0],
@@ -46,7 +42,7 @@ export const backendHandler = async (event) => {
46
42
  return {
47
43
  type: 'ERROR',
48
44
  error: error.message,
49
- ...meta
45
+ _meta_actions: reachedMessageLimit ? [] : ["REQUEST_CHAT_MODEL"]
50
46
  };
51
47
  }
52
48
  }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.0.8"
3
- }
2
+ "version": "0.0.16"
3
+ }
@@ -5,12 +5,12 @@
5
5
 
6
6
  **FIRST**: Update the knowledge base:
7
7
  ```bash
8
- openkbs update knowledge
8
+ openkbs update
9
9
  ```
10
10
 
11
- **SECOND**: Read every file in the examples folder using the Read tool:
11
+ **SECOND**: Read every single file in the examples folder using the Read tool:
12
12
  - First discover all files in the `.openkbs/knowledge/examples/` directory and ALL subdirectories.
13
- - Then, use the Read tool to examine the content of EACH file individually (skip only icon.png files).
13
+ - Then, use the Read tool to examine the content of EACH file individually (skip only icon.png files, src/Frontend/Presentational/* and src/Events/Helpers/*).
14
14
  - You must read ALL files directly
15
15
 
16
16
  **THIRD**: Read existing agent code using the Read tool:
@@ -24,6 +24,17 @@ openkbs update knowledge
24
24
  - Study the complete working examples to understand OpenKBS patterns
25
25
  - Never guess framework methods, settings or variables — always reference the examples.
26
26
 
27
+ ## FIRST DECISION: Execution Context Analysis
28
+
29
+ ** BEFORE writing ANY code, you MUST answer these questions IN ORDER:**
30
+
31
+ 1. **Where will this code execute?** (Cloud or Local)
32
+ 2. **What resources does it need to access?** (List each: databases, APIs, files, etc.)
33
+ 3. **Where does each resource exist?** (Public internet, local network, specific machine)
34
+ 4. **Can the execution environment reach each resource?** (Network path exists?)
35
+
36
+ **You MUST show your reasoning for these 4 questions before any code implementation.**
37
+
27
38
  ## Development Guidelines
28
39
  - To add npm dependency to backend handlers, add it to onRequest.json and onResponse.json
29
40
  - In src/Events and src/Frontend always use Imports (not Require)
@@ -32,46 +43,76 @@ openkbs update knowledge
32
43
  - Add and use npm dependencies only if necessary, some of those shown in the examples are purely demonstrative
33
44
  - If developing new agent, generate it's own ./scripts/run_job.js
34
45
  - Before using third-party services in onRequest and onResponse handlers, ask the user for permission
46
+ - provide README.md
47
+
48
+ ## Architecture Overview: Execution Environments Define Everything
49
+
50
+ OpenKBS provides **three distinct execution environments**, each with different capabilities and constraints:
51
+
52
+ ### Execution Environment Reality Check
35
53
 
36
- ## Architecture Overview
37
- OpenKBS agents have **two execution environments**:
54
+ **Cloud Environment (`./src/Events/`):**
55
+ - Runs in serverless compute service for running code (stateless, ephemeral)
56
+ - No localhost, no local filesystem, no persistent state
57
+ - Can ONLY reach internet-accessible resources
58
+ - Each execution is isolated and temporary
38
59
 
39
- ### 1. Cloud Environment (`./src/`)
40
- - **Event handlers** (`onRequest.js`, `onResponse.js`) run on OpenKBS cloud platform
41
- - **Purpose**: Process user messages, execute AI actions, return responses
42
- - **Deployment**: Code is deployed via `openkbs push`
60
+ **Browser Environment (`./src/Frontend/`):**
61
+ - Runs in user's browser when visiting https://[kbId].apps.openkbs.com
62
+ - React-based UI customization
63
+ - Subject to browser security constraints
43
64
 
44
- ### 2. Local Environment (`./scripts/`)
45
- - **User-run scripts** execute locally on user's machine
46
- - **Purpose**: Call cloud agents via API, orchestrate multi-agent workflows, integrate with external systems
47
- - **Execution**: Run directly with `node scripts/script-name.js`
65
+ **Local Environment (`./scripts/`) - Optional but Powerful:**
66
+ - Runs on YOUR machine with YOUR network context
67
+ - Can access YOUR localhost, files, and local services
68
+ - Enables advanced patterns: multi-agent orchestration, local resource integration
69
+ - Not required for simple agents, but unlocks complex workflows
70
+
71
+ ### The Fundamental Rule
72
+ **Before writing ANY code, ask: Where does this run and what can it reach?**
48
73
 
49
74
  ### Backend
50
75
  The OpenKBS backend framework is for developing AI agents with custom tools, using Node.js.
51
76
  It integrates with openkbs chat service via `onRequest` and `onResponse` handlers for custom actions and service integration.
52
77
 
53
- #### Backend Handlers
78
+ #### Backend Handlers (Cloud Environment)
54
79
  The OpenKBS framework's core uses `onRequest` and `onResponse` handlers as middleware for message tool call parsing and execution.
55
- All these event handlers are executed on-demand (upon API request) by the OpenKBS cloud platform, where user production agents are deployed.
80
+ These handlers run in the cloud environment.
56
81
  - **`onResponse` Handler:** Activated after the LLM generates a message, enabling command extraction, and action execution.
57
82
  - **`onRequest` Handler:** Triggered on user message to allow the user to execute action
58
83
 
59
- #### NPM Dependencies for onRequest.js or onResponse.js Backend Handlers
84
+ #### NPM Dependencies for onRequest.js or onResponse.js Backend Handlers (Cloud → Public resources)
60
85
  1. If a file imports an NPM dependency and is then imported by onRequest.js or onResponse.js, this dependency must be defined in the handler's corresponding json file
61
86
  Example: If actions.js imports mysql2 and onResponse.js imports actions.js, then mysql2 must be in onResponse.json:
62
87
  {
63
88
  "dependencies": {
64
- "mysql2": "^3.14.2"
89
+ "mysql2": "latest"
65
90
  }
66
91
  }
67
92
 
68
93
  Similarly, we need to create onRequest.json for onRequest.js as each handler have separate Node.js build with separate dependencies
69
94
 
70
- #### Managing Secrets
71
- To securely manage sensitive information like API keys or database passwords within your backend event handlers (onRequest, onResponse, etc.), use the {{secrets.your_secret_name}} syntax.
95
+ #### Managing Secrets for Backend Handlers
96
+ Secrets securely store credentials that allow Backend Handlers to access external services like databases, APIs, etc.
97
+ Example:
98
+ `const key = "{{secrets.KEY}}"`
99
+
100
+ **Workflow**:
101
+ 1. Write code using {{secrets.SECRET_NAME}} placeholders
102
+ 2. Deploy agent with `openkbs push` (generates kbId in settings.json)
103
+ 3. Prompt developer to define secrets: `Please set your credentials at: https://[kbId].apps.openkbs.com/?add_secrets=SECRET_NAME1,SECRET_NAME2`
104
+
105
+ **Example**: For MySQL connection requiring {{secrets.DB_HOST}}, {{secrets.DB_USER}}, {{secrets.DB_PASS}}:
106
+ `Please define your database credentials: https://[kbId].apps.openkbs.com/?add_secrets=DB_HOST,DB_USER,DB_PASS`
107
+
108
+ **Important**
109
+ Secrets syntax above is only applicable for all src/Events/* files, and NOT for User-Run Scripts
72
110
 
73
- #### User-Run Scripts
74
- **User-run scripts** are located in `./scripts/` folder and communicate with cloud agents via API calls.
111
+ #### User-Run Scripts (Local Environment)
112
+ User-run scripts are located in the `./scripts/` folder and communicate with cloud agents via API calls.
113
+ They execute locally, receiving the final result of the agent's flow as an API response.
114
+ This setup allows seamless interaction with local services, such as a MySQL database, directly on the user's machine.
115
+ To handle secrets in user-defined scripts, define them in a `.env` file and load them using the `dotenv` package.
75
116
 
76
117
  **Key Components:**
77
118
  - `scripts/run_job.js` - Main job runner for calling the cloud agent
@@ -84,8 +125,18 @@ To securely manage sensitive information like API keys or database passwords wit
84
125
  - **Usage**: `const client = new OpenKBSAgentClient(); await client.runJob(message);`
85
126
  - **Multi-agent support**: Each agent (base or related) finds its own settings and secrets in its directory structure
86
127
 
87
- #### NPM Dependencies for User-Run Scripts
88
- Add needed NPM dependencies to `package.json`.
128
+ #### NPM Dependencies for User-Run Scripts (Local → Public + Private resources)
129
+ Add needed NPM dependencies to `package.json`
130
+ Example: Script connecting to local MySQL:
131
+ ```json
132
+ {
133
+ "dependencies": {
134
+ "mysql2": "latest",
135
+ "dotenv": "latest"
136
+ }
137
+ }
138
+ ```
139
+ Run `npm install` before executing scripts.
89
140
 
90
141
  ### Frontend Overview
91
142
  The OpenKBS frontend framework, built with React and MUI, offers a flexible platform for custom chat interfaces. Developers can customize chat appearance and behavior via the `contentRender` module.
@@ -95,15 +146,139 @@ The `contentRender.js` file is central to frontend customization, exporting key
95
146
  - **`onRenderChatMessage(params)`:** function called every time a chat message is rendered.
96
147
 
97
148
  #### OpenKBS commands
98
- `openkbs push` - after completing changes to your agent, use this command to deploy it to the OpenKBS cloud.
99
149
  `openkbs create my-agent` - creates a directory structure for a new agent
150
+ `openkbs push` - after completing changes to your agent, use this command to deploy it to the OpenKBS cloud.
151
+ `node scripts/run_job.js init` - execute right after `openkbs push` to configure the API Key before running the job for the specific agent.
100
152
 
101
153
  ### Creating Related Agents
102
154
  To create related agents that work alongside the main agent:
103
155
 
104
156
  1. **Create in related-agents/ folder**: `cd related-agents && openkbs create agent-name`
105
157
  2. **Each related agent gets**: Own `app/settings.json`, `src/` folder, and `.openkbs/secrets.json`
106
- 3. **Script usage**: Related agents use same `OpenKBSAgentClient` - it automatically finds their settings and secrets
158
+ 3. **Script usage**: Related agents use their own `agent_client.js` located in their subdirectory, ensuring they access their own settings and secrets file.
107
159
  4. **Multi-agent workflows**: Scripts can orchestrate multiple agents by creating separate client instances
108
160
 
109
161
  Related agents are independent but can share the base agent's script utilities.
162
+
163
+ ## OpenKBS Agent Architecture: From Single Agent to Complex Orchestration
164
+
165
+ ### Core Architecture Philosophy
166
+
167
+ OpenKBS enables everything from simple single-agent automation to sophisticated multi-agent systems through a **dual-environment architecture** that seamlessly combines **cloud-based autonomous agents** with **local orchestration scripts**.
168
+
169
+ ### Understanding Where Code Runs
170
+
171
+ **The fundamental principle**: Cloud agents operate in cloud infrastructure, local scripts run on your machine. This separation enables powerful patterns:
172
+
173
+ **Cloud agents (serverless functions)** can access:
174
+ - Internet-reachable services only
175
+ - Public APIs and databases
176
+ - Any service with a public endpoint
177
+
178
+ **Local scripts (on your machine)** can access:
179
+ - Local resources (localhost, 127.0.0.1, local files)
180
+ - Cloud agents via API calls
181
+ - Both local and internet resources
182
+
183
+ **Architecture emerges from execution context**: When resources exist only locally, the architecture naturally becomes: Local Script → Cloud Agent (processing) → JSON → Local Script → Local Resource
184
+
185
+ ### Advanced Pattern: Tool Composition (When Needed)
186
+
187
+ Since cloud agent tools are code, you can create composite tools when facing repetitive multi-step operations.
188
+ This is useful when an agent would otherwise need many interaction cycles for a single logical operation.
189
+
190
+ **Use sparingly**: Only create composite tools when they significantly reduce agent interactions or when domain logic requires atomic operations.
191
+
192
+ ### The Powerful Two-Environment System
193
+
194
+ #### 1. Cloud Environment (Autonomous Agent Execution)
195
+ **Location**: `./src/Events/` - Deployed via `openkbs push`
196
+ **Purpose**: Autonomous agent execution with intelligent decision-making
197
+
198
+ **Capabilities**:
199
+ - Autonomous multi-step workflows with decision branching
200
+ - Integration with ANY internet-accessible service (public or private)
201
+ - Secure credential management via {{secrets.KEY}} system
202
+ - Sequential tool call execution based on intermediate results
203
+ - Complex data extraction and structured JSON responses
204
+ - Access to cloud databases, public APIs, web services with proper credentials
205
+
206
+ **Agent Execution Flow**:
207
+ ```
208
+ User Message → Agent Processes → Tool Call 1 → Analyze Result → Decision → Tool Call 2 → ... → Final JSON Response
209
+ ```
210
+
211
+ **Key Insight**: Cloud agents can securely connect to APIs, and any service that have public IPs/URLs
212
+
213
+ #### 2. Local Environment (Orchestration & Local Services)
214
+ **Location**: `./scripts/` - Execute locally with `node`
215
+ **Purpose**: Agent orchestration and local infrastructure integration
216
+
217
+ **Capabilities**:
218
+ - Orchestrate multiple cloud agents in complex workflows
219
+ - Direct access to local services (localhost databases, file systems)
220
+ - Dynamic workflow creation based on agent responses
221
+ - Parallel and sequential agent coordination
222
+ - Local credential management via .env files
223
+ - Bridge between cloud intelligence and local infrastructure
224
+
225
+ ### Why This Architecture Matters
226
+
227
+ #### Key Architectural Insights
228
+ - **Cloud agents** = Autonomous intelligence with internet access
229
+ - **Local scripts** = Infrastructure control and orchestration
230
+ - Scripts call agents via API, agents return JSON, scripts handle the rest
231
+
232
+ ### Orchestration Patterns
233
+
234
+ Whether using a single agent or multiple agents, common patterns include:
235
+
236
+ 1. **Single Agent**: Script → Agent → Process Result → Store/Act
237
+ 2. **Hierarchical**: Script → Discovery Agent → N Results → Spawn N Detail Agents → Aggregate
238
+ 3. **Pipeline**: Script → Agent A → Agent B (uses A's output) → Agent C → Final Result
239
+ 4. **Event-Driven**: Database Change → Script Detects → Triggers Appropriate Agent(s)
240
+ 5. **Parallel**: Script → [Agent A, Agent B, Agent C] simultaneously → Combine Results
241
+ 6. **Database Integration**: Script reads local DB → Sends data to Agent → Agent processes → Returns JSON → Script stores in local DB
242
+
243
+
244
+ ### Understanding the Architecture
245
+
246
+ #### Cloud Agents (The Intelligence Layer)
247
+ **This is where ALL agentic flow happens:**
248
+ - Agents execute autonomously in the cloud
249
+ - Users can login to the chat UI at `https://[kbId].apps.openkbs.com` to monitor execution
250
+ - Each message and tool call is visible in the chat interface
251
+ - Agents make decisions, call tools, and process data autonomously
252
+ - The agent IS the intelligence - it thinks, decides, and acts
253
+
254
+ #### Local Scripts (The Orchestration Layer)
255
+ **Scripts are API clients that:**
256
+ - Call cloud agents via API
257
+ - Receive the final JSON result after agent completes its autonomous flow
258
+ - Handle local infrastructure (databases, files)
259
+ - Orchestrate multiple agent calls
260
+ - Process and route results between agents
261
+
262
+
263
+ ### Security & Best Practices
264
+
265
+ #### Cloud Security
266
+ - Use {{secrets.KEY}} for all sensitive credentials
267
+ - Secrets are encrypted and never exposed in code
268
+ - Each agent can have its own set of secrets
269
+ - Supports database passwords, API keys, OAuth tokens
270
+
271
+ #### Local Security
272
+ - Use .env files for local credentials
273
+ - Keep local scripts in private repositories
274
+ - Implement proper error handling and logging
275
+ - Use database transactions for consistency
276
+
277
+ ### Summary
278
+
279
+ OpenKBS enables building sophisticated AI systems where:
280
+ - Cloud agents provide autonomous intelligence
281
+ - Local scripts orchestrate workflows and handle infrastructure
282
+ - You maintain full control while agents think and act independently
283
+
284
+
@@ -1,84 +1,14 @@
1
- # {{{openkbsAppName}}} · [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/open-kbs/{{{openkbs.repo}}}/blob/main/LICENSE)
1
+ # {{{openkbsAppName}}} · [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
2
+
2
3
  <table>
3
4
  <tr>
4
5
  <td>
5
6
  <img src="app/icon.png" alt="App Icon" style="width: 100px; margin-right: 10px;">
6
7
  </td>
7
8
  <td>
8
- <strong>{{{openkbs.kbDescription}}}</strong>
9
+ <strong>{{{openkbsAppName}}}</strong>
9
10
  </td>
10
11
  </tr>
11
12
  </table>
12
13
 
13
- <br />
14
-
15
- <div style="display: flex; flex-direction: row;">
16
- <img src="app/screenshots/1.png" alt="Screenshot 1" style="width: 23%; margin-right: 10px;">
17
- <img src="app/screenshots/2.png" alt="Screenshot 2" style="width: 23%; margin-right: 10px;">
18
- <img src="app/screenshots/3.png" alt="Screenshot 3" style="width: 23%; margin-right: 10px;">
19
- <img src="app/screenshots/4.png" alt="Screenshot 4" style="width: 23%; margin-right: 10px;">
20
- </div>
21
-
22
- ## Installation Guide
23
-
24
- ### Step 1: Install OpenKBS CLI and Login
25
-
26
- You need to have the OpenKBS CLI installed on your system and Login:
27
-
28
- ```bash
29
- npm install -g openkbs
30
- openkbs login
31
- ```
32
-
33
- If you do not have npm installed, you can check https://github.com/open-kbs/openkbs (Download Binary)
34
-
35
- ### Step 2: Clone the Repository
36
-
37
- Clone the repository to your local machine:
38
-
39
- ```bash
40
- git clone git@github.com:open-kbs/{{{openkbs.repo}}}.git
41
- cd {{{openkbs.repo}}}
42
- ```
43
-
44
- ### Step 3: Deploy the Application to the OpenKBS Cloud (to run our backend services locally - continue reading):
45
- Deploy your application using the OpenKBS CLI:
46
-
47
- ```bash
48
- openkbs push
49
- ```
50
-
51
- Once the deployment is complete, you will receive a URL for your app: `https://{kbId}.apps.openkbs.com`.
52
- Login to your KB and have fun!
53
-
54
- ### Step 4: Running the Frontend Locally for development
55
-
56
- Run the OpenKBS UI dev server locally:
57
-
58
- ```bash
59
- npm i
60
- npm start
61
- ```
62
-
63
- ### Step 5: Running the Backend Locally
64
-
65
- Run the Chat server locally:
66
-
67
- ```bash
68
- npm run chat
69
- ```
70
-
71
- - Enter your `OPENAI_KEY` when prompted. This key will be stored at `~/.openkbs/.env`.
72
- - From OpenKBS UI change the Chat model to GPT-* On-premises models
73
-
74
- ### Step 6: Running the AI Services locally on your own GPU
75
- To run this AI app on your own GPU with Llama 3.1 and Stable Diffusion 3, read more here [Install OpenKBS AI Server](https://github.com/open-kbs/openkbs?tab=readme-ov-file#installing-openkbs-ai-server-and-integrating-llama-31-and-stable-diffusion-3-locally)
76
-
77
-
78
- ## Install via WEB
79
- To install this app via our website visit [{{{openkbsAppName}}}](https://openkbs.com/apps/{{{openkbs.slug}}}/)
80
-
81
-
82
- ## License
83
-
84
- This project is licensed under the MIT License. For more details, please refer to the [LICENSE](https://github.com/open-kbs/{{{openkbs.repo}}}/blob/main/LICENSE) file.
14
+ ## Setup and Usage
@@ -7,10 +7,8 @@
7
7
  "author": "your name",
8
8
  "license": "MIT",
9
9
  "scripts": {
10
- "postinstall": "npm install openkbs-ui@0 && npm install openkbs-chat@0 && npm install openkbs-ai-server@0 && npm install openkbs-code@0",
11
- "start": "node index.js",
12
- "chat": "cd node_modules/openkbs-chat && npm start",
13
- "code": "KB_DIR=$(pwd) && cd node_modules/openkbs-code && KB_DIR=$KB_DIR npm start"
10
+ "postinstall": "npm install openkbs-ui@0",
11
+ "start": "node index.js"
14
12
  },
15
13
  "dependencies": {
16
14
  "@emotion/react": "^11.10.6",
@@ -4,7 +4,9 @@ const OpenKBSAgentClient = require('./utils/agent_client');
4
4
 
5
5
  async function main() {
6
6
  const client = new OpenKBSAgentClient();
7
-
7
+
8
+ if (process.argv[2] === 'init') return await client.init();
9
+
8
10
  const message = `Today's Date: ${new Date().toLocaleDateString()}
9
11
 
10
12
  PROCESS_PRODUCT: