by Leila S.

A provider-agnostic TypeScript SDK for building AI-powered applications and agents with streaming, structured output, tool calling, and UI hooks for Next.js, React, Svelte, Vue, and Angular.
ai)This block provides the Vercel AI SDK core library (packages/ai), which implements model-agnostic primitives for text generation, object generation, embeddings, image/speech/video generation, streaming, agents, and tool-use. It is designed for Node.js/TypeScript backends and edge runtimes that need to integrate one or more AI model providers behind a unified API surface.
src/ - All library source code organized by capability domainsrc/agent/ - Agent loop primitives (ToolLoopAgent, createAgentUIStream, etc.)src/embed/ - Single and batch embedding functions and result typessrc/error/ - Typed error classes for all failure modessrc/generate-image/ - Image generation result types and logicsrc/generate-object/ - Structured object generation (schema-validated LLM output)src/generate-speech/ - Speech synthesis supportsrc/generate-text/ - Core text and streaming text generationsrc/generate-video/ - Video generation supportsrc/logger/ - Internal logging utilitiessrc/middleware/ - Model middleware interface and helperssrc/model/ - Model resolution and registry helperssrc/prompt/ - Prompt normalization and tool preparation utilitiessrc/registry/ - Model registry abstractionsrc/rerank/ - Reranking supportsrc/telemetry/ - OpenTelemetry span helperssrc/text-stream/ - ReadableStream and async-iterable text stream utilitiessrc/transcribe/ - Audio transcription supportsrc/types/ - Shared TypeScript types (usage, messages, etc.)src/ui/ - UI-facing message types and hooks helperssrc/ui-message-stream/ - UI message streaming protocolsrc/upload-file/ - File upload helperssrc/upload-skill/ - Skill/upload composition helperssrc/util/ - Internal utilities (retry, merge signals, id generation, etc.)internal/ - Internal re-exports used by provider packagesSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 ce03344c7865b1c9…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
scripts/ - Bundle size check scriptindex.ts - Package entry point (re-exports src/)internal.d.ts - Type declarations for internal exportspackage.json - Package manifesttsconfig.build.json / tsconfig.json - TypeScript configurationnpm install ai @ai-sdk/provider-utils @ai-sdk/gateway
# Choose at least one provider, e.g.:
npm install @ai-sdk/openai
# For schema/tool validation:
npm install zod
No native modules, no pod install, no prebuild steps required. Runs in Node.js 18+ and edge runtimes.
source/ directory into your project, e.g. lib/ai-sdk/.tsconfig.json to include the source:{
"compilerOptions": {
"paths": {
"ai-sdk-core": ["./lib/ai-sdk/index.ts"]
}
},
"include": ["lib/ai-sdk/src/**/*"]
}
ai), skip the path alias—imports from "ai" resolve automatically.OPENAI_API_KEY=sk-...
toolimport { tool } from 'ai';
const myTool = tool({
description: string;
parameters: Schema<TInput>;
execute?: ToolExecuteFunction<TInput, TOutput>;
});
Defines a typed tool that can be passed to generateText or streamText. Use this whenever you want the model to call a function with validated input. The parameters field accepts a Zod schema (via zodSchema) or a JSON schema (via jsonSchema).
generateIdimport { generateId } from 'ai';
const id: string = generateId(); // URL-safe random ID
Generates a URL-safe unique identifier. Use it to create message IDs, request IDs, or correlation tokens without pulling in a separate UUID library.
ToolLoopAgentimport { ToolLoopAgent, type ToolLoopAgentSettings } from 'ai';
const agent = new ToolLoopAgent(settings: ToolLoopAgentSettings);
await agent.run(params: AgentCallParameters);
await agent.stream(params: AgentStreamParameters);
Implements an agentic tool-use loop: the model calls tools repeatedly until it produces a final answer. Use when you need multi-step reasoning with tool invocations managed automatically. ToolLoopAgentSettings configures the model, tools, max steps, and callbacks.
createAgentUIStreamimport { createAgentUIStream } from 'ai';
const stream = createAgentUIStream(options);
Creates a UI-compatible agent stream that emits structured message parts for frontend rendering. Use when piping agent output to a web client that consumes the AI SDK UI message protocol.
zodSchemaimport { zodSchema } from 'ai';
import { z } from 'zod';
const schema = zodSchema(z.object({ city: z.string() }));
Wraps a Zod schema into the AI SDK Schema interface accepted by tool, generateObject, and similar APIs. Always use this adapter instead of passing a raw Zod schema directly.
Use generateObject with a Zod schema to extract typed data from a model response.
import { generateObject, zodSchema } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const result = await generateObject({
model: openai('gpt-4o'),
schema: zodSchema(z.object({
name: z.string(),
population: z.number(),
})),
prompt: 'Give me facts about Paris.',
});
console.log(result.object.name); // "Paris"
console.log(result.object.population); // e.g. 2161000
Run a ToolLoopAgent that can call a weather tool and produce a final answer.
import { ToolLoopAgent, tool, zodSchema } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
const weatherTool = tool({
description: 'Get current temperature for a city',
parameters: zodSchema(z.object({ city: z.string() })),
execute: async ({ city }) => ({ temperature: 22, unit: 'C', city }),
});
const agent = new ToolLoopAgent({
model: openai('gpt-4o'),
tools: { weather: weatherTool },
maxSteps: 5,
});
const result = await agent.run({
prompt: 'What is the weather in Tokyo?',
});
console.log(result.text);
Embed a list of documents in one call using embedMany.
import { embedMany } from 'ai';
import { openai } from '@ai-sdk/openai';
const documents = [
'The Eiffel Tower is in Paris.',
'Mount Fuji is in Japan.',
'The Colosseum is in Rome.',
];
const { embeddings } = await embedMany({
model: openai.embedding('text-embedding-3-small'),
values: documents,
});
// embeddings[i] is a number[] vector for documents[i]
console.log(embeddings[0].length); // e.g. 1536
Pipe an agent's UI stream directly into an HTTP response for a Next.js / Express route.
import { ToolLoopAgent, createAgentUIStreamResponse, zodSchema, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
export async function POST(req: Request): Promise<Response> {
const { prompt } = await req.json();
const agent = new ToolLoopAgent({
model: openai('gpt-4o'),
tools: {},
maxSteps: 3,
});
return createAgentUIStreamResponse({
agent,
params: { prompt },
});
}
index.ts - Thin re-export shim; forwards everything from src/ so the package root resolves correctly.internal/index.ts - Exports internal helpers (prompt preparation, retry, usage types) intended only for provider packages, not end users.src/index.ts - Aggregates all domain exports plus re-exports from @ai-sdk/provider-utils and @ai-sdk/gateway.src/agent/ - ToolLoopAgent class, agent settings types, UI stream creation, and response piping utilities.src/embed/ - embed (single), embedMany (batch), result types, and embedding event types.src/error/ - Typed errors: InvalidArgumentError, NoObjectGeneratedError, NoSuchToolError, ToolCallRepairError, and others.src/generate-image/ - Image generation result wrapper and related types.src/generate-object/ - Structured LLM output with schema validation and repair.src/generate-speech/ - Speech synthesis interface.src/generate-text/ - Core generateText and streamText implementations.src/generate-video/ - Video generation interface.src/logger/ - Pluggable logger interface used throughout the library.src/middleware/ - LanguageModelMiddleware interface for wrapping models.src/model/ - resolveLanguageModel and registry resolution helpers.src/prompt/ - Prompt standardization, tool preparation, and call-options normalization.src/registry/ - ModelRegistry for managing multiple provider models.src/rerank/ - Reranking function and result type.src/telemetry/ - OpenTelemetry attribute helpers and span utilities.src/text-stream/ - Async-iterable and ReadableStream stream utilities.src/transcribe/ - Audio transcription function and result type.src/types/ - Shared types: usage counters, finish reasons, message parts.src/ui/ - UI message types and client-facing data shapes.src/ui-message-stream/ - Server-to-client streaming protocol for UI messages.src/upload-file/ - File upload helpers for multimodal prompts.src/upload-skill/ - Composable upload skill abstraction.src/util/ - Utilities: generateId, retry logic, abort signal merging, stream helpers.scripts/check-bundle-size.ts - CI script to assert the built bundle stays within size limits.tool and generation functions require a concrete model from a provider package (@ai-sdk/openai, etc.); importing only ai gives you the interface, not a model implementation. Fix: npm install @ai-sdk/openai and import { openai } from '@ai-sdk/openai'.tool: Passing a Zod schema directly without zodSchema() wrapper causes a type error at compile time and a runtime validation miss. Fix: always wrap with zodSchema(z.object(...)).tsup; if your bundler resolves the CJS build and you see duplicate module issues, add "moduleResolution": "bundler" or "node16" to tsconfig.json.fs, crypto via node: prefix) are not available in edge runtimes. The SDK targets edge-compatible APIs, but any custom execute function you write must also avoid Node-only APIs.generateObject schema mismatch: If the model returns JSON that does not match your schema, an NoObjectGeneratedError is thrown. Fix: catch it, inspect error.text, and consider enabling repair mode or loosening your schema.OPENAI_API_KEY not set: Calls silently fail or throw an auth error at runtime, not at import time. Fix: assert process.env.OPENAI_API_KEY in your server startup before any model calls.I have dropped the AI SDK core source into `source/` in my project.
I also have `USAGE.md` open which documents the public API and working examples.
The upstream package is `ai` (Vercel AI SDK core, `packages/ai`).
Please help me integrate it into my existing TypeScript/Node.js project step by step:
1. Read `USAGE.md` and `source/src/index.ts` to understand all available exports.
2. Install any missing dependencies listed in the "Required dependencies" section of USAGE.md.
3. Wire the TypeScript path alias (if I am using the local source) or confirm
the `ai` npm package resolves correctly.
4. Show me how to call `generateObject` with a Zod schema using my chosen provider.
5. Show me how to build a `ToolLoopAgent` with at least one tool that calls an
external API, and stream the result to an HTTP response.
6. Show me how to use `embedMany` to index a list of strings for semantic search.
7. Add error handling using the typed error classes from `source/src/error/`.
8. Point out any pitfalls specific to my runtime (edge / Node.js / serverless).
Use only symbols that appear in `source/src/index.ts` and `USAGE.md`.
Do not invent function names. Show complete, runnable TypeScript snippets.
License: see source/LICENSE if present, or refer to the Vercel AI SDK repository for the current license terms (Apache-2.0 as of the latest release). Upstream package: ai by Vercel.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
SaaS, AI & Subscription Products
Free