ai-functions 2.1.1 → 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 -4
- package/CHANGELOG.md +68 -1
- package/README.md +397 -157
- package/dist/ai-promise.d.ts +50 -3
- package/dist/ai-promise.d.ts.map +1 -1
- package/dist/ai-promise.js +410 -51
- 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 +54 -837
- 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 +272 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +513 -0
- package/dist/budget.js.map +1 -0
- package/dist/cache.d.ts +295 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +433 -0
- package/dist/cache.js.map +1 -0
- package/dist/context.d.ts +42 -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 +10 -1
- 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 -22
- package/dist/generate.js.map +1 -1
- package/dist/index.d.ts +35 -20
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +89 -42
- 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 +368 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +646 -0
- package/dist/retry.js.map +1 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -10
- 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 +453 -0
- package/dist/tool-orchestration.d.ts.map +1 -0
- package/dist/tool-orchestration.js +763 -0
- package/dist/tool-orchestration.js.map +1 -0
- 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 +10 -6
- package/src/ai-promise.ts +528 -99
- package/src/ai-schemas.ts +122 -0
- package/src/ai.ts +69 -1153
- 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 +740 -0
- package/src/cache.ts +681 -0
- package/src/context.ts +122 -76
- package/src/digital-objects-registry.ts +750 -0
- package/src/errors.ts +37 -0
- package/src/eval/runner.ts +63 -38
- 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 -33
- package/src/index.ts +325 -49
- 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 +902 -0
- package/src/schema.ts +8 -17
- package/src/telemetry.ts +403 -0
- package/src/template.ts +8 -4
- package/src/tool-orchestration.ts +1173 -0
- 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/backward-compat.test.ts +147 -0
- package/test/batch-autosubmit-errors.test.ts +610 -0
- package/test/batch-blog-posts.test.ts +87 -129
- package/test/budget-tracking.test.ts +800 -0
- package/test/cache.test.ts +712 -0
- package/test/context-isolation.test.ts +687 -0
- 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/evals/deterministic.eval.test.ts +376 -0
- package/test/generate-core.test.ts +140 -229
- package/test/implicit-batch.test.ts +22 -65
- package/test/json-parse-error-handling.test.ts +463 -0
- package/test/retry-policy-integration.test.ts +117 -0
- package/test/retry.test.ts +1016 -0
- package/test/schema.test.ts +55 -19
- package/test/streaming.test.ts +316 -0
- package/test/template.test.ts +1164 -0
- package/test/tool-orchestration.test.ts +1040 -0
- package/test/wrap-for-v3.test.ts +612 -0
- package/vitest.config.js +6 -0
- package/vitest.config.ts +20 -0
- 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/src/ai.ts
CHANGED
|
@@ -1,112 +1,83 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* AI() and ai() - Core AI function constructors
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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`)
|
|
8
|
+
*
|
|
9
|
+
* All exports are maintained for backward compatibility.
|
|
6
10
|
*/
|
|
7
11
|
|
|
8
|
-
//
|
|
9
|
-
//
|
|
12
|
+
// ============================================================================
|
|
13
|
+
// Re-export from ai-schemas.ts - Schema-based AI functions
|
|
14
|
+
// ============================================================================
|
|
15
|
+
export {
|
|
16
|
+
createSchemaFunctions,
|
|
17
|
+
type AISchemaOptions,
|
|
18
|
+
type SchemaFunctions,
|
|
19
|
+
type InferSimpleSchemaResult,
|
|
20
|
+
} from './ai-schemas.js'
|
|
10
21
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
// ============================================================================
|
|
23
|
+
// Re-export from function-registry.ts - Function definition and registry
|
|
24
|
+
// ============================================================================
|
|
25
|
+
export {
|
|
26
|
+
defineFunction,
|
|
27
|
+
createDefinedFunction,
|
|
28
|
+
createFunctionRegistry,
|
|
29
|
+
functions,
|
|
30
|
+
resetGlobalRegistry,
|
|
31
|
+
convertArgsToJSONSchema,
|
|
32
|
+
fillTemplate,
|
|
33
|
+
generateCode,
|
|
34
|
+
} from './function-registry.js'
|
|
18
35
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
/** HTTP URL for RPC fallback */
|
|
26
|
-
httpUrl?: string
|
|
27
|
-
/** Authentication token */
|
|
28
|
-
token?: string
|
|
29
|
-
}
|
|
30
|
-
import { generateObject } from './generate.js'
|
|
31
|
-
import type { SimpleSchema } from './schema.js'
|
|
32
|
-
import type { LanguageModel } from 'ai'
|
|
33
|
-
import type {
|
|
34
|
-
AIClient,
|
|
35
|
-
AIFunctionDefinition,
|
|
36
|
-
AIGenerateOptions,
|
|
37
|
-
AIGenerateResult,
|
|
38
|
-
JSONSchema,
|
|
39
|
-
ImageOptions,
|
|
40
|
-
ImageResult,
|
|
41
|
-
VideoOptions,
|
|
42
|
-
VideoResult,
|
|
43
|
-
WriteOptions,
|
|
44
|
-
ListResult,
|
|
45
|
-
ListsResult,
|
|
46
|
-
FunctionDefinition,
|
|
47
|
-
DefinedFunction,
|
|
48
|
-
CodeFunctionDefinition,
|
|
49
|
-
CodeFunctionResult,
|
|
50
|
-
GenerativeFunctionDefinition,
|
|
51
|
-
AgenticFunctionDefinition,
|
|
52
|
-
HumanFunctionDefinition,
|
|
53
|
-
HumanChannel,
|
|
54
|
-
CodeLanguage,
|
|
55
|
-
FunctionRegistry,
|
|
56
|
-
AutoDefineResult
|
|
57
|
-
} from './types.js'
|
|
58
|
-
import { schema as convertSchema, type SimpleSchema as SimpleSchemaType } from './schema.js'
|
|
36
|
+
// ============================================================================
|
|
37
|
+
// Re-export from primitives.ts - Auto-define proxy functionality
|
|
38
|
+
// (formerly in ai-proxy.ts; inlined to give property-access tracking a single
|
|
39
|
+
// owner in ai-promise.ts)
|
|
40
|
+
// ============================================================================
|
|
41
|
+
export { define, createSmartAI, aiProxy as ai, type AIProxy } from './primitives.js'
|
|
59
42
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
export interface AIClientOptions extends RPCSessionOptions {
|
|
64
|
-
/** Default model to use */
|
|
65
|
-
model?: string
|
|
66
|
-
/** Default temperature */
|
|
67
|
-
temperature?: number
|
|
68
|
-
/** Default max tokens */
|
|
69
|
-
maxTokens?: number
|
|
70
|
-
/** Custom functions available to the AI */
|
|
71
|
-
functions?: AIFunctionDefinition[]
|
|
72
|
-
}
|
|
43
|
+
// ============================================================================
|
|
44
|
+
// Local exports - withTemplate utility
|
|
45
|
+
// ============================================================================
|
|
73
46
|
|
|
74
47
|
/**
|
|
75
|
-
*
|
|
48
|
+
* Helper to create a function that supports both regular calls and tagged template literals
|
|
49
|
+
* @example
|
|
50
|
+
* const fn = withTemplate((prompt) => doSomething(prompt))
|
|
51
|
+
* fn('hello') // regular call
|
|
52
|
+
* fn`hello ${name}` // tagged template literal
|
|
76
53
|
*/
|
|
77
|
-
export
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
/** Max retries on failure */
|
|
97
|
-
maxRetries?: number
|
|
98
|
-
/** Abort signal */
|
|
99
|
-
abortSignal?: AbortSignal
|
|
100
|
-
/** Custom headers */
|
|
101
|
-
headers?: Record<string, string>
|
|
54
|
+
export function withTemplate<TArgs extends unknown[], TReturn>(
|
|
55
|
+
fn: (prompt: string, ...args: TArgs) => TReturn
|
|
56
|
+
): ((prompt: string, ...args: TArgs) => TReturn) &
|
|
57
|
+
((strings: TemplateStringsArray, ...values: unknown[]) => TReturn) {
|
|
58
|
+
return function (promptOrStrings: string | TemplateStringsArray, ...args: unknown[]): TReturn {
|
|
59
|
+
if (Array.isArray(promptOrStrings) && 'raw' in promptOrStrings) {
|
|
60
|
+
// Tagged template literal call - pass empty args for optional params
|
|
61
|
+
const strings = promptOrStrings as TemplateStringsArray
|
|
62
|
+
const values = args
|
|
63
|
+
const prompt = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '')
|
|
64
|
+
// Cast required: When called as a tagged template, additional args aren't provided.
|
|
65
|
+
// TArgs represents optional parameters that default to empty. TypeScript can't express
|
|
66
|
+
// that TArgs can be satisfied by an empty array when all elements are optional.
|
|
67
|
+
return fn(prompt, ...([] as unknown as TArgs))
|
|
68
|
+
}
|
|
69
|
+
// Regular function call
|
|
70
|
+
return fn(promptOrStrings as string, ...(args as TArgs))
|
|
71
|
+
} as ((prompt: string, ...args: TArgs) => TReturn) &
|
|
72
|
+
((strings: TemplateStringsArray, ...values: unknown[]) => TReturn)
|
|
102
73
|
}
|
|
103
74
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
75
|
+
// ============================================================================
|
|
76
|
+
// AI() - Main entry point (schema-based functions)
|
|
77
|
+
// ============================================================================
|
|
78
|
+
|
|
79
|
+
import type { SimpleSchema } from './schema.js'
|
|
80
|
+
import { createSchemaFunctions, type AISchemaOptions, type SchemaFunctions } from './ai-schemas.js'
|
|
110
81
|
|
|
111
82
|
/**
|
|
112
83
|
* Create AI functions from schemas
|
|
@@ -144,1062 +115,7 @@ type SchemaFunctions<T extends Record<string, SimpleSchema>> = {
|
|
|
144
115
|
export function AI<T extends Record<string, SimpleSchema>>(
|
|
145
116
|
schemas: T,
|
|
146
117
|
defaultOptions?: AISchemaOptions
|
|
147
|
-
): SchemaFunctions<T>
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Create an AI RPC client instance
|
|
151
|
-
*
|
|
152
|
-
* @example
|
|
153
|
-
* ```ts
|
|
154
|
-
* // Connect to remote AI service
|
|
155
|
-
* const ai = AI({ wsUrl: 'wss://ai.example.com/rpc' })
|
|
156
|
-
*
|
|
157
|
-
* // Use promise pipelining - single round trip!
|
|
158
|
-
* const result = ai.generate({ prompt: 'Hello' })
|
|
159
|
-
* const upper = result.text.map(t => t.toUpperCase())
|
|
160
|
-
* console.log(await upper)
|
|
161
|
-
*
|
|
162
|
-
* // Dynamic function calling
|
|
163
|
-
* const summary = await ai.summarize({ text: longText })
|
|
164
|
-
* ```
|
|
165
|
-
*/
|
|
166
|
-
export function AI(options: AIClientOptions): AIClient & Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
167
|
-
|
|
168
|
-
export function AI<T extends Record<string, SimpleSchema>>(
|
|
169
|
-
schemasOrOptions: T | AIClientOptions,
|
|
170
|
-
defaultOptions?: AISchemaOptions
|
|
171
|
-
): SchemaFunctions<T> | (AIClient & Record<string, (...args: unknown[]) => Promise<unknown>>) {
|
|
172
|
-
// Check if this is RPC client mode
|
|
173
|
-
if (isAIClientOptions(schemasOrOptions)) {
|
|
174
|
-
// TODO: Re-enable RPC client when rpc.do is published
|
|
175
|
-
// const { model, temperature, maxTokens, functions, wsUrl, httpUrl, token } = schemasOrOptions
|
|
176
|
-
//
|
|
177
|
-
// // Create transport based on provided URLs
|
|
178
|
-
// let transport
|
|
179
|
-
// if (wsUrl) {
|
|
180
|
-
// transport = ws(wsUrl, token ? () => token : undefined)
|
|
181
|
-
// } else if (httpUrl) {
|
|
182
|
-
// transport = http(httpUrl, token ? () => token : undefined)
|
|
183
|
-
// } else {
|
|
184
|
-
// throw new Error('AI client requires either wsUrl or httpUrl')
|
|
185
|
-
// }
|
|
186
|
-
//
|
|
187
|
-
// // Create RPC client
|
|
188
|
-
// const rpcClient = RPC<AIClient>(transport)
|
|
189
|
-
//
|
|
190
|
-
// // Create a proxy that handles both defined methods and dynamic function calls
|
|
191
|
-
// return new Proxy(rpcClient, {
|
|
192
|
-
// get(target, prop: string) {
|
|
193
|
-
// // Return existing methods
|
|
194
|
-
// if (prop in target) {
|
|
195
|
-
// return (target as unknown as Record<string, unknown>)[prop]
|
|
196
|
-
// }
|
|
197
|
-
//
|
|
198
|
-
// // Handle dynamic function calls (ai.functionName())
|
|
199
|
-
// return (...args: unknown[]) => {
|
|
200
|
-
// const client = target as unknown as AIClient
|
|
201
|
-
// return client.do(prop, args.length === 1 ? args[0] : args)
|
|
202
|
-
// }
|
|
203
|
-
// }
|
|
204
|
-
// }) as AIClient & Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
205
|
-
throw new Error('RPC client mode requires rpc.do package (not yet published). Use schema-based mode instead.')
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Schema functions mode - create a function for each schema
|
|
209
|
-
return createSchemaFunctions(schemasOrOptions as Record<string, SimpleSchema>, defaultOptions) as SchemaFunctions<T>
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Check if options are AI client options vs schemas
|
|
214
|
-
*/
|
|
215
|
-
function isAIClientOptions(value: unknown): value is AIClientOptions {
|
|
216
|
-
if (typeof value !== 'object' || value === null) return false
|
|
217
|
-
const obj = value as Record<string, unknown>
|
|
218
|
-
return 'wsUrl' in obj || 'httpUrl' in obj || 'functions' in obj
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Infer result type from simple schema
|
|
223
|
-
*/
|
|
224
|
-
type InferSimpleSchemaResult<T> = T extends string
|
|
225
|
-
? string
|
|
226
|
-
: T extends [string]
|
|
227
|
-
? string[]
|
|
228
|
-
: T extends { [K: string]: SimpleSchema }
|
|
229
|
-
? { [K in keyof T]: InferSimpleSchemaResult<T[K]> }
|
|
230
|
-
: unknown
|
|
231
|
-
|
|
232
|
-
/**
|
|
233
|
-
* Create schema-based functions from a map of schemas
|
|
234
|
-
*/
|
|
235
|
-
function createSchemaFunctions<T extends Record<string, SimpleSchema>>(
|
|
236
|
-
schemas: T,
|
|
237
|
-
defaultOptions: AISchemaOptions = {}
|
|
238
118
|
): SchemaFunctions<T> {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
for (const [name, schema] of Object.entries(schemas)) {
|
|
242
|
-
functions[name] = async (prompt?: string, options?: AISchemaOptions) => {
|
|
243
|
-
const mergedOptions = { ...defaultOptions, ...options }
|
|
244
|
-
const { model = 'sonnet', system, ...rest } = mergedOptions
|
|
245
|
-
|
|
246
|
-
// Build prompt from schema descriptions if none provided
|
|
247
|
-
const schemaPrompt = prompt || buildPromptFromSchema(schema)
|
|
248
|
-
|
|
249
|
-
const result = await generateObject({
|
|
250
|
-
model,
|
|
251
|
-
schema,
|
|
252
|
-
prompt: schemaPrompt,
|
|
253
|
-
system,
|
|
254
|
-
...rest,
|
|
255
|
-
})
|
|
256
|
-
|
|
257
|
-
return result.object
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
return functions as SchemaFunctions<T>
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* Build a prompt by extracting descriptions from the schema
|
|
266
|
-
*/
|
|
267
|
-
function buildPromptFromSchema(schema: SimpleSchema, path = ''): string {
|
|
268
|
-
if (typeof schema === 'string') {
|
|
269
|
-
return schema
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
if (Array.isArray(schema)) {
|
|
273
|
-
return schema[0] as string || 'Generate items'
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
if (typeof schema === 'object' && schema !== null) {
|
|
277
|
-
const descriptions: string[] = []
|
|
278
|
-
for (const [key, value] of Object.entries(schema)) {
|
|
279
|
-
const subPrompt = buildPromptFromSchema(value as SimpleSchema, path ? `${path}.${key}` : key)
|
|
280
|
-
if (subPrompt) {
|
|
281
|
-
descriptions.push(`${key}: ${subPrompt}`)
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return descriptions.length > 0 ? `Generate the following:\n${descriptions.join('\n')}` : ''
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
return ''
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* Create a defined function from a function definition
|
|
292
|
-
*/
|
|
293
|
-
function createDefinedFunction<TOutput, TInput>(
|
|
294
|
-
definition: FunctionDefinition<TOutput, TInput>
|
|
295
|
-
): DefinedFunction<TOutput, TInput> {
|
|
296
|
-
const call = async (args: TInput): Promise<TOutput> => {
|
|
297
|
-
switch (definition.type) {
|
|
298
|
-
case 'code':
|
|
299
|
-
return executeCodeFunction(definition, args) as Promise<TOutput>
|
|
300
|
-
case 'generative':
|
|
301
|
-
return executeGenerativeFunction(definition, args) as Promise<TOutput>
|
|
302
|
-
case 'agentic':
|
|
303
|
-
return executeAgenticFunction(definition, args) as Promise<TOutput>
|
|
304
|
-
case 'human':
|
|
305
|
-
return executeHumanFunction(definition, args) as Promise<TOutput>
|
|
306
|
-
default:
|
|
307
|
-
throw new Error(`Unknown function type: ${(definition as FunctionDefinition).type}`)
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
const asTool = (): AIFunctionDefinition<TOutput, TInput> => {
|
|
312
|
-
return {
|
|
313
|
-
name: definition.name,
|
|
314
|
-
description: definition.description || `Execute ${definition.name}`,
|
|
315
|
-
parameters: convertArgsToJSONSchema(definition.args),
|
|
316
|
-
handler: call,
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
return { definition, call, asTool }
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
/**
|
|
324
|
-
* Convert args schema to JSON Schema
|
|
325
|
-
*/
|
|
326
|
-
function convertArgsToJSONSchema(args: unknown): JSONSchema {
|
|
327
|
-
// If it's already a JSON schema-like object
|
|
328
|
-
if (typeof args === 'object' && args !== null && 'type' in args) {
|
|
329
|
-
return args as JSONSchema
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// Convert SimpleSchema to JSON Schema
|
|
333
|
-
const properties: Record<string, JSONSchema> = {}
|
|
334
|
-
const required: string[] = []
|
|
335
|
-
|
|
336
|
-
if (typeof args === 'object' && args !== null) {
|
|
337
|
-
for (const [key, value] of Object.entries(args as Record<string, unknown>)) {
|
|
338
|
-
required.push(key) // All properties required for cross-provider compatibility
|
|
339
|
-
properties[key] = convertValueToJSONSchema(value)
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
return {
|
|
344
|
-
type: 'object',
|
|
345
|
-
properties,
|
|
346
|
-
required,
|
|
347
|
-
additionalProperties: false, // Required for OpenAI compatibility
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/**
|
|
352
|
-
* Convert a single value to JSON Schema
|
|
353
|
-
*/
|
|
354
|
-
function convertValueToJSONSchema(value: unknown): JSONSchema {
|
|
355
|
-
if (typeof value === 'string') {
|
|
356
|
-
// Check for type hints: 'description (number)', 'description (boolean)', etc.
|
|
357
|
-
const typeMatch = value.match(/^(.+?)\s*\((number|boolean|integer|date)\)$/i)
|
|
358
|
-
if (typeMatch) {
|
|
359
|
-
const description = typeMatch[1]!
|
|
360
|
-
const type = typeMatch[2]!
|
|
361
|
-
switch (type.toLowerCase()) {
|
|
362
|
-
case 'number':
|
|
363
|
-
return { type: 'number', description: description.trim() }
|
|
364
|
-
case 'integer':
|
|
365
|
-
return { type: 'integer', description: description.trim() }
|
|
366
|
-
case 'boolean':
|
|
367
|
-
return { type: 'boolean', description: description.trim() }
|
|
368
|
-
case 'date':
|
|
369
|
-
return { type: 'string', format: 'date-time', description: description.trim() }
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
// Check for enum: 'option1 | option2 | option3'
|
|
374
|
-
if (value.includes(' | ')) {
|
|
375
|
-
const options = value.split(' | ').map(s => s.trim())
|
|
376
|
-
return { type: 'string', enum: options }
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
return { type: 'string', description: value }
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
if (Array.isArray(value) && value.length === 1) {
|
|
383
|
-
const [desc] = value
|
|
384
|
-
if (typeof desc === 'string') {
|
|
385
|
-
return { type: 'array', items: { type: 'string' }, description: desc }
|
|
386
|
-
}
|
|
387
|
-
if (typeof desc === 'number') {
|
|
388
|
-
return { type: 'array', items: { type: 'number' } }
|
|
389
|
-
}
|
|
390
|
-
return { type: 'array', items: convertValueToJSONSchema(desc) }
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
if (typeof value === 'object' && value !== null) {
|
|
394
|
-
return convertArgsToJSONSchema(value)
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
return { type: 'string' }
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Fill template with values
|
|
402
|
-
*/
|
|
403
|
-
function fillTemplate(template: string, args: Record<string, unknown>): string {
|
|
404
|
-
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => String(args[key] ?? ''))
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
/**
|
|
408
|
-
* Execute a code function - generates code with tests and examples
|
|
409
|
-
*/
|
|
410
|
-
async function executeCodeFunction<TInput>(
|
|
411
|
-
definition: CodeFunctionDefinition<unknown, TInput>,
|
|
412
|
-
args: TInput
|
|
413
|
-
): Promise<CodeFunctionResult> {
|
|
414
|
-
const { name, description, language = 'typescript', instructions, includeTests = true, includeExamples = true } = definition
|
|
415
|
-
|
|
416
|
-
const argsDescription = JSON.stringify(args, null, 2)
|
|
417
|
-
|
|
418
|
-
const result = await generateObject({
|
|
419
|
-
model: 'sonnet',
|
|
420
|
-
schema: {
|
|
421
|
-
code: 'The complete implementation code with JSDoc comments',
|
|
422
|
-
tests: includeTests ? 'Vitest test code for the implementation' : undefined,
|
|
423
|
-
examples: includeExamples ? 'Example usage code' : undefined,
|
|
424
|
-
documentation: 'JSDoc or equivalent documentation string',
|
|
425
|
-
},
|
|
426
|
-
system: `You are an expert ${language} developer. Generate clean, well-documented, production-ready code.`,
|
|
427
|
-
prompt: `Generate a ${language} function with the following specification:
|
|
428
|
-
|
|
429
|
-
Name: ${name}
|
|
430
|
-
Description: ${description || 'No description provided'}
|
|
431
|
-
Arguments: ${argsDescription}
|
|
432
|
-
Return Type: ${JSON.stringify(definition.returnType)}
|
|
433
|
-
|
|
434
|
-
${instructions ? `Additional Instructions: ${instructions}` : ''}
|
|
435
|
-
|
|
436
|
-
Requirements:
|
|
437
|
-
- Include comprehensive JSDoc comments
|
|
438
|
-
- Follow best practices for ${language}
|
|
439
|
-
- Handle edge cases appropriately
|
|
440
|
-
${includeTests ? '- Include vitest tests that cover main functionality and edge cases' : ''}
|
|
441
|
-
${includeExamples ? '- Include example usage showing how to call the function' : ''}`,
|
|
442
|
-
})
|
|
443
|
-
|
|
444
|
-
const obj = result.object as { code: string; tests?: string; examples?: string; documentation: string }
|
|
445
|
-
return {
|
|
446
|
-
code: obj.code,
|
|
447
|
-
tests: obj.tests,
|
|
448
|
-
examples: obj.examples,
|
|
449
|
-
language,
|
|
450
|
-
documentation: obj.documentation,
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
/**
|
|
455
|
-
* Execute a generative function - uses AI to generate content
|
|
456
|
-
*/
|
|
457
|
-
async function executeGenerativeFunction<TOutput, TInput>(
|
|
458
|
-
definition: GenerativeFunctionDefinition<TOutput, TInput>,
|
|
459
|
-
args: TInput
|
|
460
|
-
): Promise<TOutput> {
|
|
461
|
-
const { output, system, promptTemplate, model = 'sonnet', temperature, returnType } = definition
|
|
462
|
-
|
|
463
|
-
const prompt = promptTemplate
|
|
464
|
-
? fillTemplate(promptTemplate, args as Record<string, unknown>)
|
|
465
|
-
: JSON.stringify(args)
|
|
466
|
-
|
|
467
|
-
switch (output) {
|
|
468
|
-
case 'string': {
|
|
469
|
-
const result = await generateObject({
|
|
470
|
-
model,
|
|
471
|
-
schema: { text: 'The generated text response' },
|
|
472
|
-
system,
|
|
473
|
-
prompt,
|
|
474
|
-
temperature,
|
|
475
|
-
})
|
|
476
|
-
return (result.object as { text: string }).text as TOutput
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
case 'object': {
|
|
480
|
-
const objectSchema = returnType || { result: 'The generated result' }
|
|
481
|
-
const result = await generateObject({
|
|
482
|
-
model,
|
|
483
|
-
schema: objectSchema as SimpleSchemaType,
|
|
484
|
-
system,
|
|
485
|
-
prompt,
|
|
486
|
-
temperature,
|
|
487
|
-
})
|
|
488
|
-
return result.object as TOutput
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
case 'image': {
|
|
492
|
-
const client = getDefaultAIClient()
|
|
493
|
-
return client.image(prompt) as unknown as Promise<TOutput>
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
case 'video': {
|
|
497
|
-
const client = getDefaultAIClient()
|
|
498
|
-
return client.video(prompt) as unknown as Promise<TOutput>
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
default:
|
|
502
|
-
throw new Error(`Unknown output type: ${output}`)
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
/**
|
|
507
|
-
* Execute an agentic function - runs in a loop with tools
|
|
508
|
-
*/
|
|
509
|
-
async function executeAgenticFunction<TOutput, TInput>(
|
|
510
|
-
definition: AgenticFunctionDefinition<TOutput, TInput>,
|
|
511
|
-
args: TInput
|
|
512
|
-
): Promise<TOutput> {
|
|
513
|
-
const { instructions, promptTemplate, tools = [], maxIterations = 10, model = 'sonnet', returnType } = definition
|
|
514
|
-
|
|
515
|
-
const prompt = promptTemplate
|
|
516
|
-
? fillTemplate(promptTemplate, args as Record<string, unknown>)
|
|
517
|
-
: JSON.stringify(args)
|
|
518
|
-
|
|
519
|
-
// Build system prompt with tool descriptions
|
|
520
|
-
const toolDescriptions = tools.map(t => `- ${t.name}: ${t.description}`).join('\n')
|
|
521
|
-
const systemPrompt = `${instructions}
|
|
522
|
-
|
|
523
|
-
Available tools:
|
|
524
|
-
${toolDescriptions || 'No tools available'}
|
|
525
|
-
|
|
526
|
-
Work step by step to accomplish the task. When you have completed the task, provide your final result.`
|
|
527
|
-
|
|
528
|
-
let iteration = 0
|
|
529
|
-
const toolResults: unknown[] = []
|
|
530
|
-
|
|
531
|
-
// Simple agent loop
|
|
532
|
-
while (iteration < maxIterations) {
|
|
533
|
-
iteration++
|
|
534
|
-
|
|
535
|
-
const result = await generateObject({
|
|
536
|
-
model,
|
|
537
|
-
schema: {
|
|
538
|
-
thinking: 'Your step-by-step reasoning',
|
|
539
|
-
toolCall: {
|
|
540
|
-
name: 'Tool to call (or "done" if finished)',
|
|
541
|
-
arguments: 'Arguments for the tool as JSON string',
|
|
542
|
-
},
|
|
543
|
-
finalResult: returnType || 'The final result if done',
|
|
544
|
-
},
|
|
545
|
-
system: systemPrompt,
|
|
546
|
-
prompt: `Task: ${prompt}
|
|
547
|
-
|
|
548
|
-
Previous tool results:
|
|
549
|
-
${toolResults.map((r, i) => `Step ${i + 1}: ${JSON.stringify(r)}`).join('\n') || 'None yet'}
|
|
550
|
-
|
|
551
|
-
What is your next step?`,
|
|
552
|
-
})
|
|
553
|
-
|
|
554
|
-
const response = result.object as {
|
|
555
|
-
thinking: string
|
|
556
|
-
toolCall: { name: string; arguments: string }
|
|
557
|
-
finalResult: unknown
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
if (response.toolCall.name === 'done' || response.finalResult) {
|
|
561
|
-
return response.finalResult as TOutput
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
// Execute tool call
|
|
565
|
-
const tool = tools.find(t => t.name === response.toolCall.name)
|
|
566
|
-
if (tool) {
|
|
567
|
-
const toolArgs = JSON.parse(response.toolCall.arguments || '{}')
|
|
568
|
-
const toolResult = await tool.handler(toolArgs)
|
|
569
|
-
toolResults.push({ tool: response.toolCall.name, result: toolResult })
|
|
570
|
-
} else {
|
|
571
|
-
toolResults.push({ error: `Tool not found: ${response.toolCall.name}` })
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
throw new Error(`Agent exceeded maximum iterations (${maxIterations})`)
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* Execute a human function - generates UI and waits for human input
|
|
580
|
-
*
|
|
581
|
-
* **Note: This function currently returns placeholder/mock data.**
|
|
582
|
-
*
|
|
583
|
-
* In a complete implementation, this function would:
|
|
584
|
-
* 1. Generate channel-specific UI (Slack blocks, email templates, web forms, etc.)
|
|
585
|
-
* 2. Send the generated UI to the appropriate channel
|
|
586
|
-
* 3. Wait for human response with optional timeout
|
|
587
|
-
* 4. Validate and return the human's response
|
|
588
|
-
*
|
|
589
|
-
* The current implementation generates the UI artifacts but returns a pending
|
|
590
|
-
* placeholder instead of actually sending to the channel and waiting for response.
|
|
591
|
-
* This allows testing the UI generation without requiring actual channel integrations.
|
|
592
|
-
*
|
|
593
|
-
* @param definition - The human function definition with channel and instructions
|
|
594
|
-
* @param args - Arguments to pass to the function
|
|
595
|
-
* @returns A placeholder result with `_pending: true` and generated artifacts
|
|
596
|
-
*
|
|
597
|
-
* @example
|
|
598
|
-
* ```ts
|
|
599
|
-
* // The result will be a placeholder, not an actual human response:
|
|
600
|
-
* // {
|
|
601
|
-
* // _pending: true,
|
|
602
|
-
* // channel: 'workspace',
|
|
603
|
-
* // artifacts: { ... generated UI ... },
|
|
604
|
-
* // expectedResponseType: { approved: boolean }
|
|
605
|
-
* // }
|
|
606
|
-
* ```
|
|
607
|
-
*/
|
|
608
|
-
async function executeHumanFunction<TOutput, TInput>(
|
|
609
|
-
definition: HumanFunctionDefinition<TOutput, TInput>,
|
|
610
|
-
args: TInput
|
|
611
|
-
): Promise<TOutput> {
|
|
612
|
-
const { channel, instructions, promptTemplate, returnType } = definition
|
|
613
|
-
|
|
614
|
-
const prompt = promptTemplate
|
|
615
|
-
? fillTemplate(promptTemplate, args as Record<string, unknown>)
|
|
616
|
-
: JSON.stringify(args)
|
|
617
|
-
|
|
618
|
-
// Generate channel-specific UI
|
|
619
|
-
const uiSchema: Record<string, SimpleSchemaType> = {
|
|
620
|
-
// New HumanChannel types
|
|
621
|
-
chat: {
|
|
622
|
-
message: 'Chat message to send',
|
|
623
|
-
options: ['Response options if applicable'],
|
|
624
|
-
},
|
|
625
|
-
email: {
|
|
626
|
-
subject: 'Email subject',
|
|
627
|
-
html: 'Email HTML body',
|
|
628
|
-
text: 'Plain text fallback',
|
|
629
|
-
},
|
|
630
|
-
phone: {
|
|
631
|
-
script: 'Phone call script',
|
|
632
|
-
keyPoints: ['Key points to cover'],
|
|
633
|
-
},
|
|
634
|
-
sms: {
|
|
635
|
-
text: 'SMS message text (max 160 chars)',
|
|
636
|
-
},
|
|
637
|
-
workspace: {
|
|
638
|
-
blocks: ['Workspace/Slack BlockKit blocks as JSON array'],
|
|
639
|
-
text: 'Plain text fallback',
|
|
640
|
-
},
|
|
641
|
-
web: {
|
|
642
|
-
component: 'React component code for the form',
|
|
643
|
-
schema: 'JSON schema for the form fields',
|
|
644
|
-
},
|
|
645
|
-
// Legacy fallback
|
|
646
|
-
custom: {
|
|
647
|
-
data: 'Structured data for custom implementation',
|
|
648
|
-
instructions: 'Instructions for the human',
|
|
649
|
-
},
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
const result = await generateObject({
|
|
653
|
-
model: 'sonnet',
|
|
654
|
-
schema: uiSchema[channel] ?? uiSchema.custom,
|
|
655
|
-
system: `Generate ${channel} UI/content for a human-in-the-loop task.`,
|
|
656
|
-
prompt: `Task: ${instructions}
|
|
657
|
-
|
|
658
|
-
Input data:
|
|
659
|
-
${prompt}
|
|
660
|
-
|
|
661
|
-
Expected response format:
|
|
662
|
-
${JSON.stringify(returnType)}
|
|
663
|
-
|
|
664
|
-
Generate the appropriate ${channel} UI/content to collect this response from a human.`,
|
|
665
|
-
})
|
|
666
|
-
|
|
667
|
-
// NOTE: This is a placeholder implementation.
|
|
668
|
-
// In a real implementation, this would:
|
|
669
|
-
// 1. Send the generated UI to the appropriate channel (Slack, email, etc.)
|
|
670
|
-
// 2. Wait for human response with optional timeout
|
|
671
|
-
// 3. Return the validated response
|
|
672
|
-
//
|
|
673
|
-
// Current behavior: Returns generated artifacts as a pending placeholder
|
|
674
|
-
return {
|
|
675
|
-
_pending: true,
|
|
676
|
-
channel,
|
|
677
|
-
artifacts: result.object,
|
|
678
|
-
expectedResponseType: returnType,
|
|
679
|
-
} as unknown as TOutput
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
/**
|
|
683
|
-
* Helper to create a function that supports both regular calls and tagged template literals
|
|
684
|
-
* @example
|
|
685
|
-
* const fn = withTemplate((prompt) => doSomething(prompt))
|
|
686
|
-
* fn('hello') // regular call
|
|
687
|
-
* fn`hello ${name}` // tagged template literal
|
|
688
|
-
*/
|
|
689
|
-
export function withTemplate<TArgs extends unknown[], TReturn>(
|
|
690
|
-
fn: (prompt: string, ...args: TArgs) => TReturn
|
|
691
|
-
): ((prompt: string, ...args: TArgs) => TReturn) & ((strings: TemplateStringsArray, ...values: unknown[]) => TReturn) {
|
|
692
|
-
return function (promptOrStrings: string | TemplateStringsArray, ...args: unknown[]): TReturn {
|
|
693
|
-
if (Array.isArray(promptOrStrings) && 'raw' in promptOrStrings) {
|
|
694
|
-
// Tagged template literal call - pass empty args for optional params
|
|
695
|
-
const strings = promptOrStrings as TemplateStringsArray
|
|
696
|
-
const values = args
|
|
697
|
-
const prompt = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ''), '')
|
|
698
|
-
return fn(prompt, ...([] as unknown as TArgs))
|
|
699
|
-
}
|
|
700
|
-
// Regular function call
|
|
701
|
-
return fn(promptOrStrings as string, ...(args as TArgs))
|
|
702
|
-
} as ((prompt: string, ...args: TArgs) => TReturn) & ((strings: TemplateStringsArray, ...values: unknown[]) => TReturn)
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
// Default client management
|
|
706
|
-
let defaultClient: AIClient | null = null
|
|
707
|
-
|
|
708
|
-
/**
|
|
709
|
-
* Configure the default AI client
|
|
710
|
-
*/
|
|
711
|
-
export function configureAI(options: AIClientOptions): void {
|
|
712
|
-
defaultClient = AI(options) as AIClient
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
/**
|
|
716
|
-
* Get the default AI client, throwing if not configured
|
|
717
|
-
*/
|
|
718
|
-
function getDefaultAIClient(): AIClient {
|
|
719
|
-
if (!defaultClient) {
|
|
720
|
-
// Try to auto-configure from environment
|
|
721
|
-
const wsUrl = typeof process !== 'undefined' ? process.env?.AI_WS_URL : undefined
|
|
722
|
-
const httpUrl = typeof process !== 'undefined' ? process.env?.AI_HTTP_URL : undefined
|
|
723
|
-
|
|
724
|
-
if (wsUrl) {
|
|
725
|
-
defaultClient = AI({ wsUrl } as AIClientOptions) as unknown as AIClient
|
|
726
|
-
} else if (httpUrl) {
|
|
727
|
-
defaultClient = AI({ httpUrl } as AIClientOptions) as unknown as AIClient
|
|
728
|
-
} else {
|
|
729
|
-
throw new Error(
|
|
730
|
-
'AI client not configured. Call configureAI() first or set AI_WS_URL/AI_HTTP_URL environment variables.'
|
|
731
|
-
)
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
return defaultClient
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
/**
|
|
738
|
-
* Base class for implementing AI services
|
|
739
|
-
*
|
|
740
|
-
* Extend this class to create your own AI service implementation.
|
|
741
|
-
*
|
|
742
|
-
* @example
|
|
743
|
-
* ```ts
|
|
744
|
-
* class MyAIService extends AIServiceTarget {
|
|
745
|
-
* async generate(options: AIGenerateOptions): Promise<AIGenerateResult> {
|
|
746
|
-
* // Your implementation
|
|
747
|
-
* }
|
|
748
|
-
* }
|
|
749
|
-
* ```
|
|
750
|
-
*/
|
|
751
|
-
export abstract class AIServiceTarget extends RpcTarget implements AIClient {
|
|
752
|
-
abstract generate(options: AIGenerateOptions): Promise<AIGenerateResult>
|
|
753
|
-
abstract do(action: string, context?: unknown): Promise<unknown>
|
|
754
|
-
abstract is(value: unknown, type: string | JSONSchema): Promise<boolean>
|
|
755
|
-
abstract code(prompt: string, language?: string): Promise<string>
|
|
756
|
-
abstract decide<T extends string>(options: T[], context?: string): Promise<T>
|
|
757
|
-
abstract diagram(description: string, format?: 'mermaid' | 'svg' | 'ascii'): Promise<string>
|
|
758
|
-
abstract image(prompt: string, options?: ImageOptions): Promise<ImageResult>
|
|
759
|
-
abstract video(prompt: string, options?: VideoOptions): Promise<VideoResult>
|
|
760
|
-
abstract write(prompt: string, options?: WriteOptions): Promise<string>
|
|
761
|
-
abstract list(prompt: string): Promise<ListResult>
|
|
762
|
-
abstract lists(prompt: string): Promise<ListsResult>
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
/**
|
|
766
|
-
* Standalone function for defining AI functions
|
|
767
|
-
*
|
|
768
|
-
* @example
|
|
769
|
-
* ```ts
|
|
770
|
-
* import { defineFunction } from 'ai-functions'
|
|
771
|
-
*
|
|
772
|
-
* const summarize = defineFunction({
|
|
773
|
-
* type: 'generative',
|
|
774
|
-
* name: 'summarize',
|
|
775
|
-
* args: { text: 'Text to summarize' },
|
|
776
|
-
* output: 'string',
|
|
777
|
-
* promptTemplate: 'Summarize: {{text}}',
|
|
778
|
-
* })
|
|
779
|
-
*
|
|
780
|
-
* const result = await summarize.call({ text: 'Long article...' })
|
|
781
|
-
* ```
|
|
782
|
-
*/
|
|
783
|
-
export function defineFunction<TOutput, TInput>(
|
|
784
|
-
definition: FunctionDefinition<TOutput, TInput>
|
|
785
|
-
): DefinedFunction<TOutput, TInput> {
|
|
786
|
-
return createDefinedFunction(definition)
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
// ============================================================================
|
|
790
|
-
// Function Registry
|
|
791
|
-
// ============================================================================
|
|
792
|
-
|
|
793
|
-
/**
|
|
794
|
-
* In-memory function registry
|
|
795
|
-
*/
|
|
796
|
-
class InMemoryFunctionRegistry implements FunctionRegistry {
|
|
797
|
-
private functions = new Map<string, DefinedFunction>()
|
|
798
|
-
|
|
799
|
-
get(name: string): DefinedFunction | undefined {
|
|
800
|
-
return this.functions.get(name)
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
set(name: string, fn: DefinedFunction): void {
|
|
804
|
-
this.functions.set(name, fn)
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
has(name: string): boolean {
|
|
808
|
-
return this.functions.has(name)
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
list(): string[] {
|
|
812
|
-
return Array.from(this.functions.keys())
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
delete(name: string): boolean {
|
|
816
|
-
return this.functions.delete(name)
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
clear(): void {
|
|
820
|
-
this.functions.clear()
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
/**
|
|
825
|
-
* Global function registry
|
|
826
|
-
*
|
|
827
|
-
* Note: This is in-memory only. For persistence, use mdxai or mdxdb packages.
|
|
828
|
-
*/
|
|
829
|
-
export const functions: FunctionRegistry = new InMemoryFunctionRegistry()
|
|
830
|
-
|
|
831
|
-
// ============================================================================
|
|
832
|
-
// Auto-Define Functions
|
|
833
|
-
// ============================================================================
|
|
834
|
-
|
|
835
|
-
/**
|
|
836
|
-
* Analyze a function call and determine what type of function it should be
|
|
837
|
-
*/
|
|
838
|
-
async function analyzeFunction(
|
|
839
|
-
name: string,
|
|
840
|
-
args: Record<string, unknown>
|
|
841
|
-
): Promise<AutoDefineResult> {
|
|
842
|
-
// Convert camelCase/snake_case to readable name
|
|
843
|
-
const readableName = name
|
|
844
|
-
.replace(/([A-Z])/g, ' $1')
|
|
845
|
-
.replace(/_/g, ' ')
|
|
846
|
-
.toLowerCase()
|
|
847
|
-
.trim()
|
|
848
|
-
|
|
849
|
-
const argDescriptions = Object.entries(args)
|
|
850
|
-
.map(([key, value]) => {
|
|
851
|
-
const type = Array.isArray(value) ? 'array' : typeof value
|
|
852
|
-
return ` - ${key}: ${type} (example: ${JSON.stringify(value).slice(0, 50)})`
|
|
853
|
-
})
|
|
854
|
-
.join('\n')
|
|
855
|
-
|
|
856
|
-
const result = await generateObject({
|
|
857
|
-
model: 'sonnet',
|
|
858
|
-
schema: {
|
|
859
|
-
type: 'code | generative | agentic | human',
|
|
860
|
-
reasoning: 'Why this function type is appropriate (1-2 sentences)',
|
|
861
|
-
description: 'What this function does',
|
|
862
|
-
output: 'string | object | image | video | audio',
|
|
863
|
-
returnType: 'Schema for the return type as a SimpleSchema object',
|
|
864
|
-
system: 'System prompt for the AI (if generative/agentic)',
|
|
865
|
-
promptTemplate: 'Prompt template with {{arg}} placeholders',
|
|
866
|
-
instructions: 'Instructions for agentic/human functions',
|
|
867
|
-
needsTools: 'true | false',
|
|
868
|
-
suggestedTools: ['Names of tools that might be needed'],
|
|
869
|
-
channel: 'slack | email | web | sms | custom',
|
|
870
|
-
},
|
|
871
|
-
system: `You are an expert at designing AI functions. Analyze the function name and arguments to determine the best function type.
|
|
872
|
-
|
|
873
|
-
Function Types:
|
|
874
|
-
- "code": For generating executable code (calculations, algorithms, data transformations)
|
|
875
|
-
- "generative": For generating content (text, summaries, translations, creative writing, structured data)
|
|
876
|
-
- "agentic": For complex tasks requiring multiple steps, research, or tool use (research, planning, multi-step workflows)
|
|
877
|
-
- "human": For tasks requiring human judgment, approval, or input (approvals, reviews, decisions)
|
|
878
|
-
|
|
879
|
-
Guidelines:
|
|
880
|
-
- Most functions should be "generative" - they generate content or structured data
|
|
881
|
-
- Use "code" only when actual executable code needs to be generated
|
|
882
|
-
- Use "agentic" when the task requires research, multiple steps, or external tool use
|
|
883
|
-
- Use "human" when human judgment/approval is essential`,
|
|
884
|
-
prompt: `Analyze this function call and determine how to define it:
|
|
885
|
-
|
|
886
|
-
Function Name: ${name}
|
|
887
|
-
Readable Name: ${readableName}
|
|
888
|
-
Arguments:
|
|
889
|
-
${argDescriptions || ' (no arguments)'}
|
|
890
|
-
|
|
891
|
-
Determine:
|
|
892
|
-
1. What type of function this should be
|
|
893
|
-
2. What it should return
|
|
894
|
-
3. How it should be implemented`,
|
|
895
|
-
})
|
|
896
|
-
|
|
897
|
-
const analysis = result.object as {
|
|
898
|
-
type: string
|
|
899
|
-
reasoning: string
|
|
900
|
-
description: string
|
|
901
|
-
output: string
|
|
902
|
-
returnType: unknown
|
|
903
|
-
system: string
|
|
904
|
-
promptTemplate: string
|
|
905
|
-
instructions: string
|
|
906
|
-
needsTools: string
|
|
907
|
-
suggestedTools: string[]
|
|
908
|
-
channel: string
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
// Build the function definition based on the analysis
|
|
912
|
-
let definition: FunctionDefinition
|
|
913
|
-
|
|
914
|
-
const baseDefinition = {
|
|
915
|
-
name,
|
|
916
|
-
description: analysis.description,
|
|
917
|
-
args: inferArgsSchema(args),
|
|
918
|
-
returnType: analysis.returnType as SimpleSchemaType,
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
switch (analysis.type) {
|
|
922
|
-
case 'code':
|
|
923
|
-
definition = {
|
|
924
|
-
...baseDefinition,
|
|
925
|
-
type: 'code' as const,
|
|
926
|
-
language: 'typescript' as const,
|
|
927
|
-
instructions: analysis.instructions,
|
|
928
|
-
}
|
|
929
|
-
break
|
|
930
|
-
|
|
931
|
-
case 'agentic':
|
|
932
|
-
definition = {
|
|
933
|
-
...baseDefinition,
|
|
934
|
-
type: 'agentic' as const,
|
|
935
|
-
instructions: analysis.instructions || `Complete the ${readableName} task`,
|
|
936
|
-
promptTemplate: analysis.promptTemplate,
|
|
937
|
-
tools: [], // Tools would need to be provided separately
|
|
938
|
-
maxIterations: 10,
|
|
939
|
-
}
|
|
940
|
-
break
|
|
941
|
-
|
|
942
|
-
case 'human':
|
|
943
|
-
definition = {
|
|
944
|
-
...baseDefinition,
|
|
945
|
-
type: 'human' as const,
|
|
946
|
-
channel: (analysis.channel || 'web') as HumanChannel,
|
|
947
|
-
instructions: analysis.instructions || `Please review and respond to this ${readableName} request`,
|
|
948
|
-
promptTemplate: analysis.promptTemplate,
|
|
949
|
-
}
|
|
950
|
-
break
|
|
951
|
-
|
|
952
|
-
case 'generative':
|
|
953
|
-
default:
|
|
954
|
-
definition = {
|
|
955
|
-
...baseDefinition,
|
|
956
|
-
type: 'generative' as const,
|
|
957
|
-
output: (analysis.output || 'object') as 'string' | 'object' | 'image' | 'video',
|
|
958
|
-
system: analysis.system,
|
|
959
|
-
promptTemplate: analysis.promptTemplate || `{{${Object.keys(args)[0] || 'input'}}}`,
|
|
960
|
-
}
|
|
961
|
-
break
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
return {
|
|
965
|
-
type: analysis.type as 'code' | 'generative' | 'agentic' | 'human',
|
|
966
|
-
reasoning: analysis.reasoning,
|
|
967
|
-
definition,
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
/**
|
|
972
|
-
* Infer a schema from example arguments
|
|
973
|
-
*/
|
|
974
|
-
function inferArgsSchema(args: Record<string, unknown>): Record<string, string | string[] | Record<string, unknown>> {
|
|
975
|
-
const schema: Record<string, string | string[] | Record<string, unknown>> = {}
|
|
976
|
-
|
|
977
|
-
for (const [key, value] of Object.entries(args)) {
|
|
978
|
-
if (typeof value === 'string') {
|
|
979
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`
|
|
980
|
-
} else if (typeof value === 'number') {
|
|
981
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()} (number)`
|
|
982
|
-
} else if (typeof value === 'boolean') {
|
|
983
|
-
schema[key] = `Whether ${key.replace(/([A-Z])/g, ' $1').toLowerCase()} (boolean)`
|
|
984
|
-
} else if (Array.isArray(value)) {
|
|
985
|
-
if (value.length > 0 && typeof value[0] === 'string') {
|
|
986
|
-
schema[key] = [`List of ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`]
|
|
987
|
-
} else {
|
|
988
|
-
schema[key] = [`Items for ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`]
|
|
989
|
-
}
|
|
990
|
-
} else if (typeof value === 'object' && value !== null) {
|
|
991
|
-
schema[key] = inferArgsSchema(value as Record<string, unknown>)
|
|
992
|
-
} else {
|
|
993
|
-
schema[key] = `The ${key.replace(/([A-Z])/g, ' $1').toLowerCase()}`
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
return schema
|
|
998
|
-
}
|
|
999
|
-
|
|
1000
|
-
/**
|
|
1001
|
-
* Auto-define a function based on its name and arguments, or define with explicit definition
|
|
1002
|
-
*
|
|
1003
|
-
* When called with (name, args), uses AI to analyze and determine:
|
|
1004
|
-
* - What type of function it should be (code, generative, agentic, human)
|
|
1005
|
-
* - What it should return
|
|
1006
|
-
* - How it should be implemented
|
|
1007
|
-
*
|
|
1008
|
-
* When called with a FunctionDefinition, creates the function directly.
|
|
1009
|
-
*
|
|
1010
|
-
* @example
|
|
1011
|
-
* ```ts
|
|
1012
|
-
* // Auto-define from name and example args
|
|
1013
|
-
* const planTrip = await define('planTrip', { destination: 'Tokyo', travelers: 2 })
|
|
1014
|
-
*
|
|
1015
|
-
* // Or define explicitly
|
|
1016
|
-
* const summarize = define.generative({
|
|
1017
|
-
* name: 'summarize',
|
|
1018
|
-
* args: { text: 'Text to summarize' },
|
|
1019
|
-
* output: 'string',
|
|
1020
|
-
* })
|
|
1021
|
-
*
|
|
1022
|
-
* // Or with full definition
|
|
1023
|
-
* const fn = defineFunction({
|
|
1024
|
-
* type: 'generative',
|
|
1025
|
-
* name: 'translate',
|
|
1026
|
-
* args: { text: 'Text', lang: 'Target language' },
|
|
1027
|
-
* output: 'string',
|
|
1028
|
-
* })
|
|
1029
|
-
* ```
|
|
1030
|
-
*/
|
|
1031
|
-
async function autoDefineImpl(
|
|
1032
|
-
name: string,
|
|
1033
|
-
args: Record<string, unknown>
|
|
1034
|
-
): Promise<DefinedFunction> {
|
|
1035
|
-
// Check if already defined
|
|
1036
|
-
const existing = functions.get(name)
|
|
1037
|
-
if (existing) {
|
|
1038
|
-
return existing
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
// Analyze and define the function
|
|
1042
|
-
const { definition } = await analyzeFunction(name, args)
|
|
1043
|
-
|
|
1044
|
-
// Create the defined function
|
|
1045
|
-
const definedFn = createDefinedFunction(definition)
|
|
1046
|
-
|
|
1047
|
-
// Store in registry
|
|
1048
|
-
functions.set(name, definedFn)
|
|
1049
|
-
|
|
1050
|
-
return definedFn
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
/**
|
|
1054
|
-
* Define functions - auto-define or use typed helpers
|
|
1055
|
-
*/
|
|
1056
|
-
export const define = Object.assign(autoDefineImpl, {
|
|
1057
|
-
/**
|
|
1058
|
-
* Define a code generation function
|
|
1059
|
-
*/
|
|
1060
|
-
code: <TOutput, TInput>(
|
|
1061
|
-
definition: Omit<CodeFunctionDefinition<TOutput, TInput>, 'type'>
|
|
1062
|
-
): DefinedFunction<TOutput, TInput> => {
|
|
1063
|
-
const fn = defineFunction({ type: 'code', ...definition } as CodeFunctionDefinition<TOutput, TInput>)
|
|
1064
|
-
functions.set(definition.name, fn as DefinedFunction)
|
|
1065
|
-
return fn
|
|
1066
|
-
},
|
|
1067
|
-
|
|
1068
|
-
/**
|
|
1069
|
-
* Define a generative function
|
|
1070
|
-
*/
|
|
1071
|
-
generative: <TOutput, TInput>(
|
|
1072
|
-
definition: Omit<GenerativeFunctionDefinition<TOutput, TInput>, 'type'>
|
|
1073
|
-
): DefinedFunction<TOutput, TInput> => {
|
|
1074
|
-
const fn = defineFunction({ type: 'generative', ...definition } as GenerativeFunctionDefinition<TOutput, TInput>)
|
|
1075
|
-
functions.set(definition.name, fn as DefinedFunction)
|
|
1076
|
-
return fn
|
|
1077
|
-
},
|
|
1078
|
-
|
|
1079
|
-
/**
|
|
1080
|
-
* Define an agentic function
|
|
1081
|
-
*/
|
|
1082
|
-
agentic: <TOutput, TInput>(
|
|
1083
|
-
definition: Omit<AgenticFunctionDefinition<TOutput, TInput>, 'type'>
|
|
1084
|
-
): DefinedFunction<TOutput, TInput> => {
|
|
1085
|
-
const fn = defineFunction({ type: 'agentic', ...definition } as AgenticFunctionDefinition<TOutput, TInput>)
|
|
1086
|
-
functions.set(definition.name, fn as DefinedFunction)
|
|
1087
|
-
return fn
|
|
1088
|
-
},
|
|
1089
|
-
|
|
1090
|
-
/**
|
|
1091
|
-
* Define a human-in-the-loop function
|
|
1092
|
-
*/
|
|
1093
|
-
human: <TOutput, TInput>(
|
|
1094
|
-
definition: Omit<HumanFunctionDefinition<TOutput, TInput>, 'type'>
|
|
1095
|
-
): DefinedFunction<TOutput, TInput> => {
|
|
1096
|
-
const fn = defineFunction({ type: 'human', ...definition } as HumanFunctionDefinition<TOutput, TInput>)
|
|
1097
|
-
functions.set(definition.name, fn as DefinedFunction)
|
|
1098
|
-
return fn
|
|
1099
|
-
},
|
|
1100
|
-
})
|
|
1101
|
-
|
|
1102
|
-
// ============================================================================
|
|
1103
|
-
// AI() - Smart AI Client with Auto-Definition
|
|
1104
|
-
// ============================================================================
|
|
1105
|
-
|
|
1106
|
-
/** Known built-in method names that should not be auto-defined */
|
|
1107
|
-
const BUILTIN_METHODS = new Set([
|
|
1108
|
-
'do', 'is', 'code', 'decide', 'diagram', 'generate', 'image', 'video', 'write', 'list', 'lists',
|
|
1109
|
-
'functions', 'define', 'defineFunction', 'then', 'catch', 'finally',
|
|
1110
|
-
])
|
|
1111
|
-
|
|
1112
|
-
/**
|
|
1113
|
-
* Create a smart AI client that auto-defines functions on first call
|
|
1114
|
-
*
|
|
1115
|
-
* @example
|
|
1116
|
-
* ```ts
|
|
1117
|
-
* const ai = AI()
|
|
1118
|
-
*
|
|
1119
|
-
* // First call - auto-defines the function
|
|
1120
|
-
* const trip = await ai.planTrip({
|
|
1121
|
-
* destination: 'Tokyo',
|
|
1122
|
-
* dates: { start: '2024-03-01', end: '2024-03-10' },
|
|
1123
|
-
* travelers: 2,
|
|
1124
|
-
* })
|
|
1125
|
-
*
|
|
1126
|
-
* // Second call - uses cached definition (in-memory)
|
|
1127
|
-
* const trip2 = await ai.planTrip({
|
|
1128
|
-
* destination: 'Paris',
|
|
1129
|
-
* dates: { start: '2024-06-01', end: '2024-06-07' },
|
|
1130
|
-
* travelers: 4,
|
|
1131
|
-
* })
|
|
1132
|
-
*
|
|
1133
|
-
* // Access registry and define
|
|
1134
|
-
* console.log(ai.functions.list()) // ['planTrip']
|
|
1135
|
-
* ai.define.generative({ name: 'summarize', ... })
|
|
1136
|
-
* ```
|
|
1137
|
-
*/
|
|
1138
|
-
function createSmartAI(): AIProxy {
|
|
1139
|
-
const base = {
|
|
1140
|
-
functions,
|
|
1141
|
-
define,
|
|
1142
|
-
defineFunction,
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
return new Proxy(base as AIProxy, {
|
|
1146
|
-
get(target, prop: string) {
|
|
1147
|
-
// Return built-in properties
|
|
1148
|
-
if (prop in target) {
|
|
1149
|
-
return (target as Record<string, unknown>)[prop]
|
|
1150
|
-
}
|
|
1151
|
-
|
|
1152
|
-
// Skip internal properties
|
|
1153
|
-
if (typeof prop === 'symbol' || prop.startsWith('_') || BUILTIN_METHODS.has(prop)) {
|
|
1154
|
-
return undefined
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
// Return a function that auto-defines and calls
|
|
1158
|
-
return async (args: Record<string, unknown> = {}) => {
|
|
1159
|
-
// Check if function is already defined
|
|
1160
|
-
let fn = functions.get(prop)
|
|
1161
|
-
|
|
1162
|
-
if (!fn) {
|
|
1163
|
-
// Auto-define the function
|
|
1164
|
-
fn = await define(prop, args)
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
// Call the function
|
|
1168
|
-
return fn.call(args)
|
|
1169
|
-
}
|
|
1170
|
-
},
|
|
1171
|
-
})
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
/**
|
|
1175
|
-
* Type for the AI proxy with auto-define capability
|
|
1176
|
-
*/
|
|
1177
|
-
export interface AIProxy {
|
|
1178
|
-
/** Function registry */
|
|
1179
|
-
functions: FunctionRegistry
|
|
1180
|
-
/** Define functions */
|
|
1181
|
-
define: typeof define
|
|
1182
|
-
/** Define a function with full definition */
|
|
1183
|
-
defineFunction: typeof defineFunction
|
|
1184
|
-
/** Dynamic function calls */
|
|
1185
|
-
[key: string]: unknown
|
|
119
|
+
// Schema functions mode - create a function for each schema
|
|
120
|
+
return createSchemaFunctions(schemas, defaultOptions)
|
|
1186
121
|
}
|
|
1187
|
-
|
|
1188
|
-
/**
|
|
1189
|
-
* Default AI instance with auto-define capability
|
|
1190
|
-
*
|
|
1191
|
-
* @example
|
|
1192
|
-
* ```ts
|
|
1193
|
-
* import { ai } from 'ai-functions'
|
|
1194
|
-
*
|
|
1195
|
-
* // Auto-define and call
|
|
1196
|
-
* const result = await ai.summarize({ text: 'Long article...' })
|
|
1197
|
-
*
|
|
1198
|
-
* // Access functions registry
|
|
1199
|
-
* ai.functions.list()
|
|
1200
|
-
*
|
|
1201
|
-
* // Define explicitly
|
|
1202
|
-
* ai.define.generative({ name: 'translate', ... })
|
|
1203
|
-
* ```
|
|
1204
|
-
*/
|
|
1205
|
-
export const ai: AIProxy = createSmartAI()
|