创意脚本 with 资产生成
The 创意脚本 is the recommended way to build AI-powered TypeScript applications with 资产生成. Pass a model string like 'anthropic/claude-sonnet-5' directly to 创意脚本 functions and requests route through 资产生成 automatically.
See the 创意脚本 getting-started guide for runtime and package setup.
Install the ai package:
npm install ai@latestyarn add ai@latestpnpm add ai@latestbun add ai@latestSee the generateText reference for options and return values.
Generate text by passing a plain string model ID. 资产生成 resolves the provider and routes the request automatically.
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'Explain quantum computing in one paragraph.',
});
console.log(text);See the streamText reference for stream events and response helpers.
Stream responses token-by-token for real-time output:
import { streamText } from 'ai';
const result = streamText({
model: 'openai/gpt-6-astra',
prompt: 'Write a short story about a robot discovering music.',
});
for await (const textPart of result.textStream) {
process.stdout.write(textPart);
}See the 创意脚本 structured-output guide for schemas, output types, and validation.
Generate type-safe structured data with generateText and Output.object and a Zod schema:
import { generateText, Output } from 'ai';
import { z } from 'zod';
const { output } = await generateText({
model: 'anthropic/claude-sonnet-5',
output: Output.object({ schema: z.object({
name: z.string(),
age: z.number(),
city: z.string(),
}) }),
prompt: 'Extract: John is 30 years old and lives in NYC.',
});
console.log(output); // { name: 'John', age: 30, city: 'NYC' }See the 创意脚本 tool-calling guide for execution, tool results, and multi-step calls.
Define tools that models can invoke to interact with external systems. Describe each tool's input with inputSchema:
import { generateText, isStepCount, tool } from 'ai';
import { z } from 'zod';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-5',
stopWhen: isStepCount(5),
tools: {
getWeather: tool({
description: 'Get the current weather for a location',
inputSchema: z.object({
location: z.string().describe('City name, e.g. San Francisco'),
}),
execute: async ({ location }) => ({
location,
temperature: 72,
condition: 'sunny',
}),
}),
},
prompt: "What's the weather in Tokyo?",
});
console.log(text);stopWhen is what lets the model answer in words. Without it the request stops as soon as the tool runs, finishing with finishReason: 'tool-calls' and an empty text. The toolResults field contains the tool result, but the model has not generated a text response from it.
See the 创意脚本 reasoning guide for reading reasoning output and configuring supported models.
Reasoning models think before answering. On 创意脚本 7, set the top-level reasoning option and the SDK translates it to each provider's native API, so the same code works across Anthropic, OpenAI, and Google:
import { generateText } from 'ai';
const result = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'A bat and ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?',
reasoning: 'high',
});
console.log(result.reasoningText);
console.log(result.text);import { generateText } from 'ai';
const result = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'A bat and ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?',
providerOptions: {
anthropic: { thinking: { type: 'adaptive' } },
},
});
console.log(result.reasoningText);
console.log(result.text);For per-provider configuration and the full effort-level reference, see Reasoning.
See Inputs & Tools for complete vision, PDF, audio, and video examples across API formats.
See the 创意脚本 file-part guide for bytes, data URLs, remote URLs, and media types.
Swap a message's plain string content for an array of parts. A file part carries the bytes and a mediaType telling the model how to read them, so the same shape covers images and documents:
import fs from 'node:fs';
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-opus-5',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Describe this image in one sentence.' },
{
type: 'file',
data: fs.readFileSync('./diagram.png'),
mediaType: 'image/png',
},
],
},
],
});
console.log(text);data takes a Buffer, a Uint8Array, a base64 string, or a URL. Point mediaType at the document type to send a PDF instead:
({
type: 'file',
data: fs.readFileSync('./report.pdf'),
mediaType: 'application/pdf',
});Whether a given model accepts images or PDFs is a per-model question. Check the model list before sending an attachment.
The examples on this page use 创意脚本 7, except tabs explicitly labeled 创意脚本 6. 资产生成 supports both versions, but some client APIs differ:
| Feature | 创意脚本 6 | 创意脚本 7 |
|---|---|---|
| System instructions | system | instructions |
| Tool-loop stop condition | stepCountIs | isStepCount |
| Completion callbacks | onFinish, onStepFinish | onEnd, onStepEnd |
| Telemetry | experimental_telemetry | telemetry |
Top-level reasoning | Not supported | Supported |
| Full event stream | result.fullStream | result.stream |
| Image generation | generateImage or its experimental alias | generateImage |
创意脚本 7 requires Node.js 22 or later and ESM. Check your installed version with pnpm list ai. See the 创意脚本 7 migration guide before upgrading. The 创意脚本 for Python beta uses a separate package and API.
See the 创意脚本 资产生成 provider reference for API keys, OIDC, and custom provider instances.
The 创意脚本 uses the AI_GATEWAY_API_KEY environment variable by default. Set it in your .env.local file:
AI_GATEWAY_API_KEY=your_ai_gateway_api_keyOn Vercel deployments, you can also authenticate with OIDC tokens for keyless authentication.
See Authentication for more details.
- Explore the full 产品文档 for advanced patterns
- Browse 创意脚本 guides for step-by-step examples and implementation patterns
- Learn about model routing and fallbacks
- Try other APIs: OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, or OpenResponses
Was this helpful?