@fkws/klonk 0.0.4 → 0.0.6
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 +373 -0
- package/README.md +401 -228
- package/package.json +2 -11
- package/dist/cli.cjs +0 -132
- package/dist/cli.d.ts +0 -0
- package/dist/cli.js +0 -115
package/README.md
CHANGED
|
@@ -1,276 +1,449 @@
|
|
|
1
|
-
<picture>
|
|
2
|
-
<source media="(prefers-color-scheme: dark)" srcset=".github/assets/logo_dark_mode.png">
|
|
3
|
-
<source media="(prefers-color-scheme: light)" srcset=".github/assets/logo_bright_mode.png">
|
|
4
|
-
<img alt="Klonk Logo" src=".github/assets/logo_bright_mode.png">
|
|
5
|
-
</picture>
|
|
6
|
-
|
|
7
1
|
# Klonk
|
|
2
|
+
*A code-first, type-safe automation engine for TypeScript.*
|
|
8
3
|
|
|
9
|
-
|
|
4
|
+
## Introduction
|
|
5
|
+
Klonk is a code-first, type-safe automation engine designed with developer experience as a top priority. It provides powerful, composable primitives to build complex workflows and state machines with world-class autocomplete and type inference. If you've ever wanted to build event-driven automations or a stateful agent, but in code, with all the benefits of TypeScript, Klonk is for you.
|
|
10
6
|
|
|
11
|
-
|
|
7
|
+
The two main features are **Workflows** and **Machines**.
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
- **Workflows**: Combine triggers with a series of tasks (a `Playlist`) to automate processes. Perfect for event-driven automation, like "when a file is added to Dropbox, parse it, and create an entry in Notion."
|
|
10
|
+
- **Machines**: Create finite state machines where each state has its own `Playlist` of tasks and conditional transitions to other states. Ideal for building agents, multi-step processes, or any system with complex, stateful logic.
|
|
14
11
|
|
|
15
|
-
|
|
12
|
+
## Installation
|
|
13
|
+
```bash
|
|
14
|
+
bun add @fkws/klonk
|
|
15
|
+
# or
|
|
16
|
+
npm i @fkws/klonk
|
|
17
|
+
```
|
|
16
18
|
|
|
17
|
-
|
|
19
|
+
## Core Concepts
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
At the heart of Klonk are a few key concepts that work together.
|
|
20
22
|
|
|
21
|
-
|
|
22
|
-
.
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.addTask(new B_Task("task-b", client), (source, outputs) => ({
|
|
26
|
-
inputForB: outputs['task-a'].someProperty // Easily leverage auto-completion in your IDE
|
|
27
|
-
}))
|
|
28
|
-
);
|
|
29
|
-
```
|
|
23
|
+
### Task
|
|
24
|
+
A `Task` is the smallest unit of work. It's an abstract class with two main methods you need to implement:
|
|
25
|
+
- `validateInput(input)`: Runtime validation of the task's input (on top of strong typing).
|
|
26
|
+
- `run(input)`: Executes the task's logic.
|
|
30
27
|
|
|
31
|
-
|
|
28
|
+
Tasks use a `Railroad` return type, which is a simple way to handle success and error states without throwing exceptions. You can also use it for the rest of your application.
|
|
32
29
|
|
|
33
|
-
###
|
|
30
|
+
### Playlist
|
|
31
|
+
A `Playlist` is a sequence of `Tasks` that are executed in order. The magic of a `Playlist` is that each task has access to the outputs of all the tasks that ran before it, in a fully type-safe way. You build a `Playlist` by chaining `.addTask()` calls.
|
|
34
32
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
- Version control your workflows with Git.
|
|
38
|
-
- Write unit and integration tests.
|
|
39
|
-
- Integrate with your existing CI/CD pipelines.
|
|
33
|
+
### Trigger
|
|
34
|
+
A `Trigger` is what kicks off a `Workflow`. It's an event source. Klonk can be extended with triggers for anything: file system events, webhooks, new database entries, messages in a queue, etc.
|
|
40
35
|
|
|
41
|
-
###
|
|
36
|
+
### Workflow
|
|
37
|
+
A `Workflow` connects one or more `Triggers` to a `Playlist`. When a trigger fires an event, the workflow runs the playlist, passing the event data as the initial input. This allows you to create powerful, event-driven automations.
|
|
42
38
|
|
|
43
|
-
|
|
39
|
+
### Machine
|
|
40
|
+
A `Machine` is a finite state machine. It's made up of `StateNode`s. Each `StateNode` represents a state and has two key components:
|
|
41
|
+
1. A `Playlist` that runs when the machine enters that state.
|
|
42
|
+
2. A set of conditional `Transitions` to other states.
|
|
43
|
+
3. Retry rules for when a transition fails to resolve.
|
|
44
44
|
|
|
45
|
-
|
|
46
|
-
`@fkws-npm/klonk/tasks` and `@fkws-npm/klonk/triggers` implement powerful built-ins. Klonk provides a rich set of triggers and tasks that cover a wide range of common automation scenarios, from file system events to webhook listeners. These components are designed to be robust and ready for production use. When combined with the official integrations for popular services like Dropbox, Notion, and OpenRouter, you have all the tools you need to build versatile and powerful workflows right out of the box, without having to write custom components for every step.
|
|
45
|
+
The `Machine` carries a mutable `stateData` object that can be read from and written to by playlists and transition conditions throughout its execution.
|
|
47
46
|
|
|
48
47
|
## Features
|
|
48
|
+
- **Type-Safe & Autocompleted**: Klonk leverages TypeScript's inference to provide a world-class developer experience. The inputs and outputs of every step are strongly typed, so you'll know at compile time if your logic is sound.
|
|
49
|
+
- **Code-First**: Define your automations directly in TypeScript. No YAML, no drag-and-drop UIs. Just the full power of a real programming language.
|
|
50
|
+
- **Composable & Extensible**: The core primitives (`Task`, `Trigger`) are simple abstract classes, making it easy to create your own reusable components and integrations.
|
|
51
|
+
- **Flexible Execution**: `Machines` can be run synchronously to completion (`run`) for request/response style work, or started as a long-running background process (`start`).
|
|
49
52
|
|
|
50
|
-
|
|
51
|
-
-
|
|
52
|
-
- **Modern Integration Support**: Built-in, async-ready integrations for services like Notion, Dropbox, and OpenRouter.
|
|
53
|
-
- **AI-Powered**: Leverage powerful AI models for intelligent document and data processing right out of the box.
|
|
54
|
-
- **Code-First & Declarative**: Define workflows in pure TypeScript for maximum flexibility and clarity.
|
|
55
|
-
- **Self-Hosted**: Run on your own servers with no recurring fees.
|
|
56
|
-
|
|
57
|
-
## Installation
|
|
53
|
+
## Klonkworks: Pre-built Components
|
|
54
|
+
Coming soon(ish)! Klonkworks will be a large collection of pre-built Tasks, Triggers, and integrations. This will allow you to quickly assemble powerful automations that connect to a wide variety of services, often without needing to build your own components from scratch.
|
|
58
55
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
56
|
+
## Code Examples
|
|
57
|
+
<details>
|
|
58
|
+
<summary><b>Creating a Task</b></summary>
|
|
62
59
|
|
|
63
|
-
|
|
60
|
+
Here's how you create a custom `Task`. This task uses an AI client to perform text inference.
|
|
64
61
|
|
|
65
|
-
```
|
|
66
|
-
|
|
62
|
+
```typescript
|
|
63
|
+
import { Railroad, Task } from "@fkws/klonk";
|
|
64
|
+
import { OpenRouterClient } from "./common/OpenrouterClient"
|
|
65
|
+
import { Model } from "./common/models";
|
|
66
|
+
|
|
67
|
+
type TABasicTextInferenceInput = {
|
|
68
|
+
inputText: string;
|
|
69
|
+
instructions?: string;
|
|
70
|
+
model: Model;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type TABasicTextInferenceOutput = {
|
|
74
|
+
text: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// A Task is a generic class. You provide the Input, Output, and an Ident (a unique string literal for the task).
|
|
78
|
+
export class TABasicTextInference<IdentType extends string> extends Task<
|
|
79
|
+
TABasicTextInferenceInput, // These type parameters are part of the secret sauce typing system Klonk uses.
|
|
80
|
+
TABasicTextInferenceOutput, // Input Type, Output Type, Ident Type
|
|
81
|
+
IdentType
|
|
82
|
+
> {
|
|
83
|
+
constructor(ident: IdentType, public client: OpenRouterClient) {
|
|
84
|
+
super(ident);
|
|
85
|
+
if (!this.client) {
|
|
86
|
+
throw new Error("[TABasicTextInference] An IOpenRouter client instance is required.");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// validateInput is for runtime validation of the data your task receives.
|
|
91
|
+
async validateInput(input: TABasicTextInferenceInput): Promise<boolean> {
|
|
92
|
+
if (!input.inputText || !input.model) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The core logic of your task. It must return a Railroad type.
|
|
99
|
+
async run(input: TABasicTextInferenceInput): Promise<Railroad<TABasicTextInferenceOutput>> {
|
|
100
|
+
try {
|
|
101
|
+
const result = await this.client.basicTextInference({
|
|
102
|
+
inputText: input.inputText,
|
|
103
|
+
instructions: input.instructions,
|
|
104
|
+
model: input.model
|
|
105
|
+
});
|
|
106
|
+
// On success, return a success object with your data.
|
|
107
|
+
return {
|
|
108
|
+
success: true, // Railroad is a simple result type
|
|
109
|
+
data: {
|
|
110
|
+
text: result
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
} catch (error) {
|
|
114
|
+
// On failure, return an error object. The next Task's input builder will react to this.
|
|
115
|
+
return {
|
|
116
|
+
success: false,
|
|
117
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
67
122
|
```
|
|
123
|
+
</details>
|
|
68
124
|
|
|
69
|
-
|
|
125
|
+
<details>
|
|
126
|
+
<summary><b>Creating a Trigger</b></summary>
|
|
70
127
|
|
|
71
|
-
|
|
128
|
+
Here's an example of a custom `Trigger`. This trigger fires on a given interval and pushes the current date as its event data.
|
|
72
129
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
130
|
+
```typescript
|
|
131
|
+
import { Trigger } from '@fkws/klonk';
|
|
132
|
+
|
|
133
|
+
// A simple trigger that fires every `intervalMs` with the current date.
|
|
134
|
+
// You define the shape of the data the trigger will provide, in this case `{ now: Date }`.
|
|
135
|
+
export class IntervalTrigger<TIdent extends string> extends Trigger<TIdent, { now: Date }> {
|
|
136
|
+
private intervalId: NodeJS.Timeout | null = null;
|
|
137
|
+
|
|
138
|
+
constructor(ident: TIdent, private intervalMs: number) {
|
|
139
|
+
super(ident); // Pass the unique identifier to the parent constructor.
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The start method is called by the Workflow to begin listening for events.
|
|
143
|
+
async start(): Promise<void> {
|
|
144
|
+
if (this.intervalId) return; // Prevent multiple intervals.
|
|
145
|
+
|
|
146
|
+
this.intervalId = setInterval(() => {
|
|
147
|
+
// When an event occurs, use pushEvent to add it to the internal queue for the workflow to poll.
|
|
148
|
+
this.pushEvent({ now: new Date() });
|
|
149
|
+
}, this.intervalMs);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The stop method cleans up any resources, like intervals or open connections.
|
|
153
|
+
async stop(): Promise<void> {
|
|
154
|
+
if (this.intervalId) {
|
|
155
|
+
clearInterval(this.intervalId);
|
|
156
|
+
this.intervalId = null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
</details>
|
|
77
162
|
|
|
78
|
-
|
|
163
|
+
<details>
|
|
164
|
+
<summary><b>Building a Workflow</b></summary>
|
|
79
165
|
|
|
80
|
-
|
|
166
|
+
Workflows are perfect for event-driven automations. This example creates a workflow that triggers when a new invoice PDF is added to a Dropbox folder. It then parses the invoice and creates a new item in a Notion database.
|
|
81
167
|
|
|
82
|
-
|
|
83
|
-
import { Workflow } from '@fkws-npm/klonk';
|
|
84
|
-
import { TRDropboxFileAdded } from '@fkws-npm/klonk/triggers';
|
|
85
|
-
import { TADropboxDownloadFile, TALogToConsole } from '@fkws-npm/klonk/tasks';
|
|
86
|
-
import { IDropbox } from '@fkws-npm/klonk/integrations';
|
|
168
|
+
Notice how the `builder` function for each task (`(source, outputs) => { ... }`) has access to the initial `source` data (from the trigger) and the `outputs` of all previous tasks. Klonk automatically infers the types for `source` and `outputs`!
|
|
87
169
|
|
|
88
|
-
|
|
89
|
-
|
|
170
|
+
```typescript
|
|
171
|
+
import { z } from 'zod';
|
|
172
|
+
import { Workflow } from '@fkws/klonk';
|
|
173
|
+
|
|
174
|
+
// The following example requires a lot of tasks, integrations and a trigger.
|
|
175
|
+
// Soon, you will be able to import these from @fkws/klonkworks.
|
|
176
|
+
import { TACreateNotionDatabaseItem, TANotionGetTitlesAndIdsForDatabase, TAParsePdfAi, TADropboxDownloadFile } from '@fkws/klonkworks/tasks';
|
|
177
|
+
import { INotion, IOpenRouter, IDropbox } from '@fkws/klonkworks/integrations';
|
|
178
|
+
import { TRDropboxFileAdded } from '@fkws/klonkworks/triggers';
|
|
179
|
+
|
|
180
|
+
// Providers and clients are instantiated as usual.
|
|
181
|
+
const notionProvider = new INotion({apiKey: process.env.NOTION_API_KEY!});
|
|
182
|
+
const openrouterProvider = new IOpenRouter({apiKey: process.env.OPENROUTER_API_KEY!});
|
|
183
|
+
const dropboxProvider = new IDropbox({
|
|
90
184
|
appKey: process.env.DROPBOX_APP_KEY!,
|
|
91
185
|
appSecret: process.env.DROPBOX_APP_SECRET!,
|
|
92
|
-
refreshToken: process.env.
|
|
186
|
+
refreshToken: process.env.DROPBOX_REFRESH_KEY!
|
|
93
187
|
});
|
|
94
188
|
|
|
95
|
-
//
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
folderPath: "/MyKlonkFiles"
|
|
189
|
+
// Start building a workflow.
|
|
190
|
+
const workflow = Workflow.create().addTrigger(
|
|
191
|
+
// A workflow is initiated by one or more triggers.
|
|
192
|
+
new TRDropboxFileAdded("dropbox-trigger", {
|
|
193
|
+
client: dropboxProvider,
|
|
194
|
+
folderPath: process.env.DROPBOX_INVOICES_FOLDER_PATH ?? "",
|
|
102
195
|
})
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
196
|
+
).setPlaylist(p => p // Builder function allows complex types to be assembled!
|
|
197
|
+
.addTask( // .addTask() adds a task to the playlist.
|
|
198
|
+
new TANotionGetTitlesAndIdsForDatabase("get-payees", notionProvider),
|
|
199
|
+
// The second argument to addTask builds the input for that task.
|
|
200
|
+
// `source` is the data from the trigger, `outputs` contains all previous task outputs.
|
|
201
|
+
(source, outputs) => {
|
|
202
|
+
return { database_id: process.env.NOTION_PAYEES_DATABASE_ID!}
|
|
203
|
+
}
|
|
204
|
+
).addTask(
|
|
205
|
+
new TANotionGetTitlesAndIdsForDatabase("get-expense-types", notionProvider),
|
|
206
|
+
(source, outputs) => { // Type inference works for source and outputs!
|
|
207
|
+
return { database_id: process.env.NOTION_EXPENSE_TYPES_DATABASE_ID!}
|
|
208
|
+
}
|
|
209
|
+
).addTask(
|
|
210
|
+
new TADropboxDownloadFile("download-invoice-pdf", dropboxProvider),
|
|
211
|
+
(source, outputs) => {
|
|
212
|
+
// The `source` object contains the trigger ident, so you can handle multiple triggers.
|
|
213
|
+
if (source.triggerIdent == "dropbox-trigger") {
|
|
214
|
+
return { file_metadata: source.data}
|
|
215
|
+
} else {
|
|
216
|
+
throw new Error(`Trigger ${source.triggerIdent} is not implemented for task download-invoice-pdf.`)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
).addTask(
|
|
220
|
+
new TAParsePdfAi("parse-invoice", openrouterProvider),
|
|
221
|
+
(source, outputs) => {
|
|
222
|
+
// Access the outputs of previous tasks via the `outputs` object.
|
|
223
|
+
// The keys are the idents you provided to the tasks.
|
|
224
|
+
const downloadResult = outputs['download-invoice-pdf'];
|
|
225
|
+
if (!downloadResult.success) {
|
|
226
|
+
throw downloadResult.error ?? new Error('Failed to download invoice PDF');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const payeesResult = outputs['get-payees'];
|
|
230
|
+
if (!payeesResult.success) {
|
|
231
|
+
throw payeesResult.error ?? new Error('Failed to load payees');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const expenseTypesResult = outputs['get-expense-types'];
|
|
235
|
+
if (!expenseTypesResult.success) {
|
|
236
|
+
throw expenseTypesResult.error ?? new Error('Failed to load expense types');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const payees = payeesResult.data;
|
|
240
|
+
const expenseTypes = expenseTypesResult.data;
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
pdf: downloadResult.data.file,
|
|
244
|
+
instructions: "Extract data from the invoice",
|
|
245
|
+
schema: z.object({
|
|
246
|
+
payee: z.enum(payees.map(p => p.id) as [string, ...string[]])
|
|
247
|
+
.describe("The payee id of the invoice according to this map: " + JSON.stringify(payees, null, 2)),
|
|
248
|
+
total: z.number()
|
|
249
|
+
.describe("The total amount of the invoice."),
|
|
250
|
+
invoice_date: z.string()
|
|
251
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
252
|
+
.describe("The date of the invoice as an ISO 8601 string (YYYY-MM-DD)."),
|
|
253
|
+
expense_type: z.enum(expenseTypes.map(e => e.id) as [string, ...string[]])
|
|
254
|
+
.describe("The expense type id of the invoice according to this map: " + JSON.stringify(expenseTypes, null, 2))
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
).addTask(
|
|
259
|
+
new TACreateNotionDatabaseItem("create-notion-invoice", notionProvider),
|
|
260
|
+
(source, outputs) => {
|
|
261
|
+
const invoiceResult = outputs['parse-invoice'];
|
|
262
|
+
if (!invoiceResult.success) {
|
|
263
|
+
throw invoiceResult.error ?? new Error('Failed to parse invoice');
|
|
264
|
+
}
|
|
265
|
+
const invoiceData = invoiceResult.data;
|
|
266
|
+
const properties = {
|
|
267
|
+
'Name': { 'title': [{ 'text': { 'content': 'Invoice' } }] },
|
|
268
|
+
'Payee': { 'relation': [{ 'id': invoiceData.payee }] },
|
|
269
|
+
'Total': { 'number': invoiceData.total },
|
|
270
|
+
'Invoice Date': { 'date': { 'start': invoiceData.invoice_date } },
|
|
271
|
+
'Expense Type': { 'relation': [{ 'id': invoiceData.expense_type }] }
|
|
272
|
+
};
|
|
273
|
+
return {
|
|
274
|
+
database_id: process.env.NOTION_INVOICES_DATABASE_ID!,
|
|
275
|
+
properties: properties
|
|
276
|
+
}
|
|
277
|
+
}
|
|
122
278
|
)
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
//
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
```typescript
|
|
139
|
-
import { Workflow } from '@fkws-npm/klonk';
|
|
140
|
-
import { z } from 'zod';
|
|
141
|
-
import { TRDropboxFileAdded } from '@fkws-npm/klonk/triggers';
|
|
142
|
-
import {
|
|
143
|
-
TADropboxDownloadFile,
|
|
144
|
-
TAParsePdfAi,
|
|
145
|
-
TACreateNotionDatabaseItem
|
|
146
|
-
} from '@fkws-npm/klonk/tasks';
|
|
147
|
-
import { IDropbox, IOpenRouter, INotion } from '@fkws-npm/klonk/integrations';
|
|
148
|
-
|
|
149
|
-
// --- Client & Schema Setup ---
|
|
150
|
-
const dropbox = new IDropbox({ /* ... */ });
|
|
151
|
-
const openRouter = new IOpenRouter({ apiKeyEnvVar: "OPENROUTER_API_KEY" });
|
|
152
|
-
const notion = new INotion({ apiKeyEnvVar: "NOTION_API_KEY" });
|
|
153
|
-
|
|
154
|
-
const InvoiceSchema = z.object({
|
|
155
|
-
invoice_number: z.string(),
|
|
156
|
-
total_amount: z.number(),
|
|
157
|
-
is_paid: z.boolean(),
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
// Run the workflow
|
|
282
|
+
console.log('[WCreateNotionInvoiceFromFile] Starting workflow...');
|
|
283
|
+
// .start() begins the workflow's trigger polling loop.
|
|
284
|
+
workflow.start({
|
|
285
|
+
// The callback is executed every time the playlist successfully completes.
|
|
286
|
+
callback: (source, outputs) => {
|
|
287
|
+
console.log('[WCreateNotionInvoiceFromFile] Workflow completed');
|
|
288
|
+
console.dir({
|
|
289
|
+
source,
|
|
290
|
+
outputs
|
|
291
|
+
}, { depth: null });
|
|
292
|
+
}
|
|
158
293
|
});
|
|
159
|
-
|
|
160
|
-
// --- Workflow Definition ---
|
|
161
|
-
const invoiceWorkflow = Workflow.create()
|
|
162
|
-
.addTrigger(new TRDropboxFileAdded("new-invoice", { client: dropbox, folderPath: "/Invoices" }))
|
|
163
|
-
.setPlaylist(p => p
|
|
164
|
-
// Step 1: Download the file from Dropbox
|
|
165
|
-
.addTask(new TADropboxDownloadFile("download-pdf", dropbox),
|
|
166
|
-
(source, outputs) => ({
|
|
167
|
-
file_metadata: source.data
|
|
168
|
-
})
|
|
169
|
-
)
|
|
170
|
-
// Step 2: Use AI to parse the downloaded PDF
|
|
171
|
-
.addTask(new TAParsePdfAi("parse-with-ai", openRouter),
|
|
172
|
-
(source, outputs) => ({
|
|
173
|
-
pdf: outputs['download-pdf'].file, // Type-safe access to previous output by its ID
|
|
174
|
-
instructions: "Extract the invoice number, total amount, and payment status from the PDF.",
|
|
175
|
-
zodSchema: InvoiceSchema,
|
|
176
|
-
})
|
|
177
|
-
)
|
|
178
|
-
// Step 3: Create a new item in a Notion database
|
|
179
|
-
.addTask(new TACreateNotionDatabaseItem("create-notion-record", notion),
|
|
180
|
-
(source, outputs) => {
|
|
181
|
-
const invoiceData = outputs['parse-with-ai']; // Type-safe access to the parsed data
|
|
182
|
-
return {
|
|
183
|
-
database_id: 'YOUR_INVOICES_DATABASE_ID',
|
|
184
|
-
properties: {
|
|
185
|
-
'Invoice Number': { title: [{ text: { content: invoiceData.invoice_number } }] },
|
|
186
|
-
'Total': { number: invoiceData.total_amount },
|
|
187
|
-
'Status': { select: { name: invoiceData.is_paid ? "Paid" : "Unpaid" } }
|
|
188
|
-
}
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
)
|
|
192
|
-
);
|
|
193
|
-
|
|
194
|
-
// --- Start the workflow ---
|
|
195
|
-
invoiceWorkflow.start();
|
|
196
294
|
```
|
|
295
|
+
</details>
|
|
197
296
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
If your use case can't be served with Klonk's built-ins, you can easily extend Klonk by implementing the `Task` and `Trigger` abstract classes.
|
|
297
|
+
<details>
|
|
298
|
+
<summary><b>Building a Machine</b></summary>
|
|
201
299
|
|
|
202
|
-
|
|
300
|
+
`Machines` are ideal for building complex, stateful agents. This example shows a simple AI agent that takes a user's query, refines it, performs a web search, and then generates a final response.
|
|
203
301
|
|
|
204
|
-
|
|
302
|
+
The `Machine` manages a `StateData` object. Each `StateNode`'s `Playlist` can modify this state, and the `Transitions` between states can use it to decide which state to move to next.
|
|
205
303
|
|
|
206
304
|
```typescript
|
|
207
|
-
import {
|
|
208
|
-
import
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
305
|
+
import { Machine, StateNode } from "@fkws/klonk"
|
|
306
|
+
import { OpenRouterClient } from "./tasks/common/OpenrouterClient"
|
|
307
|
+
import { Model } from "./tasks/common/models"
|
|
308
|
+
import { TABasicTextInference } from "./tasks/TABasicTextInference"
|
|
309
|
+
import { TASearchOnline } from "./tasks/TASearchOnline"
|
|
310
|
+
|
|
311
|
+
type StateData = {
|
|
312
|
+
input: string;
|
|
313
|
+
output?: string;
|
|
314
|
+
model?: Model;
|
|
315
|
+
refinedInput?: string;
|
|
316
|
+
searchTerm?: string;
|
|
317
|
+
searchResults?: {
|
|
318
|
+
results: {
|
|
319
|
+
url: string;
|
|
320
|
+
title: string;
|
|
321
|
+
content: string;
|
|
322
|
+
raw_content?: string | undefined;
|
|
323
|
+
score: string;
|
|
324
|
+
}[];
|
|
325
|
+
query: string;
|
|
326
|
+
answer?: string | undefined;
|
|
327
|
+
images?: string[] | undefined;
|
|
328
|
+
follow_up_questions?: string[] | undefined;
|
|
329
|
+
response_time: string;
|
|
330
|
+
},
|
|
331
|
+
finalResponse?: string;
|
|
234
332
|
}
|
|
235
|
-
```
|
|
236
333
|
|
|
237
|
-
|
|
334
|
+
const client = new OpenRouterClient(process.env.OPENROUTER_API_KEY!)
|
|
335
|
+
|
|
336
|
+
const webSearchAgent = Machine
|
|
337
|
+
.create<StateData>()
|
|
338
|
+
.addState(StateNode
|
|
339
|
+
.create<StateData>()
|
|
340
|
+
.setIdent("refine_and_extract")
|
|
341
|
+
.setPlaylist(p => p // Builder function allows complex types to be assembled!
|
|
342
|
+
.addTask(new TABasicTextInference("refine", client),
|
|
343
|
+
(state, outputs) => { // This function constructs the INPUT of the task from the state and outputs of previous tasks
|
|
344
|
+
const input = state.input;
|
|
345
|
+
const model = state.model ? state.model : "openai/gpt-5"
|
|
346
|
+
const instructions = `You are a prompt refiner. Any prompts you receive, you will refine to improve LLM performance. Break down the prompt by Intent, Mood, and Instructions. Do NOT reply or answer the user's message! ONLY refine the prompt.`;
|
|
347
|
+
return {
|
|
348
|
+
inputText: input,
|
|
349
|
+
model: model,
|
|
350
|
+
instructions: instructions
|
|
351
|
+
}
|
|
352
|
+
})
|
|
353
|
+
.addTask(new TABasicTextInference("extract_search_terms", client),
|
|
354
|
+
(state, outputs) => {
|
|
355
|
+
const input = `Original request: ${state.input}\n\nRefined prompt: ${state.refinedInput}`;
|
|
356
|
+
const model = state.model ? state.model : "openai/gpt-5"
|
|
357
|
+
const instructions = `You will receive the original user request AND an LLM refined version of the prompt. Please use both to extract one short web search query that will retrieve useful results.`;
|
|
358
|
+
return {
|
|
359
|
+
inputText: input,
|
|
360
|
+
model: model,
|
|
361
|
+
instructions: instructions
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
.finally((state, outputs) => { // The finally block allows the playlist to react to the last task and to modify state data before the run ends.
|
|
365
|
+
if (outputs.refine.success) {
|
|
366
|
+
state.refinedInput = outputs.refine.data.text
|
|
367
|
+
} else {
|
|
368
|
+
state.refinedInput = "Sorry, an error occurred: " + outputs.refine.error
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (outputs.extract_search_terms.success) {
|
|
372
|
+
state.searchTerm = outputs.extract_search_terms.data.text
|
|
373
|
+
}
|
|
374
|
+
}))
|
|
375
|
+
.retryLimit(3) // Simple retry rule setters. Also includes .preventRetry() to disable retries entirely and .retryDelayMs(delayMs) to set the delay between retries. Default is infinite retries at 1000ms delay.
|
|
376
|
+
.addTransition({
|
|
377
|
+
to: "search_web", // Transitions refer to states by their ident.
|
|
378
|
+
condition: async (stateData: StateData) => stateData.searchTerm ? true : false,
|
|
379
|
+
weight: 2 // Weight determines the order in which transitions are tried. Higher weight = higher priority.
|
|
380
|
+
})
|
|
381
|
+
.addTransition({
|
|
382
|
+
to: "generate_response",
|
|
383
|
+
condition: async (stateData: StateData) => true,
|
|
384
|
+
weight: 1
|
|
385
|
+
}),
|
|
386
|
+
{ initial: true } // The machine needs an initial state.
|
|
387
|
+
)
|
|
388
|
+
.addState(StateNode.create<StateData>()
|
|
389
|
+
.setIdent("search_web")
|
|
390
|
+
.setPlaylist(p => p
|
|
391
|
+
.addTask(new TASearchOnline("search"),
|
|
392
|
+
(state, outputs) => {
|
|
393
|
+
return {
|
|
394
|
+
query: state.searchTerm! // We are sure that the searchTerm is not undefined because of the transition condition.
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
.finally((state, outputs) => {
|
|
398
|
+
if(outputs.search.success) {
|
|
399
|
+
state.searchResults = outputs.search.data
|
|
400
|
+
}
|
|
401
|
+
}))
|
|
402
|
+
.addTransition({
|
|
403
|
+
to: "generate_response",
|
|
404
|
+
condition: async (stateData: StateData) => true,
|
|
405
|
+
weight: 1
|
|
406
|
+
})
|
|
407
|
+
)
|
|
408
|
+
.addState(StateNode.create<StateData>()
|
|
409
|
+
.setIdent("generate_response")
|
|
410
|
+
.setPlaylist(p => p
|
|
411
|
+
.addTask(new TABasicTextInference("generate_response", client),
|
|
412
|
+
(state, outputs) => {
|
|
413
|
+
return {
|
|
414
|
+
inputText: state.input,
|
|
415
|
+
model: state.model ? state.model : "openai/gpt-5",
|
|
416
|
+
instructions: "You will receive a user request and a refined prompt. There may also be search results. Based on the information, please write a professional response to the user's request."
|
|
417
|
+
}
|
|
418
|
+
})
|
|
419
|
+
.finally((state, outputs) => {
|
|
420
|
+
if(outputs.generate_response.success) {
|
|
421
|
+
state.finalResponse = outputs.generate_response.data.text
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
state.finalResponse = "Sorry, an error occurred: " + outputs.generate_response.error
|
|
425
|
+
}
|
|
426
|
+
})
|
|
427
|
+
))
|
|
428
|
+
.finalize({ // Finalize your machine to make it ready to run. Verbose machines emit JSON logs. If you don't provide an ident, a uuidv4 will be generated for it.
|
|
429
|
+
verbose: true,
|
|
430
|
+
ident: "web-search-agent"
|
|
431
|
+
})
|
|
238
432
|
|
|
239
|
-
|
|
433
|
+
// ------------- EXECUTION: -------------
|
|
240
434
|
|
|
241
|
-
|
|
242
|
-
|
|
435
|
+
const state: StateData = { // The state object is mutable and is passed to the machine and playlists.
|
|
436
|
+
input: "How do I update AMD graphic driver?",
|
|
437
|
+
model: "openai/gpt-4o-mini"
|
|
438
|
+
}
|
|
243
439
|
|
|
244
|
-
//
|
|
245
|
-
|
|
440
|
+
// The .run() method executes the machine until it reaches a terminal state
|
|
441
|
+
// (leaf, failed, out of retries, looped back to initial state)
|
|
442
|
+
// and returns the final state. The original state object is also mutated.
|
|
443
|
+
const finalState = await webSearchAgent.run(state)
|
|
246
444
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
TriggerEvent<IdentType, NewUserEventData>
|
|
251
|
-
> {
|
|
252
|
-
constructor(ident: IdentType) {
|
|
253
|
-
super(ident);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// 3. The `start` method is called by the workflow to begin polling
|
|
257
|
-
async start(): Promise<void> {
|
|
258
|
-
// Example: check for new users every 10 seconds
|
|
259
|
-
setInterval(async () => {
|
|
260
|
-
const newUser = await this.checkForNewUserInDb();
|
|
261
|
-
if (newUser) {
|
|
262
|
-
// 4. Add new events to the `this.queue` property
|
|
263
|
-
this.queue.push({
|
|
264
|
-
triggerIdent: this.ident,
|
|
265
|
-
data: newUser
|
|
266
|
-
});
|
|
267
|
-
}
|
|
268
|
-
}, 10000);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private async checkForNewUserInDb(): Promise<NewUserEventData | null> {
|
|
272
|
-
// Your database logic here...
|
|
273
|
-
return null;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
445
|
+
console.log(finalState.finalResponse) // The final state is returned.
|
|
446
|
+
// Or simply:
|
|
447
|
+
console.log(state.finalResponse) // original state object is also mutated.
|
|
276
448
|
```
|
|
449
|
+
</details>
|