ai-functions
Version:
Core AI primitives for building intelligent applications
428 lines • 14.8 kB
TypeScript
/**
* AI Function Primitives with Promise Pipelining
*
* All functions return AIPromise for:
* - Dynamic schema inference from destructuring
* - Promise pipelining without await
* - Magical .map() for batch processing
* - Dependency graph resolution
*
* @example
* ```ts
* // No await needed until the end!
* const { summary, keyPoints, conclusion } = ai`write about ${topic}`
* const isValid = is`${conclusion} is solid given ${keyPoints}`
* const improved = ai`improve ${conclusion} using ${keyPoints}`
*
* // Batch processing with map
* const ideas = list`startup ideas`
* const evaluated = await ideas.map(idea => ({
* idea,
* viable: is`${idea} is viable`,
* market: ai`market size for ${idea}`,
* }))
*
* // Only await at the end
* if (await isValid) {
* console.log(await improved)
* }
* ```
*
* @packageDocumentation
*/
import { AIPromise } from './ai-promise.js';
import type { SimpleSchema } from './schema.js';
import type { AgenticFunctionDefinition, CodeFunctionDefinition, DefinedFunction, FunctionRegistry, GenerativeFunctionDefinition, HumanChannel, HumanFunctionDefinition } from './types.js';
import { defineFunction } from './function-registry.js';
export type GenerateType = 'text' | 'json' | 'code' | 'list' | 'lists' | 'markdown' | 'yaml' | 'diagram' | 'slides' | 'boolean' | 'summary' | 'extract';
export interface GenerateOptions {
/** Model to use */
model?: string;
/** System prompt */
system?: string;
/** Temperature (0-2) */
temperature?: number;
/** Max tokens */
maxTokens?: number;
/** Schema for JSON output */
schema?: SimpleSchema;
/** Language for code generation */
language?: string;
/** Format for diagrams */
format?: 'mermaid' | 'svg' | 'ascii';
/** Number of slides for presentations */
slides?: number;
}
/**
* Core generate primitive - all other functions use this under the hood
*/
export declare function generate(type: GenerateType, prompt: string, options?: GenerateOptions): Promise<unknown>;
/**
* General-purpose AI function with dynamic schema inference
*
* @example
* ```ts
* // Simple text generation
* const text = await ai`write a poem about ${topic}`
*
* // Dynamic schema from destructuring - no await needed!
* const { summary, keyPoints, conclusion } = ai`write about ${topic}`
* console.log(await summary)
*
* // Chain with other functions
* const isValid = is`${conclusion} is solid`
* const improved = ai`improve ${conclusion}`
* ```
*/
export declare const ai: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<unknown>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<unknown>);
/**
* Generate text content
*
* @example
* ```ts
* const post = await write`blog post about ${topic}`
* ```
*/
export declare const write: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Generate code
*
* @example
* ```ts
* const code = await code`email validation function`
* ```
*/
export declare const code: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Generate a list of items with .map() support
*
* @example
* ```ts
* // Simple list
* const ideas = await list`startup ideas`
*
* // With map - batch processes in ONE call!
* const evaluated = await list`startup ideas`.map(idea => ({
* idea,
* viable: is`${idea} is viable`,
* market: ai`market size for ${idea}`,
* }))
*
* // Async iteration
* for await (const idea of list`startup ideas`) {
* console.log(idea)
* }
* ```
*/
export declare const list: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string[]>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string[]>);
/**
* Generate multiple named lists with dynamic schema
*
* @example
* ```ts
* // Destructuring infers the schema!
* const { pros, cons } = await lists`pros and cons of ${topic}`
*
* // No await - pipeline with other functions
* const { benefits, risks, costs } = lists`analysis of ${project}`
* const summary = ai`summarize: benefits=${benefits}, risks=${risks}`
* console.log(await summary)
* ```
*/
export declare const lists: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<Record<string, string[]>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<Record<string, string[]>>);
/**
* Extract structured data with dynamic schema
*
* @example
* ```ts
* // Dynamic schema from destructuring
* const { name, email, phone } = await extract`contact info from ${document}`
*
* // As array
* const emails = await extract`email addresses from ${text}`
* ```
*/
export declare const extract: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<unknown[]>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<unknown[]>);
/**
* Summarize text
*
* @example
* ```ts
* const summary = await summarize`${longArticle}`
* ```
*/
export declare const summarize: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Check if something is true/false
*
* @example
* ```ts
* // Simple check
* const isColor = await is`${topic} a color`
*
* // Pipeline - no await needed!
* const { conclusion } = ai`write about ${topic}`
* const isValid = is`${conclusion} is well-argued`
* if (await isValid) { ... }
* ```
*/
export declare const is: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<boolean>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<boolean>);
/**
* Generate a diagram
*
* @example
* ```ts
* const diagram = await diagram`user authentication flow`
* ```
*/
export declare const diagram: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Generate presentation slides
*
* @example
* ```ts
* const slides = await slides`quarterly review`
* ```
*/
export declare const slides: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Generate an image
*/
export declare const image: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<Buffer<ArrayBufferLike>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<Buffer<ArrayBufferLike>>);
/**
* Generate a video
*/
export declare const video: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<Buffer<ArrayBufferLike>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<Buffer<ArrayBufferLike>>);
/**
* Execute a task
*
* @example
* ```ts
* const { summary, actions } = await do`send welcome email to ${user}`
* ```
*/
declare function doImpl(promptOrStrings: string | TemplateStringsArray, ...args: unknown[]): AIPromise<{
summary: string;
actions: string[];
}>;
export { doImpl as do };
/**
* Conduct research on a topic
*
* @example
* ```ts
* const { summary, findings, sources } = await research`${competitor} vs our product`
* ```
*/
export declare const research: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<{
summary: string;
findings: string[];
sources: string[];
}>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<{
summary: string;
findings: string[];
sources: string[];
}>);
/**
* Read a URL and convert to markdown
*/
export declare const read: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<string>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<string>);
/**
* Browse a URL with browser automation
*
* @experimental This function is experimental and returns mock data.
* The actual implementation will use Stagehand or Playwright for browser automation.
* Do not rely on this function in production code until it is fully implemented.
*
* @param urlOrStrings - URL string or template literal
* @param args - Template literal values
* @returns Browser automation interface with do, extract, screenshot, and close methods
*
* @example
* ```ts
* const browser = await browse`https://example.com`
* await browser.do('click the login button')
* const data = await browser.extract('user profile information')
* const screenshot = await browser.screenshot()
* await browser.close()
* ```
*/
export declare function browse(urlOrStrings: string | TemplateStringsArray, ...args: unknown[]): Promise<{
do: (action: string) => Promise<void>;
extract: (query: string) => Promise<unknown>;
screenshot: () => Promise<Buffer>;
close: () => Promise<void>;
}>;
/**
* LLM as judge - compare options and pick the best
*
* @example
* ```ts
* const winner = await decide`higher click-through rate`(headlineA, headlineB)
* ```
*/
export declare function decide(criteriaOrStrings: string | TemplateStringsArray, ...templateArgs: unknown[]): <T>(...options: T[]) => AIPromise<T>;
export interface HumanOptions extends GenerateOptions {
channel?: HumanChannel;
assignee?: string;
timeout?: number;
webhook?: string;
}
export interface HumanResult<T = unknown> {
pending: boolean;
requestId: string;
response?: T;
respondedBy?: string;
respondedAt?: Date;
artifacts?: {
slackBlocks?: unknown[];
emailHtml?: string;
webComponent?: string;
smsText?: string;
};
}
/**
* Ask a human for input
*/
export declare const ask: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<HumanResult<string>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<HumanResult<string>>);
/**
* Request human approval
*/
export declare const approve: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<HumanResult<{
approved: boolean;
notes?: string;
}>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<HumanResult<{
approved: boolean;
notes?: string;
}>>);
/**
* Request human review
*/
export declare const review: ((strings: TemplateStringsArray, ...values: unknown[]) => AIPromise<HumanResult<{
rating?: number;
feedback: string;
approved?: boolean;
}>>) & ((prompt: string, options?: import("./template.js").FunctionOptions) => AIPromise<HumanResult<{
rating?: number;
feedback: string;
approved?: boolean;
}>>);
/**
* Auto-define a function based on its name and arguments, or define with explicit definition
*
* When called with (name, args), uses AI to analyze and determine:
* - What type of function it should be (code, generative, agentic, human)
* - What it should return
* - How it should be implemented
*
* When called with a FunctionDefinition, creates the function directly.
*
* @example
* ```ts
* // Auto-define from name and example args
* const planTrip = await define('planTrip', { destination: 'Tokyo', travelers: 2 })
*
* // Or define explicitly
* const summarize = define.generative({
* name: 'summarize',
* args: { text: 'Text to summarize' },
* output: 'string',
* })
*
* // Or with full definition
* const fn = defineFunction({
* type: 'generative',
* name: 'translate',
* args: { text: 'Text', lang: 'Target language' },
* output: 'string',
* })
* ```
*/
declare function autoDefineImpl(name: string, args: Record<string, unknown>): Promise<DefinedFunction>;
/**
* Define functions - auto-define or use typed helpers
*/
export declare const define: typeof autoDefineImpl & {
/**
* Define a **deterministic** code function (a handler — no LLM at call time).
*
* Supply a `handler` (canonical) or an inline `code` body. To have a model
* *author* code instead, use {@link generateCode} or `define.generative`.
*/
code: <TOutput, TInput>(definition: Omit<CodeFunctionDefinition<TOutput, TInput>, "type">) => DefinedFunction<TOutput, TInput>;
/**
* Define a generative function
*/
generative: <TOutput, TInput>(definition: Omit<GenerativeFunctionDefinition<TOutput, TInput>, "type">) => DefinedFunction<TOutput, TInput>;
/**
* Define an agentic function
*/
agentic: <TOutput, TInput>(definition: Omit<AgenticFunctionDefinition<TOutput, TInput>, "type">) => DefinedFunction<TOutput, TInput>;
/**
* Define a human-in-the-loop function
*/
human: <TOutput, TInput>(definition: Omit<HumanFunctionDefinition<TOutput, TInput>, "type">) => DefinedFunction<TOutput, TInput>;
};
/**
* Type for the AI proxy with auto-define capability
*/
export interface AIProxy {
/** Function registry */
functions: FunctionRegistry;
/** Define functions */
define: typeof define;
/** Define a function with full definition */
defineFunction: typeof defineFunction;
/** Dynamic function calls */
[key: string]: unknown;
}
/**
* Create a smart AI client that auto-defines functions on first call
*
* @example
* ```ts
* const ai = createSmartAI()
*
* // First call - auto-defines the function
* const trip = await ai.planTrip({
* destination: 'Tokyo',
* dates: { start: '2024-03-01', end: '2024-03-10' },
* travelers: 2,
* })
*
* // Second call - uses cached definition (in-memory)
* const trip2 = await ai.planTrip({
* destination: 'Paris',
* dates: { start: '2024-06-01', end: '2024-06-07' },
* travelers: 4,
* })
*
* // Access registry and define
* console.log(ai.functions.list()) // ['planTrip']
* ai.define.generative({ name: 'summarize', ... })
* ```
*/
export declare function createSmartAI(): AIProxy;
/**
* Default AI proxy instance with auto-define capability.
*
* This is the smart proxy `aiProxy` (re-exported from index.ts as `aiProxy`).
* It is intentionally distinct from the `ai` template-tag primitive above —
* see `ai` (line ~354) for the template function used like `ai\`...\``.
*
* @example
* ```ts
* import { aiProxy } from 'ai-functions'
*
* // Auto-define and call
* const result = await aiProxy.summarize({ text: 'Long article...' })
*
* // Access functions registry
* aiProxy.functions.list()
*
* // Define explicitly
* aiProxy.define.generative({ name: 'translate', ... })
* ```
*/
export declare const aiProxy: AIProxy;
//# sourceMappingURL=primitives.d.ts.map