ai-workflows 0.0.2 → 1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AI Primitives
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,18 +1,45 @@
1
+ [![npm version](https://badge.fury.io/js/ai-workflows.svg)](https://badge.fury.io/js/ai-workflows)
2
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+
1
4
  # ai-workflows
2
5
 
6
+ Composable AI Workflows & Durable Execution Framework
7
+
8
+ ## Overview
9
+
10
+ ai-workflows is a powerful framework for building event-driven, AI-powered workflows with durable execution guarantees. It provides both a JavaScript API and MDX-based workflow definitions for maximum flexibility.
11
+
12
+ ## Features
13
+
14
+ - 🎯 **Event-Driven Architecture** - Build reactive workflows that respond to external events
15
+ - 🤖 **AI Functions** - Built-in MDX-based AI functions structured data generation and processing
16
+ - ⏰ **Smart Scheduling** - Schedule tasks with natural language time expressions
17
+ - 📝 **Workflow Definitions** - Design workflows by composing AI functions and events
18
+ - 💪 **Durable Execution** - Reliable workflow execution with state persistence
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install ai-workflows
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ### JavaScript API
29
+
3
30
  ```javascript
4
31
  import { ai, Workflow } from 'ai-workflows'
5
32
 
6
33
  const workflow = Workflow()
7
34
 
8
- workflow.on('ticket.created', ticket => {
35
+ workflow.on('ticket.created', (ticket) => {
9
36
  const summary = ai.summarize(ticket)
10
37
  workflow.send('ticket.summarized', summary)
11
38
  })
12
39
 
13
- workflow.on('ticket.summarized', summary => ai.sentiment(summary).then('update.ticket'))
40
+ workflow.on('ticket.summarized', (summary) => ai.sentiment(summary).then('update.ticket'))
14
41
 
15
- workflow.every('30 minutes during business hours', context => ai.reviewKPIs(context).then('slack.post'))
42
+ workflow.every('30 minutes during business hours', (context) => ai.reviewKPIs(context).then('slack.post'))
16
43
 
17
44
  export default workflow
18
- ```
45
+ ```
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ import { readFileSync, writeFileSync, readdirSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, resolve } from 'node:path';
4
+ import matter from 'gray-matter';
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+ const aiDir = resolve(process.cwd(), 'ai');
8
+ const outputFile = resolve(process.cwd(), 'src/ai-types.d.ts');
9
+ /**
10
+ * Converts an MDX output type definition to a TypeScript type
11
+ * Handles enum types (separated by |) and string types
12
+ */
13
+ function convertOutputTypeToTS(type) {
14
+ if (type.includes('|')) {
15
+ // Handle enum types (e.g., "Article | BlogPosting | Thing")
16
+ return type.split('|').map(t => `'${t.trim()}'`).join(' | ');
17
+ }
18
+ return 'string';
19
+ }
20
+ /**
21
+ * Generates TypeScript type definitions from MDX files
22
+ */
23
+ function generateTypes() {
24
+ const mdxFiles = readdirSync(aiDir).filter(file => file.endsWith('.mdx'));
25
+ let typeDefinitions = `// Generated TypeScript definitions for AI methods
26
+ // DO NOT EDIT DIRECTLY - Generated from MDX files in ai/
27
+
28
+ declare const ai: {
29
+ `;
30
+ for (const file of mdxFiles) {
31
+ const methodName = file.replace('.mdx', '');
32
+ const content = readFileSync(resolve(aiDir, file), 'utf-8');
33
+ const { data: frontmatter } = matter(content);
34
+ if (!frontmatter.output?.type) {
35
+ console.warn(`Warning: ${file} is missing output type definition`);
36
+ continue;
37
+ }
38
+ const tsType = convertOutputTypeToTS(frontmatter.output.type);
39
+ const description = frontmatter.output.description || 'No description provided';
40
+ typeDefinitions += ` /**
41
+ * ${description}
42
+ * @param input The input data for the AI operation
43
+ * @returns A promise that resolves to the generated output
44
+ */
45
+ ${methodName}(input: unknown): Promise<${tsType}>;
46
+
47
+ `;
48
+ }
49
+ typeDefinitions += `}
50
+
51
+ export { ai }
52
+ `;
53
+ writeFileSync(outputFile, typeDefinitions);
54
+ console.log(`Generated type definitions at ${outputFile}`);
55
+ }
56
+ // Run the generator
57
+ generateTypes();
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The ai object is a Proxy that dynamically loads MDX files for each method call
3
+ * Example: ai.summarize(ticket) will load ai/summarize.mdx and use its configuration
4
+ */
5
+ export declare const ai: {};
@@ -0,0 +1,94 @@
1
+ import { readFileSync, existsSync } from 'fs';
2
+ import path from 'path';
3
+ import matter from 'gray-matter';
4
+ import { z } from 'zod';
5
+ import { OpenAI } from 'openai';
6
+ const aiBasePath = path.resolve(process.cwd(), 'ai');
7
+ const openai = new OpenAI({
8
+ apiKey: process.env.OPENAI_API_KEY
9
+ });
10
+ // Schema for required MDX frontmatter
11
+ const frontmatterSchema = z.object({
12
+ model: z.string(),
13
+ system: z.string(),
14
+ output: z.object({
15
+ type: z.string(),
16
+ description: z.string()
17
+ })
18
+ });
19
+ /**
20
+ * Creates a Zod schema from an output definition in MDX frontmatter
21
+ * Handles enum types (separated by |) and string types with descriptions
22
+ * @param outputDef - The output definition from MDX frontmatter
23
+ * @returns A Zod schema for validating the output
24
+ */
25
+ function createZodSchemaFromOutput(outputDef) {
26
+ const { type, description } = outputDef;
27
+ // Create schema based on output type
28
+ const schema = type.includes('|')
29
+ ? z.object({
30
+ type: z.enum(type.split('|').map(t => t.trim())),
31
+ description: z.string()
32
+ })
33
+ : z.object({
34
+ type: z.string(),
35
+ description: z.string()
36
+ });
37
+ return schema.describe(description);
38
+ }
39
+ /**
40
+ * The ai object is a Proxy that dynamically loads MDX files for each method call
41
+ * Example: ai.summarize(ticket) will load ai/summarize.mdx and use its configuration
42
+ */
43
+ export const ai = new Proxy({}, {
44
+ get(_target, methodName) {
45
+ return async (input) => {
46
+ try {
47
+ // Check if MDX file exists
48
+ const mdxFile = path.join(aiBasePath, `${methodName}.mdx`);
49
+ if (!existsSync(mdxFile)) {
50
+ throw new Error(`No MDX file found for ai.${methodName}(). Create ${methodName}.mdx in the ai/ directory.`);
51
+ }
52
+ // Load and parse the MDX file
53
+ const fileContent = readFileSync(mdxFile, 'utf-8');
54
+ const { data: rawFrontmatter, content } = matter(fileContent);
55
+ // Validate frontmatter against schema
56
+ const frontmatter = frontmatterSchema.parse(rawFrontmatter);
57
+ // Create Zod schema from output definition
58
+ const outputSchema = createZodSchemaFromOutput(frontmatter.output);
59
+ // Generate response using OpenAI
60
+ const completion = await openai.chat.completions.create({
61
+ model: frontmatter.model,
62
+ messages: [
63
+ { role: 'system', content: frontmatter.system },
64
+ { role: 'user', content: `${content}\n\nInput: ${JSON.stringify(input, null, 2)}` }
65
+ ],
66
+ response_format: { type: 'json_object' },
67
+ temperature: 0.7, // Add some creativity while maintaining structure
68
+ });
69
+ // Parse and validate the response
70
+ let result;
71
+ try {
72
+ result = JSON.parse(completion.choices[0].message.content || '{}');
73
+ }
74
+ catch (error) {
75
+ // Narrow error type for proper handling
76
+ const parseError = error;
77
+ throw new Error(`Failed to parse OpenAI response as JSON: ${parseError.message}`);
78
+ }
79
+ // Validate against our schema and return
80
+ return outputSchema.parse(result);
81
+ }
82
+ catch (error) {
83
+ // Enhance error messages for different types of failures
84
+ if (error instanceof z.ZodError) {
85
+ throw new Error(`Schema validation failed in ai.${methodName}(): ${error.errors.map(e => e.message).join(', ')}`);
86
+ }
87
+ else if (error instanceof Error) {
88
+ throw new Error(`Error in ai.${methodName}(): ${error.message}`);
89
+ }
90
+ throw error;
91
+ }
92
+ };
93
+ }
94
+ });
@@ -0,0 +1,9 @@
1
+ import { ai } from './ai-proxy.js';
2
+ export { ai };
3
+ /**
4
+ * A placeholder function that adds two numbers
5
+ * @param a First number
6
+ * @param b Second number
7
+ * @returns The sum of a and b
8
+ */
9
+ export declare function add(a: number, b: number): number;
@@ -0,0 +1,11 @@
1
+ import { ai } from './ai-proxy.js';
2
+ export { ai };
3
+ /**
4
+ * A placeholder function that adds two numbers
5
+ * @param a First number
6
+ * @param b Second number
7
+ * @returns The sum of a and b
8
+ */
9
+ export function add(a, b) {
10
+ return a + b;
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
1
+ import { describe, it, expect, beforeAll } from '@jest/globals';
2
+ import { add, ai } from './index.js';
3
+ import { mkdir, writeFile } from 'fs/promises';
4
+ import path from 'path';
5
+ describe('add', () => {
6
+ it('should add two numbers correctly', () => {
7
+ expect(add(2, 3)).toBe(5);
8
+ expect(add(-1, 1)).toBe(0);
9
+ expect(add(0, 0)).toBe(0);
10
+ });
11
+ });
12
+ describe('ai', () => {
13
+ beforeAll(async () => {
14
+ // Create ai directory and test MDX file
15
+ await mkdir(path.resolve(process.cwd(), 'ai'), { recursive: true });
16
+ await writeFile(path.resolve(process.cwd(), 'ai/test.mdx'), `---
17
+ model: gpt-3.5-turbo
18
+ system: Test system prompt
19
+ output:
20
+ type: Article | BlogPosting
21
+ description: Test description
22
+ ---
23
+
24
+ # Test MDX
25
+
26
+ Test content`);
27
+ });
28
+ it('should handle AI method calls correctly', async () => {
29
+ const result = await ai.test({ input: 'test' });
30
+ expect(result).toEqual({
31
+ type: 'Article',
32
+ description: 'Test description'
33
+ });
34
+ });
35
+ });
package/package.json CHANGED
@@ -1,42 +1,83 @@
1
1
  {
2
2
  "name": "ai-workflows",
3
- "version": "0.0.2",
4
- "description": "Framework for Developing AI-Native Workflows",
3
+ "type": "module",
4
+ "version": "1.1.0",
5
+ "description": "Composable AI Workflows & Durable Execution Framework",
6
+ "main": "dist/index.js",
5
7
  "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "bin": {
10
+ "ai-workflows": "bin/cli.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "bin"
15
+ ],
6
16
  "scripts": {
7
- "build": "tsc",
8
- "format": "prettier --write .",
9
- "test": "dotenv -- vitest --globals"
17
+ "build": "tsc && NODE_OPTIONS=\"--experimental-specifier-resolution=node --loader ts-node/esm\" ts-node scripts/generate-types.ts",
18
+ "test": "jest",
19
+ "test:watch": "jest --watch",
20
+ "lint": "eslint src",
21
+ "format": "prettier --write \"src/**/*.{ts,tsx,js,jsx}\" \"*.{md,mdx}\"",
22
+ "prepublishOnly": "pnpm run build",
23
+ "generate-types": "NODE_OPTIONS=\"--experimental-specifier-resolution=node --loader ts-node/esm\" ts-node scripts/generate-types.ts"
10
24
  },
25
+ "keywords": [
26
+ "ai",
27
+ "workflows",
28
+ "mdx",
29
+ "durable-execution"
30
+ ],
31
+ "author": "AI Primitives",
32
+ "license": "MIT",
33
+ "homepage": "https://mdx.org.ai",
11
34
  "repository": {
12
35
  "type": "git",
13
- "url": "git+https://github.com/nathanclevenger/ai-workflows.git"
36
+ "url": "git+https://github.com/ai-primitives/ai-workflows.git"
14
37
  },
15
- "keywords": [],
16
- "author": "Nathan Clevenger",
17
- "license": "MIT",
18
38
  "bugs": {
19
- "url": "https://github.com/nathanclevenger/ai-workflows/issues"
39
+ "url": "https://github.com/ai-primitives/ai-workflows/issues"
20
40
  },
21
- "homepage": "https://github.com/nathanclevenger/ai-workflows#readme",
22
41
  "devDependencies": {
23
- "@cloudflare/workers-types": "^4.20241018.0",
24
- "typescript": "^5.6.3",
25
- "vitest": "^2.1.3"
42
+ "@babel/core": "^7.26.0",
43
+ "@babel/preset-env": "^7.26.0",
44
+ "@eslint/js": "^9.17.0",
45
+ "@jest/globals": "^29.7.0",
46
+ "@semantic-release/commit-analyzer": "^13.0.0",
47
+ "@semantic-release/github": "^11.0.1",
48
+ "@semantic-release/npm": "^12.0.1",
49
+ "@semantic-release/release-notes-generator": "^14.0.1",
50
+ "@swc/core": "^1.10.1",
51
+ "@testing-library/jest-dom": "^6.4.2",
52
+ "@testing-library/react": "^16.1.0",
53
+ "@types/jest": "^29.5.14",
54
+ "@types/js-yaml": "^4.0.9",
55
+ "@types/node": "^22.10.2",
56
+ "@types/react": "^18.3.17",
57
+ "@types/react-dom": "^18.2.0",
58
+ "@typescript-eslint/eslint-plugin": "^8.18.0",
59
+ "@typescript-eslint/parser": "^8.18.0",
60
+ "babel-jest": "^29.7.0",
61
+ "eslint": "^9.17.0",
62
+ "identity-obj-proxy": "^3.0.0",
63
+ "jest": "^29.7.0",
64
+ "jest-environment-jsdom": "^29.7.0",
65
+ "prettier": "^3.4.2",
66
+ "semantic-release": "^24.2.0",
67
+ "ts-jest": "^29.2.5",
68
+ "ts-node": "^10.9.2",
69
+ "typescript": "^5.7.2"
26
70
  },
27
71
  "dependencies": {
28
- "ai": "^3.4.18",
72
+ "@ai-sdk/openai": "^1.0.8",
73
+ "ai": "^4.0.18",
29
74
  "ai-functions": "^0.2.19",
30
- "autoevals": "^0.0.99",
31
- "braintrust": "^0.0.166",
32
- "itty-router": "^5.0.18",
33
- "openai": "^4.68.1"
34
- },
35
- "prettier": {
36
- "semi": false,
37
- "singleQuote": true,
38
- "trailingComma": "es5",
39
- "tabWidth": 2,
40
- "printWidth": 120
75
+ "gray-matter": "^4.0.3",
76
+ "mdxld": "^0.1.1",
77
+ "openai": "^4.77.0",
78
+ "react": "^18.3.1",
79
+ "react-dom": "^18.2.0",
80
+ "yaml": "^2.6.1",
81
+ "zod": "^3.24.1"
41
82
  }
42
- }
83
+ }
package/bun.lockb DELETED
Binary file
package/index.test.ts DELETED
@@ -1,9 +0,0 @@
1
- import { describe, it } from 'vitest'
2
-
3
- // An entry will be shown in the report for this suite
4
- describe.todo('unimplemented suite')
5
-
6
- // An entry will be shown in the report for this test
7
- describe('suite', () => {
8
- it.todo('unimplemented test')
9
- })
package/index.ts DELETED
@@ -1,81 +0,0 @@
1
- import { AI } from 'ai-functions'
2
- import { AutoRouter } from 'itty-router'
3
-
4
- export const ai: Record<string, any> = {}
5
-
6
- export type WorkflowOptions = {
7
- queue?: string
8
- dql?: string
9
- }
10
-
11
- // export let send: (event: string | WorkflowEvent) => Promise<any>
12
-
13
- // TODO: Add generic type for the event data
14
- export const Workflow = (options: WorkflowOptions) => {
15
-
16
-
17
- const { queue = 'workflows' } = options
18
-
19
- const api = AutoRouter()
20
-
21
- const events: Record<string, any> = {}
22
-
23
- const send = (env: any) => async (event: string | WorkflowEvent) => {
24
- if (env[queue] && env[queue].send) {
25
- if (typeof event === 'string') {
26
- return (data: any) => (env[queue] as Queue<WorkflowEvent>).send({ event, data })
27
- }
28
- return await (env[queue] as Queue<WorkflowEvent>).send(event)
29
- }
30
- throw new Error('Queue not found')
31
- }
32
-
33
- return {
34
- on: (event: string, handler: WorkflowEventHandler) => {
35
- events[event] = handler
36
- api.get('/' + event, async (req, env, ctx) => {
37
- const data = Object.fromEntries(new URL(req.url).searchParams)
38
- return send(env)({ event, data })
39
- })
40
- api.post('/' + event, async (req, env, ctx) => {
41
- const data = await req.json()
42
- return send(env)({ event, data })
43
- })
44
- },
45
- fetch: api.fetch,
46
- queue: (batch: MessageBatch<WorkflowEvent>, env: any, ctx: ExecutionContext) => {
47
- batch.messages.map(async (message) => {
48
- const { event, data } = message.body
49
- if (events[event]) {
50
- try {
51
- const results = await events[event](message.body, { ai, db: env.db, api: env.api, data, message, send: send(env) })
52
- console.log(results)
53
- message.ack()
54
- // TODO: Try to support `workflow.on('ticket.summarized', summary => ai.sentiment(summary).then('update.ticket'))`
55
- // if (typeof results === 'string') {
56
- // const resultData = await results
57
- // return send(env)({ event: results, data })
58
- // }
59
- } catch (error) {
60
- console.error(error)
61
- message.retry()
62
- }
63
- }
64
- throw new Error('Event not found')
65
- })
66
- },
67
- }
68
- }
69
-
70
- export type WorkflowEvent<T = any> = {
71
- event: string
72
- data: T
73
- }
74
-
75
- export type WorkflowContext = {
76
- ai: Record<string, any>
77
- db: Record<string, any>
78
- api: Record<string, any>
79
- }
80
-
81
- export type WorkflowEventHandler = (event: WorkflowEvent, context: WorkflowContext) => Promise<any>
package/tsconfig.json DELETED
@@ -1,48 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
-
5
- /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
6
- "target": "es2021",
7
- /* Specify a set of bundled library declaration files that describe the target runtime environment. */
8
- "lib": ["es2021"],
9
- /* Specify what JSX code is generated. */
10
- "jsx": "react-jsx",
11
- "jsxImportSource": "hono/jsx",
12
-
13
- /* Specify what module code is generated. */
14
- "module": "es2022",
15
- /* Specify how TypeScript looks up a file from a given module specifier. */
16
- "moduleResolution": "Bundler",
17
- /* Specify type package names to be included without being referenced in a source file. */
18
- "types": ["@cloudflare/workers-types/2023-07-01"],
19
- /* Enable importing .json files */
20
- "resolveJsonModule": true,
21
-
22
- /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
23
- "allowJs": true,
24
- /* Enable error reporting in type-checked JavaScript files. */
25
- "checkJs": false,
26
-
27
- /* Disable emitting files from a compilation. */
28
- "noEmit": false,
29
-
30
- /* Emit the compiled files to the ./dist folder */
31
- "outDir": "./dist",
32
-
33
- /* Ensure that each file can be safely transpiled without relying on other imports. */
34
- "isolatedModules": true,
35
- /* Allow 'import x from y' when a module doesn't have a default export. */
36
- "allowSyntheticDefaultImports": true,
37
- /* Ensure that casing is correct in imports. */
38
- "forceConsistentCasingInFileNames": true,
39
-
40
- /* Enable all strict type-checking options. */
41
- "strict": true,
42
-
43
- /* Skip type checking all .d.ts files. */
44
- "skipLibCheck": true
45
- },
46
- "exclude": ["test"],
47
- "include": ["types.d.ts", "**/*.ts", "**/*.tsx"]
48
- }