ai-functions 2.1.3 → 2.3.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/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +55 -1
- package/README.md +38 -0
- package/dist/ai-promise.d.ts +3 -3
- package/dist/ai-promise.d.ts.map +1 -1
- package/dist/ai-promise.js +135 -64
- package/dist/ai-promise.js.map +1 -1
- package/dist/ai-schemas.d.ts +56 -0
- package/dist/ai-schemas.d.ts.map +1 -0
- package/dist/ai-schemas.js +53 -0
- package/dist/ai-schemas.js.map +1 -0
- package/dist/ai.d.ts +16 -242
- package/dist/ai.d.ts.map +1 -1
- package/dist/ai.js +51 -858
- package/dist/ai.js.map +1 -1
- package/dist/batch/anthropic.d.ts +6 -4
- package/dist/batch/anthropic.d.ts.map +1 -1
- package/dist/batch/anthropic.js +83 -145
- package/dist/batch/anthropic.js.map +1 -1
- package/dist/batch/bedrock.d.ts +8 -30
- package/dist/batch/bedrock.d.ts.map +1 -1
- package/dist/batch/bedrock.js +155 -338
- package/dist/batch/bedrock.js.map +1 -1
- package/dist/batch/cloudflare.d.ts +8 -20
- package/dist/batch/cloudflare.d.ts.map +1 -1
- package/dist/batch/cloudflare.js +68 -189
- package/dist/batch/cloudflare.js.map +1 -1
- package/dist/batch/google.d.ts +6 -20
- package/dist/batch/google.d.ts.map +1 -1
- package/dist/batch/google.js +70 -238
- package/dist/batch/google.js.map +1 -1
- package/dist/batch/index.d.ts +4 -1
- package/dist/batch/index.d.ts.map +1 -1
- package/dist/batch/index.js +4 -1
- package/dist/batch/index.js.map +1 -1
- package/dist/batch/memory.d.ts +1 -1
- package/dist/batch/memory.d.ts.map +1 -1
- package/dist/batch/memory.js +14 -10
- package/dist/batch/memory.js.map +1 -1
- package/dist/batch/openai.d.ts +11 -14
- package/dist/batch/openai.d.ts.map +1 -1
- package/dist/batch/openai.js +52 -156
- package/dist/batch/openai.js.map +1 -1
- package/dist/batch/provider.d.ts +111 -0
- package/dist/batch/provider.d.ts.map +1 -0
- package/dist/batch/provider.js +233 -0
- package/dist/batch/provider.js.map +1 -0
- package/dist/batch-map.d.ts.map +1 -1
- package/dist/batch-map.js +23 -17
- package/dist/batch-map.js.map +1 -1
- package/dist/batch-queue.d.ts +65 -0
- package/dist/batch-queue.d.ts.map +1 -1
- package/dist/batch-queue.js +169 -14
- package/dist/batch-queue.js.map +1 -1
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +27 -14
- package/dist/budget.js.map +1 -1
- package/dist/cache.d.ts +23 -0
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +36 -15
- package/dist/cache.js.map +1 -1
- package/dist/context.d.ts +26 -8
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +64 -62
- package/dist/context.js.map +1 -1
- package/dist/digital-objects-registry.d.ts +229 -0
- package/dist/digital-objects-registry.d.ts.map +1 -0
- package/dist/digital-objects-registry.js +617 -0
- package/dist/digital-objects-registry.js.map +1 -0
- package/dist/embeddings.d.ts +2 -2
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/errors.d.ts +22 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +35 -0
- package/dist/errors.js.map +1 -0
- package/dist/eval/runner.d.ts +8 -0
- package/dist/eval/runner.d.ts.map +1 -1
- package/dist/eval/runner.js +41 -35
- package/dist/eval/runner.js.map +1 -1
- package/dist/eval-log/in-memory.d.ts +34 -0
- package/dist/eval-log/in-memory.d.ts.map +1 -0
- package/dist/eval-log/in-memory.js +84 -0
- package/dist/eval-log/in-memory.js.map +1 -0
- package/dist/eval-log/index.d.ts +29 -0
- package/dist/eval-log/index.d.ts.map +1 -0
- package/dist/eval-log/index.js +39 -0
- package/dist/eval-log/index.js.map +1 -0
- package/dist/eval-log/types.d.ts +101 -0
- package/dist/eval-log/types.d.ts.map +1 -0
- package/dist/eval-log/types.js +16 -0
- package/dist/eval-log/types.js.map +1 -0
- package/dist/function-registry.d.ts +116 -0
- package/dist/function-registry.d.ts.map +1 -0
- package/dist/function-registry.js +546 -0
- package/dist/function-registry.js.map +1 -0
- package/dist/generate.d.ts +9 -3
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +18 -18
- package/dist/generate.js.map +1 -1
- package/dist/index.d.ts +18 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +35 -18
- package/dist/index.js.map +1 -1
- package/dist/logger.d.ts +118 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +187 -0
- package/dist/logger.js.map +1 -0
- package/dist/middleware/budget.d.ts +84 -0
- package/dist/middleware/budget.d.ts.map +1 -0
- package/dist/middleware/budget.js +110 -0
- package/dist/middleware/budget.js.map +1 -0
- package/dist/middleware/cache.d.ts +103 -0
- package/dist/middleware/cache.d.ts.map +1 -0
- package/dist/middleware/cache.js +228 -0
- package/dist/middleware/cache.js.map +1 -0
- package/dist/middleware/embed-cache.d.ts +99 -0
- package/dist/middleware/embed-cache.d.ts.map +1 -0
- package/dist/middleware/embed-cache.js +128 -0
- package/dist/middleware/embed-cache.js.map +1 -0
- package/dist/middleware/index.d.ts +11 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +11 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/trace.d.ts +103 -0
- package/dist/middleware/trace.d.ts.map +1 -0
- package/dist/middleware/trace.js +176 -0
- package/dist/middleware/trace.js.map +1 -0
- package/dist/primitives.d.ts +120 -1
- package/dist/primitives.d.ts.map +1 -1
- package/dist/primitives.js +398 -26
- package/dist/primitives.js.map +1 -1
- package/dist/retry.d.ts +66 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +115 -8
- package/dist/retry.js.map +1 -1
- package/dist/schema.js +2 -2
- package/dist/schema.js.map +1 -1
- package/dist/telemetry.d.ts +128 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/dist/telemetry.js +285 -0
- package/dist/telemetry.js.map +1 -0
- package/dist/template.d.ts.map +1 -1
- package/dist/template.js +6 -1
- package/dist/template.js.map +1 -1
- package/dist/tool-orchestration.d.ts +66 -4
- package/dist/tool-orchestration.d.ts.map +1 -1
- package/dist/tool-orchestration.js +123 -23
- package/dist/tool-orchestration.js.map +1 -1
- package/dist/type-guards.d.ts +28 -0
- package/dist/type-guards.d.ts.map +1 -0
- package/dist/type-guards.js +29 -0
- package/dist/type-guards.js.map +1 -0
- package/dist/types.d.ts +135 -17
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +36 -1
- package/dist/types.js.map +1 -1
- package/dist/wrap-for-v3.d.ts +80 -0
- package/dist/wrap-for-v3.d.ts.map +1 -0
- package/dist/wrap-for-v3.js +89 -0
- package/dist/wrap-for-v3.js.map +1 -0
- package/examples/00-quickstart.ts +232 -0
- package/examples/01-rag-chatbot.ts +212 -0
- package/examples/02-multi-agent-research.ts +290 -0
- package/examples/03-email-classification.ts +379 -0
- package/examples/04-content-moderation.ts +400 -0
- package/examples/05-document-extraction.ts +455 -0
- package/examples/06-streaming-chat-nextjs.ts +437 -0
- package/examples/07-cloudflare-worker.ts +483 -0
- package/examples/08-batch-processing.ts +491 -0
- package/examples/09-budget-constrained.ts +527 -0
- package/examples/10-tool-orchestration.ts +565 -0
- package/examples/11-retry-resilience.ts +403 -0
- package/examples/12-caching-strategies.ts +422 -0
- package/examples/README.md +145 -0
- package/package.json +28 -25
- package/src/ai-promise.ts +226 -140
- package/src/ai-schemas.ts +122 -0
- package/src/ai.ts +69 -1176
- package/src/batch/anthropic.ts +96 -161
- package/src/batch/bedrock.ts +203 -454
- package/src/batch/cloudflare.ts +99 -282
- package/src/batch/google.ts +91 -297
- package/src/batch/index.ts +4 -1
- package/src/batch/memory.ts +15 -10
- package/src/batch/openai.ts +65 -193
- package/src/batch/provider.ts +336 -0
- package/src/batch-map.ts +29 -24
- package/src/batch-queue.ts +200 -11
- package/src/budget.ts +31 -18
- package/src/cache.ts +45 -17
- package/src/context.ts +106 -77
- package/src/digital-objects-registry.ts +750 -0
- package/src/errors.ts +37 -0
- package/src/eval/runner.ts +60 -36
- package/src/eval-log/in-memory.ts +90 -0
- package/src/eval-log/index.ts +46 -0
- package/src/eval-log/types.ts +110 -0
- package/src/function-registry.ts +671 -0
- package/src/generate.ts +33 -28
- package/src/index.ts +119 -21
- package/src/logger.ts +232 -0
- package/src/middleware/budget.ts +171 -0
- package/src/middleware/cache.ts +299 -0
- package/src/middleware/embed-cache.ts +195 -0
- package/src/middleware/index.ts +23 -0
- package/src/middleware/trace.ts +248 -0
- package/src/primitives.ts +589 -62
- package/src/retry.ts +144 -18
- package/src/schema.ts +8 -8
- package/src/telemetry.ts +403 -0
- package/src/template.ts +8 -4
- package/src/tool-orchestration.ts +213 -48
- package/src/type-guards.ts +31 -0
- package/src/types.ts +164 -25
- package/src/wrap-for-v3.ts +105 -0
- package/test/ai-promise.test.ts +1080 -0
- package/test/ai-proxy.test.ts +1 -1
- package/test/batch-autosubmit-errors.test.ts +49 -37
- package/test/batch-blog-posts.test.ts +87 -129
- package/test/core-functions.test.ts +183 -579
- package/test/decide.test.ts +154 -322
- package/test/define.test.ts +211 -8
- package/test/digital-objects-registry.test.ts +760 -0
- package/test/embedding-cache-middleware.test.ts +140 -0
- package/test/generate-core.test.ts +140 -229
- package/test/implicit-batch.test.ts +22 -65
- package/test/retry-policy-integration.test.ts +117 -0
- package/test/schema.test.ts +55 -19
- package/test/template.test.ts +1164 -0
- package/test/tool-orchestration.test.ts +270 -0
- package/test/wrap-for-v3.test.ts +612 -0
- package/vitest.config.js +6 -0
- package/vitest.config.ts +20 -0
- package/LICENSE +0 -21
- package/dist/rpc/auth.d.ts +0 -69
- package/dist/rpc/auth.d.ts.map +0 -1
- package/dist/rpc/auth.js +0 -136
- package/dist/rpc/auth.js.map +0 -1
- package/dist/rpc/client.d.ts +0 -62
- package/dist/rpc/client.d.ts.map +0 -1
- package/dist/rpc/client.js +0 -103
- package/dist/rpc/client.js.map +0 -1
- package/dist/rpc/deferred.d.ts +0 -60
- package/dist/rpc/deferred.d.ts.map +0 -1
- package/dist/rpc/deferred.js +0 -96
- package/dist/rpc/deferred.js.map +0 -1
- package/dist/rpc/index.d.ts +0 -22
- package/dist/rpc/index.d.ts.map +0 -1
- package/dist/rpc/index.js +0 -38
- package/dist/rpc/index.js.map +0 -1
- package/dist/rpc/local.d.ts +0 -42
- package/dist/rpc/local.d.ts.map +0 -1
- package/dist/rpc/local.js +0 -50
- package/dist/rpc/local.js.map +0 -1
- package/dist/rpc/server.d.ts +0 -165
- package/dist/rpc/server.d.ts.map +0 -1
- package/dist/rpc/server.js +0 -405
- package/dist/rpc/server.js.map +0 -1
- package/dist/rpc/session.d.ts +0 -32
- package/dist/rpc/session.d.ts.map +0 -1
- package/dist/rpc/session.js +0 -43
- package/dist/rpc/session.js.map +0 -1
- package/dist/rpc/transport.d.ts +0 -306
- package/dist/rpc/transport.d.ts.map +0 -1
- package/dist/rpc/transport.js +0 -731
- package/dist/rpc/transport.js.map +0 -1
- package/src/batch/anthropic.js +0 -256
- package/src/batch/bedrock.js +0 -584
- package/src/batch/cloudflare.js +0 -287
- package/src/batch/google.js +0 -359
- package/src/batch/index.js +0 -30
- package/src/batch/memory.js +0 -187
- package/src/batch/openai.js +0 -402
- package/src/eval/index.js +0 -7
- package/src/eval/models.js +0 -119
- package/src/eval/runner.js +0 -147
- package/test/schema.test.js +0 -96
package/dist/ai.js
CHANGED
|
@@ -1,463 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* AI() and ai() - Core AI function constructors
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
// import { RPC, http, ws, type RPCProxy, type RPCPromise as RpcPromiseType } from 'rpc.do'
|
|
9
|
-
/**
|
|
10
|
-
* Base class for RPC service targets
|
|
11
|
-
* This is a placeholder for services that want to expose methods over RPC
|
|
12
|
-
*/
|
|
13
|
-
export class RpcTarget {
|
|
14
|
-
}
|
|
15
|
-
import { generateObject } from './generate.js';
|
|
16
|
-
import { schema as convertSchema } from './schema.js';
|
|
17
|
-
export function AI(schemasOrOptions, defaultOptions) {
|
|
18
|
-
// Check if this is RPC client mode
|
|
19
|
-
if (isAIClientOptions(schemasOrOptions)) {
|
|
20
|
-
// TODO: Re-enable RPC client when rpc.do is published
|
|
21
|
-
// const { model, temperature, maxTokens, functions, wsUrl, httpUrl, token } = schemasOrOptions
|
|
22
|
-
//
|
|
23
|
-
// // Create transport based on provided URLs
|
|
24
|
-
// let transport
|
|
25
|
-
// if (wsUrl) {
|
|
26
|
-
// transport = ws(wsUrl, token ? () => token : undefined)
|
|
27
|
-
// } else if (httpUrl) {
|
|
28
|
-
// transport = http(httpUrl, token ? () => token : undefined)
|
|
29
|
-
// } else {
|
|
30
|
-
// throw new Error('AI client requires either wsUrl or httpUrl')
|
|
31
|
-
// }
|
|
32
|
-
//
|
|
33
|
-
// // Create RPC client
|
|
34
|
-
// const rpcClient = RPC<AIClient>(transport)
|
|
35
|
-
//
|
|
36
|
-
// // Create a proxy that handles both defined methods and dynamic function calls
|
|
37
|
-
// return new Proxy(rpcClient, {
|
|
38
|
-
// get(target, prop: string) {
|
|
39
|
-
// // Return existing methods
|
|
40
|
-
// if (prop in target) {
|
|
41
|
-
// return (target as unknown as Record<string, unknown>)[prop]
|
|
42
|
-
// }
|
|
43
|
-
//
|
|
44
|
-
// // Handle dynamic function calls (ai.functionName())
|
|
45
|
-
// return (...args: unknown[]) => {
|
|
46
|
-
// const client = target as unknown as AIClient
|
|
47
|
-
// return client.do(prop, args.length === 1 ? args[0] : args)
|
|
48
|
-
// }
|
|
49
|
-
// }
|
|
50
|
-
// }) as AIClient & Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
51
|
-
throw new Error('RPC client mode requires rpc.do package (not yet published). Use schema-based mode instead.');
|
|
52
|
-
}
|
|
53
|
-
// Schema functions mode - create a function for each schema
|
|
54
|
-
return createSchemaFunctions(schemasOrOptions, defaultOptions);
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Check if options are AI client options vs schemas
|
|
58
|
-
*/
|
|
59
|
-
function isAIClientOptions(value) {
|
|
60
|
-
if (typeof value !== 'object' || value === null)
|
|
61
|
-
return false;
|
|
62
|
-
const obj = value;
|
|
63
|
-
return 'wsUrl' in obj || 'httpUrl' in obj || 'functions' in obj;
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Create schema-based functions from a map of schemas
|
|
67
|
-
*/
|
|
68
|
-
function createSchemaFunctions(schemas, defaultOptions = {}) {
|
|
69
|
-
const functions = {};
|
|
70
|
-
for (const [name, schema] of Object.entries(schemas)) {
|
|
71
|
-
functions[name] = async (prompt, options) => {
|
|
72
|
-
const mergedOptions = { ...defaultOptions, ...options };
|
|
73
|
-
const { model = 'sonnet', system, ...rest } = mergedOptions;
|
|
74
|
-
// Build prompt from schema descriptions if none provided
|
|
75
|
-
const schemaPrompt = prompt || buildPromptFromSchema(schema);
|
|
76
|
-
const result = await generateObject({
|
|
77
|
-
model,
|
|
78
|
-
schema,
|
|
79
|
-
prompt: schemaPrompt,
|
|
80
|
-
system,
|
|
81
|
-
...rest,
|
|
82
|
-
});
|
|
83
|
-
return result.object;
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
return functions;
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Build a prompt by extracting descriptions from the schema
|
|
90
|
-
*/
|
|
91
|
-
function buildPromptFromSchema(schema, path = '') {
|
|
92
|
-
if (typeof schema === 'string') {
|
|
93
|
-
return schema;
|
|
94
|
-
}
|
|
95
|
-
if (Array.isArray(schema)) {
|
|
96
|
-
return schema[0] || 'Generate items';
|
|
97
|
-
}
|
|
98
|
-
if (typeof schema === 'object' && schema !== null) {
|
|
99
|
-
const descriptions = [];
|
|
100
|
-
for (const [key, value] of Object.entries(schema)) {
|
|
101
|
-
const subPrompt = buildPromptFromSchema(value, path ? `${path}.${key}` : key);
|
|
102
|
-
if (subPrompt) {
|
|
103
|
-
descriptions.push(`${key}: ${subPrompt}`);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
return descriptions.length > 0 ? `Generate the following:\n${descriptions.join('\n')}` : '';
|
|
107
|
-
}
|
|
108
|
-
return '';
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Create a defined function from a function definition
|
|
112
|
-
*/
|
|
113
|
-
function createDefinedFunction(definition) {
|
|
114
|
-
const call = async (args) => {
|
|
115
|
-
switch (definition.type) {
|
|
116
|
-
case 'code':
|
|
117
|
-
return executeCodeFunction(definition, args);
|
|
118
|
-
case 'generative':
|
|
119
|
-
return executeGenerativeFunction(definition, args);
|
|
120
|
-
case 'agentic':
|
|
121
|
-
return executeAgenticFunction(definition, args);
|
|
122
|
-
case 'human':
|
|
123
|
-
return executeHumanFunction(definition, args);
|
|
124
|
-
default:
|
|
125
|
-
throw new Error(`Unknown function type: ${definition.type}`);
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
const asTool = () => {
|
|
129
|
-
return {
|
|
130
|
-
name: definition.name,
|
|
131
|
-
description: definition.description || `Execute ${definition.name}`,
|
|
132
|
-
parameters: convertArgsToJSONSchema(definition.args),
|
|
133
|
-
handler: call,
|
|
134
|
-
};
|
|
135
|
-
};
|
|
136
|
-
return { definition, call, asTool };
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Convert args schema to JSON Schema
|
|
140
|
-
*/
|
|
141
|
-
function convertArgsToJSONSchema(args) {
|
|
142
|
-
// If it's already a JSON schema-like object
|
|
143
|
-
if (typeof args === 'object' && args !== null && 'type' in args) {
|
|
144
|
-
return args;
|
|
145
|
-
}
|
|
146
|
-
// Convert SimpleSchema to JSON Schema
|
|
147
|
-
const properties = {};
|
|
148
|
-
const required = [];
|
|
149
|
-
if (typeof args === 'object' && args !== null) {
|
|
150
|
-
for (const [key, value] of Object.entries(args)) {
|
|
151
|
-
required.push(key); // All properties required for cross-provider compatibility
|
|
152
|
-
properties[key] = convertValueToJSONSchema(value);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
return {
|
|
156
|
-
type: 'object',
|
|
157
|
-
properties,
|
|
158
|
-
required,
|
|
159
|
-
additionalProperties: false, // Required for OpenAI compatibility
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Convert a single value to JSON Schema
|
|
164
|
-
*/
|
|
165
|
-
function convertValueToJSONSchema(value) {
|
|
166
|
-
if (typeof value === 'string') {
|
|
167
|
-
// Check for type hints: 'description (number)', 'description (boolean)', etc.
|
|
168
|
-
const typeMatch = value.match(/^(.+?)\s*\((number|boolean|integer|date)\)$/i);
|
|
169
|
-
if (typeMatch) {
|
|
170
|
-
const description = typeMatch[1];
|
|
171
|
-
const type = typeMatch[2];
|
|
172
|
-
switch (type.toLowerCase()) {
|
|
173
|
-
case 'number':
|
|
174
|
-
return { type: 'number', description: description.trim() };
|
|
175
|
-
case 'integer':
|
|
176
|
-
return { type: 'integer', description: description.trim() };
|
|
177
|
-
case 'boolean':
|
|
178
|
-
return { type: 'boolean', description: description.trim() };
|
|
179
|
-
case 'date':
|
|
180
|
-
return { type: 'string', format: 'date-time', description: description.trim() };
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
// Check for enum: 'option1 | option2 | option3'
|
|
184
|
-
if (value.includes(' | ')) {
|
|
185
|
-
const options = value.split(' | ').map(s => s.trim());
|
|
186
|
-
return { type: 'string', enum: options };
|
|
187
|
-
}
|
|
188
|
-
return { type: 'string', description: value };
|
|
189
|
-
}
|
|
190
|
-
if (Array.isArray(value) && value.length === 1) {
|
|
191
|
-
const [desc] = value;
|
|
192
|
-
if (typeof desc === 'string') {
|
|
193
|
-
return { type: 'array', items: { type: 'string' }, description: desc };
|
|
194
|
-
}
|
|
195
|
-
if (typeof desc === 'number') {
|
|
196
|
-
return { type: 'array', items: { type: 'number' } };
|
|
197
|
-
}
|
|
198
|
-
return { type: 'array', items: convertValueToJSONSchema(desc) };
|
|
199
|
-
}
|
|
200
|
-
if (typeof value === 'object' && value !== null) {
|
|
201
|
-
return convertArgsToJSONSchema(value);
|
|
202
|
-
}
|
|
203
|
-
return { type: 'string' };
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Fill template with values
|
|
207
|
-
*/
|
|
208
|
-
function fillTemplate(template, args) {
|
|
209
|
-
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => String(args[key] ?? ''));
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Execute a code function - generates code with tests and examples
|
|
213
|
-
*/
|
|
214
|
-
async function executeCodeFunction(definition, args) {
|
|
215
|
-
const { name, description, language = 'typescript', instructions, includeTests = true, includeExamples = true } = definition;
|
|
216
|
-
const argsDescription = JSON.stringify(args, null, 2);
|
|
217
|
-
const result = await generateObject({
|
|
218
|
-
model: 'sonnet',
|
|
219
|
-
schema: {
|
|
220
|
-
code: 'The complete implementation code with JSDoc comments',
|
|
221
|
-
tests: includeTests ? 'Vitest test code for the implementation' : undefined,
|
|
222
|
-
examples: includeExamples ? 'Example usage code' : undefined,
|
|
223
|
-
documentation: 'JSDoc or equivalent documentation string',
|
|
224
|
-
},
|
|
225
|
-
system: `You are an expert ${language} developer. Generate clean, well-documented, production-ready code.`,
|
|
226
|
-
prompt: `Generate a ${language} function with the following specification:
|
|
227
|
-
|
|
228
|
-
Name: ${name}
|
|
229
|
-
Description: ${description || 'No description provided'}
|
|
230
|
-
Arguments: ${argsDescription}
|
|
231
|
-
Return Type: ${JSON.stringify(definition.returnType)}
|
|
232
|
-
|
|
233
|
-
${instructions ? `Additional Instructions: ${instructions}` : ''}
|
|
234
|
-
|
|
235
|
-
Requirements:
|
|
236
|
-
- Include comprehensive JSDoc comments
|
|
237
|
-
- Follow best practices for ${language}
|
|
238
|
-
- Handle edge cases appropriately
|
|
239
|
-
${includeTests ? '- Include vitest tests that cover main functionality and edge cases' : ''}
|
|
240
|
-
${includeExamples ? '- Include example usage showing how to call the function' : ''}`,
|
|
241
|
-
});
|
|
242
|
-
const obj = result.object;
|
|
243
|
-
return {
|
|
244
|
-
code: obj.code,
|
|
245
|
-
tests: obj.tests,
|
|
246
|
-
examples: obj.examples,
|
|
247
|
-
language,
|
|
248
|
-
documentation: obj.documentation,
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
/**
|
|
252
|
-
* Execute a generative function - uses AI to generate content
|
|
253
|
-
*/
|
|
254
|
-
async function executeGenerativeFunction(definition, args) {
|
|
255
|
-
const { output, system, promptTemplate, model = 'sonnet', temperature, returnType } = definition;
|
|
256
|
-
const prompt = promptTemplate
|
|
257
|
-
? fillTemplate(promptTemplate, args)
|
|
258
|
-
: JSON.stringify(args);
|
|
259
|
-
switch (output) {
|
|
260
|
-
case 'string': {
|
|
261
|
-
const result = await generateObject({
|
|
262
|
-
model,
|
|
263
|
-
schema: { text: 'The generated text response' },
|
|
264
|
-
system,
|
|
265
|
-
prompt,
|
|
266
|
-
temperature,
|
|
267
|
-
});
|
|
268
|
-
return result.object.text;
|
|
269
|
-
}
|
|
270
|
-
case 'object': {
|
|
271
|
-
const objectSchema = returnType || { result: 'The generated result' };
|
|
272
|
-
const result = await generateObject({
|
|
273
|
-
model,
|
|
274
|
-
schema: objectSchema,
|
|
275
|
-
system,
|
|
276
|
-
prompt,
|
|
277
|
-
temperature,
|
|
278
|
-
});
|
|
279
|
-
return result.object;
|
|
280
|
-
}
|
|
281
|
-
case 'image': {
|
|
282
|
-
const client = getDefaultAIClient();
|
|
283
|
-
// Cast required: client.image() returns ImageResult but TOutput is determined by the
|
|
284
|
-
// output parameter at runtime. TypeScript can't narrow TOutput based on output='image'.
|
|
285
|
-
return client.image(prompt);
|
|
286
|
-
}
|
|
287
|
-
case 'video': {
|
|
288
|
-
const client = getDefaultAIClient();
|
|
289
|
-
// Cast required: client.video() returns VideoResult but TOutput is determined by the
|
|
290
|
-
// output parameter at runtime. TypeScript can't narrow TOutput based on output='video'.
|
|
291
|
-
return client.video(prompt);
|
|
292
|
-
}
|
|
293
|
-
default:
|
|
294
|
-
throw new Error(`Unknown output type: ${output}`);
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Execute an agentic function - runs in a loop with tools
|
|
299
|
-
*/
|
|
300
|
-
async function executeAgenticFunction(definition, args) {
|
|
301
|
-
const { instructions, promptTemplate, tools = [], maxIterations = 10, model = 'sonnet', returnType } = definition;
|
|
302
|
-
const prompt = promptTemplate
|
|
303
|
-
? fillTemplate(promptTemplate, args)
|
|
304
|
-
: JSON.stringify(args);
|
|
305
|
-
// Build system prompt with tool descriptions
|
|
306
|
-
const toolDescriptions = tools.map(t => `- ${t.name}: ${t.description}`).join('\n');
|
|
307
|
-
const systemPrompt = `${instructions}
|
|
308
|
-
|
|
309
|
-
Available tools:
|
|
310
|
-
${toolDescriptions || 'No tools available'}
|
|
311
|
-
|
|
312
|
-
Work step by step to accomplish the task. When you have completed the task, provide your final result.`;
|
|
313
|
-
let iteration = 0;
|
|
314
|
-
const toolResults = [];
|
|
315
|
-
// Simple agent loop
|
|
316
|
-
while (iteration < maxIterations) {
|
|
317
|
-
iteration++;
|
|
318
|
-
const result = await generateObject({
|
|
319
|
-
model,
|
|
320
|
-
schema: {
|
|
321
|
-
thinking: 'Your step-by-step reasoning',
|
|
322
|
-
toolCall: {
|
|
323
|
-
name: 'Tool to call (or "done" if finished)',
|
|
324
|
-
arguments: 'Arguments for the tool as JSON string',
|
|
325
|
-
},
|
|
326
|
-
finalResult: returnType || 'The final result if done',
|
|
327
|
-
},
|
|
328
|
-
system: systemPrompt,
|
|
329
|
-
prompt: `Task: ${prompt}
|
|
330
|
-
|
|
331
|
-
Previous tool results:
|
|
332
|
-
${toolResults.map((r, i) => `Step ${i + 1}: ${JSON.stringify(r)}`).join('\n') || 'None yet'}
|
|
333
|
-
|
|
334
|
-
What is your next step?`,
|
|
335
|
-
});
|
|
336
|
-
const response = result.object;
|
|
337
|
-
if (response.toolCall.name === 'done' || response.finalResult) {
|
|
338
|
-
return response.finalResult;
|
|
339
|
-
}
|
|
340
|
-
// Execute tool call
|
|
341
|
-
const tool = tools.find(t => t.name === response.toolCall.name);
|
|
342
|
-
if (tool) {
|
|
343
|
-
let toolArgs;
|
|
344
|
-
try {
|
|
345
|
-
toolArgs = JSON.parse(response.toolCall.arguments || '{}');
|
|
346
|
-
}
|
|
347
|
-
catch (e) {
|
|
348
|
-
toolResults.push({
|
|
349
|
-
error: `Invalid tool arguments: ${e.message}`,
|
|
350
|
-
});
|
|
351
|
-
continue;
|
|
352
|
-
}
|
|
353
|
-
const toolResult = await tool.handler(toolArgs);
|
|
354
|
-
toolResults.push({ tool: response.toolCall.name, result: toolResult });
|
|
355
|
-
}
|
|
356
|
-
else {
|
|
357
|
-
toolResults.push({ error: `Tool not found: ${response.toolCall.name}` });
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
throw new Error(`Agent exceeded maximum iterations (${maxIterations})`);
|
|
361
|
-
}
|
|
362
|
-
/**
|
|
363
|
-
* Execute a human function - generates UI and waits for human input
|
|
364
|
-
*
|
|
365
|
-
* **Note: This function currently returns placeholder/mock data.**
|
|
366
|
-
*
|
|
367
|
-
* In a complete implementation, this function would:
|
|
368
|
-
* 1. Generate channel-specific UI (Slack blocks, email templates, web forms, etc.)
|
|
369
|
-
* 2. Send the generated UI to the appropriate channel
|
|
370
|
-
* 3. Wait for human response with optional timeout
|
|
371
|
-
* 4. Validate and return the human's response
|
|
372
|
-
*
|
|
373
|
-
* The current implementation generates the UI artifacts but returns a pending
|
|
374
|
-
* placeholder instead of actually sending to the channel and waiting for response.
|
|
375
|
-
* This allows testing the UI generation without requiring actual channel integrations.
|
|
376
|
-
*
|
|
377
|
-
* @param definition - The human function definition with channel and instructions
|
|
378
|
-
* @param args - Arguments to pass to the function
|
|
379
|
-
* @returns A placeholder result with `_pending: true` and generated artifacts
|
|
4
|
+
* This module is a re-export layer that delegates to focused modules:
|
|
5
|
+
* - ai-schemas.ts - Schema-based AI function generation
|
|
6
|
+
* - function-registry.ts - Function definition and registry
|
|
7
|
+
* - primitives.ts - Auto-define proxy functionality (`define`, `createSmartAI`, `aiProxy`)
|
|
380
8
|
*
|
|
381
|
-
*
|
|
382
|
-
* ```ts
|
|
383
|
-
* // The result will be a placeholder, not an actual human response:
|
|
384
|
-
* // {
|
|
385
|
-
* // _pending: true,
|
|
386
|
-
* // channel: 'workspace',
|
|
387
|
-
* // artifacts: { ... generated UI ... },
|
|
388
|
-
* // expectedResponseType: { approved: boolean }
|
|
389
|
-
* // }
|
|
390
|
-
* ```
|
|
9
|
+
* All exports are maintained for backward compatibility.
|
|
391
10
|
*/
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
phone: {
|
|
410
|
-
script: 'Phone call script',
|
|
411
|
-
keyPoints: ['Key points to cover'],
|
|
412
|
-
},
|
|
413
|
-
sms: {
|
|
414
|
-
text: 'SMS message text (max 160 chars)',
|
|
415
|
-
},
|
|
416
|
-
workspace: {
|
|
417
|
-
blocks: ['Workspace/Slack BlockKit blocks as JSON array'],
|
|
418
|
-
text: 'Plain text fallback',
|
|
419
|
-
},
|
|
420
|
-
web: {
|
|
421
|
-
component: 'React component code for the form',
|
|
422
|
-
schema: 'JSON schema for the form fields',
|
|
423
|
-
},
|
|
424
|
-
// Legacy fallback
|
|
425
|
-
custom: {
|
|
426
|
-
data: 'Structured data for custom implementation',
|
|
427
|
-
instructions: 'Instructions for the human',
|
|
428
|
-
},
|
|
429
|
-
};
|
|
430
|
-
const result = await generateObject({
|
|
431
|
-
model: 'sonnet',
|
|
432
|
-
schema: uiSchema[channel] ?? uiSchema.custom,
|
|
433
|
-
system: `Generate ${channel} UI/content for a human-in-the-loop task.`,
|
|
434
|
-
prompt: `Task: ${instructions}
|
|
435
|
-
|
|
436
|
-
Input data:
|
|
437
|
-
${prompt}
|
|
438
|
-
|
|
439
|
-
Expected response format:
|
|
440
|
-
${JSON.stringify(returnType)}
|
|
441
|
-
|
|
442
|
-
Generate the appropriate ${channel} UI/content to collect this response from a human.`,
|
|
443
|
-
});
|
|
444
|
-
// NOTE: This is a placeholder implementation.
|
|
445
|
-
// In a real implementation, this would:
|
|
446
|
-
// 1. Send the generated UI to the appropriate channel (Slack, email, etc.)
|
|
447
|
-
// 2. Wait for human response with optional timeout
|
|
448
|
-
// 3. Return the validated response
|
|
449
|
-
//
|
|
450
|
-
// Current behavior: Returns generated artifacts as a pending placeholder
|
|
451
|
-
// Cast required: This is a placeholder implementation that returns a different shape
|
|
452
|
-
// than TOutput. When fully implemented, this would return actual TOutput from human input.
|
|
453
|
-
// The _pending flag allows consumers to detect placeholder vs real responses.
|
|
454
|
-
return {
|
|
455
|
-
_pending: true,
|
|
456
|
-
channel,
|
|
457
|
-
artifacts: result.object,
|
|
458
|
-
expectedResponseType: returnType,
|
|
459
|
-
};
|
|
460
|
-
}
|
|
11
|
+
// ============================================================================
|
|
12
|
+
// Re-export from ai-schemas.ts - Schema-based AI functions
|
|
13
|
+
// ============================================================================
|
|
14
|
+
export { createSchemaFunctions, } from './ai-schemas.js';
|
|
15
|
+
// ============================================================================
|
|
16
|
+
// Re-export from function-registry.ts - Function definition and registry
|
|
17
|
+
// ============================================================================
|
|
18
|
+
export { defineFunction, createDefinedFunction, createFunctionRegistry, functions, resetGlobalRegistry, convertArgsToJSONSchema, fillTemplate, generateCode, } from './function-registry.js';
|
|
19
|
+
// ============================================================================
|
|
20
|
+
// Re-export from primitives.ts - Auto-define proxy functionality
|
|
21
|
+
// (formerly in ai-proxy.ts; inlined to give property-access tracking a single
|
|
22
|
+
// owner in ai-promise.ts)
|
|
23
|
+
// ============================================================================
|
|
24
|
+
export { define, createSmartAI, aiProxy as ai } from './primitives.js';
|
|
25
|
+
// ============================================================================
|
|
26
|
+
// Local exports - withTemplate utility
|
|
27
|
+
// ============================================================================
|
|
461
28
|
/**
|
|
462
29
|
* Helper to create a function that supports both regular calls and tagged template literals
|
|
463
30
|
* @example
|
|
@@ -481,416 +48,42 @@ export function withTemplate(fn) {
|
|
|
481
48
|
return fn(promptOrStrings, ...args);
|
|
482
49
|
};
|
|
483
50
|
}
|
|
484
|
-
|
|
485
|
-
let defaultClient = null;
|
|
51
|
+
import { createSchemaFunctions } from './ai-schemas.js';
|
|
486
52
|
/**
|
|
487
|
-
*
|
|
488
|
-
*/
|
|
489
|
-
export function configureAI(options) {
|
|
490
|
-
defaultClient = AI(options);
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Get the default AI client, throwing if not configured
|
|
494
|
-
*/
|
|
495
|
-
function getDefaultAIClient() {
|
|
496
|
-
if (!defaultClient) {
|
|
497
|
-
// Try to auto-configure from environment
|
|
498
|
-
const wsUrl = typeof process !== 'undefined' ? process.env?.AI_WS_URL : undefined;
|
|
499
|
-
const httpUrl = typeof process !== 'undefined' ? process.env?.AI_HTTP_URL : undefined;
|
|
500
|
-
if (wsUrl) {
|
|
501
|
-
// Explicitly type the options to call the correct AI() overload.
|
|
502
|
-
// Without this, TypeScript might incorrectly match the schema overload.
|
|
503
|
-
const options = { wsUrl };
|
|
504
|
-
defaultClient = AI(options);
|
|
505
|
-
}
|
|
506
|
-
else if (httpUrl) {
|
|
507
|
-
// Explicitly type the options to call the correct AI() overload.
|
|
508
|
-
const options = { httpUrl };
|
|
509
|
-
defaultClient = AI(options);
|
|
510
|
-
}
|
|
511
|
-
else {
|
|
512
|
-
throw new Error('AI client not configured. Call configureAI() first or set AI_WS_URL/AI_HTTP_URL environment variables.');
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
return defaultClient;
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* Base class for implementing AI services
|
|
519
|
-
*
|
|
520
|
-
* Extend this class to create your own AI service implementation.
|
|
521
|
-
*
|
|
522
|
-
* @example
|
|
523
|
-
* ```ts
|
|
524
|
-
* class MyAIService extends AIServiceTarget {
|
|
525
|
-
* async generate(options: AIGenerateOptions): Promise<AIGenerateResult> {
|
|
526
|
-
* // Your implementation
|
|
527
|
-
* }
|
|
528
|
-
* }
|
|
529
|
-
* ```
|
|
530
|
-
*/
|
|
531
|
-
export class AIServiceTarget extends RpcTarget {
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Standalone function for defining AI functions
|
|
53
|
+
* Create AI functions from schemas
|
|
535
54
|
*
|
|
536
55
|
* @example
|
|
537
56
|
* ```ts
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
57
|
+
* const ai = AI({
|
|
58
|
+
* storyBrand: {
|
|
59
|
+
* hero: 'Who is the customer?',
|
|
60
|
+
* problem: {
|
|
61
|
+
* internal: 'What internal problem do they face?',
|
|
62
|
+
* external: 'What external challenge exists?',
|
|
63
|
+
* philosophical: 'Why is this wrong?',
|
|
64
|
+
* },
|
|
65
|
+
* guide: 'Who helps them? (the brand)',
|
|
66
|
+
* plan: ['What are the steps to success?'],
|
|
67
|
+
* callToAction: 'What should they do?',
|
|
68
|
+
* success: 'What does success look like?',
|
|
69
|
+
* failure: 'What happens if they fail?',
|
|
70
|
+
* },
|
|
71
|
+
* recipe: {
|
|
72
|
+
* name: 'Recipe name',
|
|
73
|
+
* type: 'food | drink | dessert',
|
|
74
|
+
* servings: 'How many servings? (number)',
|
|
75
|
+
* ingredients: ['List all ingredients'],
|
|
76
|
+
* steps: ['Cooking steps in order'],
|
|
77
|
+
* },
|
|
546
78
|
* })
|
|
547
79
|
*
|
|
548
|
-
*
|
|
80
|
+
* // Call the generated functions
|
|
81
|
+
* const brand = await ai.storyBrand('Acme Corp sells widgets')
|
|
82
|
+
* const dinner = await ai.recipe('Italian pasta for 4 people')
|
|
549
83
|
* ```
|
|
550
84
|
*/
|
|
551
|
-
export function
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
// ============================================================================
|
|
555
|
-
// Function Registry
|
|
556
|
-
// ============================================================================
|
|
557
|
-
/**
|
|
558
|
-
* In-memory function registry
|
|
559
|
-
*/
|
|
560
|
-
class InMemoryFunctionRegistry {
|
|
561
|
-
functions = new Map();
|
|
562
|
-
get(name) {
|
|
563
|
-
return this.functions.get(name);
|
|
564
|
-
}
|
|
565
|
-
set(name, fn) {
|
|
566
|
-
this.functions.set(name, fn);
|
|
567
|
-
}
|
|
568
|
-
has(name) {
|
|
569
|
-
return this.functions.has(name);
|
|
570
|
-
}
|
|
571
|
-
list() {
|
|
572
|
-
return Array.from(this.functions.keys());
|
|
573
|
-
}
|
|
574
|
-
delete(name) {
|
|
575
|
-
return this.functions.delete(name);
|
|
576
|
-
}
|
|
577
|
-
clear() {
|
|
578
|
-
this.functions.clear();
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* Global function registry
|
|
583
|
-
*
|
|
584
|
-
* Note: This is in-memory only. For persistence, use mdxai or mdxdb packages.
|
|
585
|
-
*/
|
|
586
|
-
export const functions = new InMemoryFunctionRegistry();
|
|
587
|
-
// ============================================================================
|
|
588
|
-
// Auto-Define Functions
|
|
589
|
-
// ============================================================================
|
|
590
|
-
/**
|
|
591
|
-
* Analyze a function call and determine what type of function it should be
|
|
592
|
-
*/
|
|
593
|
-
async function analyzeFunction(name, args) {
|
|
594
|
-
// Convert camelCase/snake_case to readable name
|
|
595
|
-
const readableName = name
|
|
596
|
-
.replace(/([A-Z])/g, ' $1')
|
|
597
|
-
.replace(/_/g, ' ')
|
|
598
|
-
.toLowerCase()
|
|
599
|
-
.trim();
|
|
600
|
-
const argDescriptions = Object.entries(args)
|
|
601
|
-
.map(([key, value]) => {
|
|
602
|
-
const type = Array.isArray(value) ? 'array' : typeof value;
|
|
603
|
-
return ` - ${key}: ${type} (example: ${JSON.stringify(value).slice(0, 50)})`;
|
|
604
|
-
})
|
|
605
|
-
.join('\n');
|
|
606
|
-
const result = await generateObject({
|
|
607
|
-
model: 'sonnet',
|
|
608
|
-
schema: {
|
|
609
|
-
type: 'code | generative | agentic | human',
|
|
610
|
-
reasoning: 'Why this function type is appropriate (1-2 sentences)',
|
|
611
|
-
description: 'What this function does',
|
|
612
|
-
output: 'string | object | image | video | audio',
|
|
613
|
-
returnType: 'Schema for the return type as a SimpleSchema object',
|
|
614
|
-
system: 'System prompt for the AI (if generative/agentic)',
|
|
615
|
-
promptTemplate: 'Prompt template with {{arg}} placeholders',
|
|
616
|
-
instructions: 'Instructions for agentic/human functions',
|
|
617
|
-
needsTools: 'true | false',
|
|
618
|
-
suggestedTools: ['Names of tools that might be needed'],
|
|
619
|
-
channel: 'slack | email | web | sms | custom',
|
|
620
|
-
},
|
|
621
|
-
system: `You are an expert at designing AI functions. Analyze the function name and arguments to determine the best function type.
|
|
622
|
-
|
|
623
|
-
Function Types:
|
|
624
|
-
- "code": For generating executable code (calculations, algorithms, data transformations)
|
|
625
|
-
- "generative": For generating content (text, summaries, translations, creative writing, structured data)
|
|
626
|
-
- "agentic": For complex tasks requiring multiple steps, research, or tool use (research, planning, multi-step workflows)
|
|
627
|
-
- "human": For tasks requiring human judgment, approval, or input (approvals, reviews, decisions)
|
|
628
|
-
|
|
629
|
-
Guidelines:
|
|
630
|
-
- Most functions should be "generative" - they generate content or structured data
|
|
631
|
-
- Use "code" only when actual executable code needs to be generated
|
|
632
|
-
- Use "agentic" when the task requires research, multiple steps, or external tool use
|
|
633
|
-
- Use "human" when human judgment/approval is essential`,
|
|
634
|
-
prompt: `Analyze this function call and determine how to define it:
|
|
635
|
-
|
|
636
|
-
Function Name: ${name}
|
|
637
|
-
Readable Name: ${readableName}
|
|
638
|
-
Arguments:
|
|
639
|
-
${argDescriptions || ' (no arguments)'}
|
|
640
|
-
|
|
641
|
-
Determine:
|
|
642
|
-
1. What type of function this should be
|
|
643
|
-
2. What it should return
|
|
644
|
-
3. How it should be implemented`,
|
|
645
|
-
});
|
|
646
|
-
const analysis = result.object;
|
|
647
|
-
// Build the function definition based on the analysis
|
|
648
|
-
let definition;
|
|
649
|
-
const baseDefinition = {
|
|
650
|
-
name,
|
|
651
|
-
description: analysis.description,
|
|
652
|
-
args: inferArgsSchema(args),
|
|
653
|
-
returnType: analysis.returnType,
|
|
654
|
-
};
|
|
655
|
-
switch (analysis.type) {
|
|
656
|
-
case 'code':
|
|
657
|
-
definition = {
|
|
658
|
-
...baseDefinition,
|
|
659
|
-
type: 'code',
|
|
660
|
-
language: 'typescript',
|
|
661
|
-
instructions: analysis.instructions,
|
|
662
|
-
};
|
|
663
|
-
break;
|
|
664
|
-
case 'agentic':
|
|
665
|
-
definition = {
|
|
666
|
-
...baseDefinition,
|
|
667
|
-
type: 'agentic',
|
|
668
|
-
instructions: analysis.instructions || `Complete the ${readableName} task`,
|
|
669
|
-
promptTemplate: analysis.promptTemplate,
|
|
670
|
-
tools: [], // Tools would need to be provided separately
|
|
671
|
-
maxIterations: 10,
|
|
672
|
-
};
|
|
673
|
-
break;
|
|
674
|
-
case 'human':
|
|
675
|
-
definition = {
|
|
676
|
-
...baseDefinition,
|
|
677
|
-
type: 'human',
|
|
678
|
-
channel: (analysis.channel || 'web'),
|
|
679
|
-
instructions: analysis.instructions || `Please review and respond to this ${readableName} request`,
|
|
680
|
-
promptTemplate: analysis.promptTemplate,
|
|
681
|
-
};
|
|
682
|
-
break;
|
|
683
|
-
case 'generative':
|
|
684
|
-
default:
|
|
685
|
-
definition = {
|
|
686
|
-
...baseDefinition,
|
|
687
|
-
type: 'generative',
|
|
688
|
-
output: (analysis.output || 'object'),
|
|
689
|
-
system: analysis.system,
|
|
690
|
-
promptTemplate: analysis.promptTemplate || `{{${Object.keys(args)[0] || 'input'}}}`,
|
|
691
|
-
};
|
|
692
|
-
break;
|
|
693
|
-
}
|
|
694
|
-
return {
|
|
695
|
-
type: analysis.type,
|
|
696
|
-
reasoning: analysis.reasoning,
|
|
697
|
-
definition,
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* Infer a schema from example arguments
|
|
702
|
-
*/
|
|
703
|
-
function inferArgsSchema(args) {
|
|
704
|
-
const schema = {};
|
|
705
|
-
for (const [key, value] of Object.entries(args)) {
|
|
706
|
-
if (typeof value === 'string') {
|
|
707
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`;
|
|
708
|
-
}
|
|
709
|
-
else if (typeof value === 'number') {
|
|
710
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()} (number)`;
|
|
711
|
-
}
|
|
712
|
-
else if (typeof value === 'boolean') {
|
|
713
|
-
schema[key] = `Whether ${key.replace(/([A-Z])/g, ' $1').toLowerCase()} (boolean)`;
|
|
714
|
-
}
|
|
715
|
-
else if (Array.isArray(value)) {
|
|
716
|
-
if (value.length > 0 && typeof value[0] === 'string') {
|
|
717
|
-
schema[key] = [`List of ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`];
|
|
718
|
-
}
|
|
719
|
-
else {
|
|
720
|
-
schema[key] = [`Items for ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`];
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
else if (typeof value === 'object' && value !== null) {
|
|
724
|
-
schema[key] = inferArgsSchema(value);
|
|
725
|
-
}
|
|
726
|
-
else {
|
|
727
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`;
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return schema;
|
|
731
|
-
}
|
|
732
|
-
/**
|
|
733
|
-
* Auto-define a function based on its name and arguments, or define with explicit definition
|
|
734
|
-
*
|
|
735
|
-
* When called with (name, args), uses AI to analyze and determine:
|
|
736
|
-
* - What type of function it should be (code, generative, agentic, human)
|
|
737
|
-
* - What it should return
|
|
738
|
-
* - How it should be implemented
|
|
739
|
-
*
|
|
740
|
-
* When called with a FunctionDefinition, creates the function directly.
|
|
741
|
-
*
|
|
742
|
-
* @example
|
|
743
|
-
* ```ts
|
|
744
|
-
* // Auto-define from name and example args
|
|
745
|
-
* const planTrip = await define('planTrip', { destination: 'Tokyo', travelers: 2 })
|
|
746
|
-
*
|
|
747
|
-
* // Or define explicitly
|
|
748
|
-
* const summarize = define.generative({
|
|
749
|
-
* name: 'summarize',
|
|
750
|
-
* args: { text: 'Text to summarize' },
|
|
751
|
-
* output: 'string',
|
|
752
|
-
* })
|
|
753
|
-
*
|
|
754
|
-
* // Or with full definition
|
|
755
|
-
* const fn = defineFunction({
|
|
756
|
-
* type: 'generative',
|
|
757
|
-
* name: 'translate',
|
|
758
|
-
* args: { text: 'Text', lang: 'Target language' },
|
|
759
|
-
* output: 'string',
|
|
760
|
-
* })
|
|
761
|
-
* ```
|
|
762
|
-
*/
|
|
763
|
-
async function autoDefineImpl(name, args) {
|
|
764
|
-
// Check if already defined
|
|
765
|
-
const existing = functions.get(name);
|
|
766
|
-
if (existing) {
|
|
767
|
-
return existing;
|
|
768
|
-
}
|
|
769
|
-
// Analyze and define the function
|
|
770
|
-
const { definition } = await analyzeFunction(name, args);
|
|
771
|
-
// Create the defined function
|
|
772
|
-
const definedFn = createDefinedFunction(definition);
|
|
773
|
-
// Store in registry
|
|
774
|
-
functions.set(name, definedFn);
|
|
775
|
-
return definedFn;
|
|
776
|
-
}
|
|
777
|
-
/**
|
|
778
|
-
* Define functions - auto-define or use typed helpers
|
|
779
|
-
*/
|
|
780
|
-
export const define = Object.assign(autoDefineImpl, {
|
|
781
|
-
/**
|
|
782
|
-
* Define a code generation function
|
|
783
|
-
*/
|
|
784
|
-
code: (definition) => {
|
|
785
|
-
const fn = defineFunction({ type: 'code', ...definition });
|
|
786
|
-
functions.set(definition.name, fn);
|
|
787
|
-
return fn;
|
|
788
|
-
},
|
|
789
|
-
/**
|
|
790
|
-
* Define a generative function
|
|
791
|
-
*/
|
|
792
|
-
generative: (definition) => {
|
|
793
|
-
const fn = defineFunction({ type: 'generative', ...definition });
|
|
794
|
-
functions.set(definition.name, fn);
|
|
795
|
-
return fn;
|
|
796
|
-
},
|
|
797
|
-
/**
|
|
798
|
-
* Define an agentic function
|
|
799
|
-
*/
|
|
800
|
-
agentic: (definition) => {
|
|
801
|
-
const fn = defineFunction({ type: 'agentic', ...definition });
|
|
802
|
-
functions.set(definition.name, fn);
|
|
803
|
-
return fn;
|
|
804
|
-
},
|
|
805
|
-
/**
|
|
806
|
-
* Define a human-in-the-loop function
|
|
807
|
-
*/
|
|
808
|
-
human: (definition) => {
|
|
809
|
-
const fn = defineFunction({ type: 'human', ...definition });
|
|
810
|
-
functions.set(definition.name, fn);
|
|
811
|
-
return fn;
|
|
812
|
-
},
|
|
813
|
-
});
|
|
814
|
-
// ============================================================================
|
|
815
|
-
// AI() - Smart AI Client with Auto-Definition
|
|
816
|
-
// ============================================================================
|
|
817
|
-
/** Known built-in method names that should not be auto-defined */
|
|
818
|
-
const BUILTIN_METHODS = new Set([
|
|
819
|
-
'do', 'is', 'code', 'decide', 'diagram', 'generate', 'image', 'video', 'write', 'list', 'lists',
|
|
820
|
-
'functions', 'define', 'defineFunction', 'then', 'catch', 'finally',
|
|
821
|
-
]);
|
|
822
|
-
/**
|
|
823
|
-
* Create a smart AI client that auto-defines functions on first call
|
|
824
|
-
*
|
|
825
|
-
* @example
|
|
826
|
-
* ```ts
|
|
827
|
-
* const ai = AI()
|
|
828
|
-
*
|
|
829
|
-
* // First call - auto-defines the function
|
|
830
|
-
* const trip = await ai.planTrip({
|
|
831
|
-
* destination: 'Tokyo',
|
|
832
|
-
* dates: { start: '2024-03-01', end: '2024-03-10' },
|
|
833
|
-
* travelers: 2,
|
|
834
|
-
* })
|
|
835
|
-
*
|
|
836
|
-
* // Second call - uses cached definition (in-memory)
|
|
837
|
-
* const trip2 = await ai.planTrip({
|
|
838
|
-
* destination: 'Paris',
|
|
839
|
-
* dates: { start: '2024-06-01', end: '2024-06-07' },
|
|
840
|
-
* travelers: 4,
|
|
841
|
-
* })
|
|
842
|
-
*
|
|
843
|
-
* // Access registry and define
|
|
844
|
-
* console.log(ai.functions.list()) // ['planTrip']
|
|
845
|
-
* ai.define.generative({ name: 'summarize', ... })
|
|
846
|
-
* ```
|
|
847
|
-
*/
|
|
848
|
-
function createSmartAI() {
|
|
849
|
-
const base = {
|
|
850
|
-
functions,
|
|
851
|
-
define,
|
|
852
|
-
defineFunction,
|
|
853
|
-
};
|
|
854
|
-
return new Proxy(base, {
|
|
855
|
-
get(target, prop) {
|
|
856
|
-
// Return built-in properties
|
|
857
|
-
if (prop in target) {
|
|
858
|
-
return target[prop];
|
|
859
|
-
}
|
|
860
|
-
// Skip internal properties
|
|
861
|
-
if (typeof prop === 'symbol' || prop.startsWith('_') || BUILTIN_METHODS.has(prop)) {
|
|
862
|
-
return undefined;
|
|
863
|
-
}
|
|
864
|
-
// Return a function that auto-defines and calls
|
|
865
|
-
return async (args = {}) => {
|
|
866
|
-
// Check if function is already defined
|
|
867
|
-
let fn = functions.get(prop);
|
|
868
|
-
if (!fn) {
|
|
869
|
-
// Auto-define the function
|
|
870
|
-
fn = await define(prop, args);
|
|
871
|
-
}
|
|
872
|
-
// Call the function
|
|
873
|
-
return fn.call(args);
|
|
874
|
-
};
|
|
875
|
-
},
|
|
876
|
-
});
|
|
85
|
+
export function AI(schemas, defaultOptions) {
|
|
86
|
+
// Schema functions mode - create a function for each schema
|
|
87
|
+
return createSchemaFunctions(schemas, defaultOptions);
|
|
877
88
|
}
|
|
878
|
-
/**
|
|
879
|
-
* Default AI instance with auto-define capability
|
|
880
|
-
*
|
|
881
|
-
* @example
|
|
882
|
-
* ```ts
|
|
883
|
-
* import { ai } from 'ai-functions'
|
|
884
|
-
*
|
|
885
|
-
* // Auto-define and call
|
|
886
|
-
* const result = await ai.summarize({ text: 'Long article...' })
|
|
887
|
-
*
|
|
888
|
-
* // Access functions registry
|
|
889
|
-
* ai.functions.list()
|
|
890
|
-
*
|
|
891
|
-
* // Define explicitly
|
|
892
|
-
* ai.define.generative({ name: 'translate', ... })
|
|
893
|
-
* ```
|
|
894
|
-
*/
|
|
895
|
-
export const ai = createSmartAI();
|
|
896
89
|
//# sourceMappingURL=ai.js.map
|