develop-ai-functions-example by vercel/ai
npx skills add https://github.com/vercel/ai --skill develop-ai-functions-exampleexamples/ai-functions/ 目录包含用于验证、测试和迭代跨提供商的 AI SDK 函数的脚本。
示例按 AI SDK 函数在 examples/ai-functions/src/ 目录中组织:
| 目录 | 用途 |
|---|---|
generate-text/ | 使用 generateText() 进行非流式文本生成 |
stream-text/ | 使用 streamText() 进行流式文本生成 |
generate-object/ |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
使用 generateObject() 进行结构化输出生成 |
stream-object/ | 使用 streamObject() 进行流式结构化输出 |
agent/ | 用于智能体工作流的 ToolLoopAgent 示例 |
embed/ | 使用 embed() 进行单次嵌入生成 |
embed-many/ | 使用 embedMany() 进行批量嵌入生成 |
generate-image/ | 使用 generateImage() 进行图像生成 |
generate-speech/ | 使用 generateSpeech() 进行文本转语音 |
transcribe/ | 使用 transcribe() 进行音频转录 |
rerank/ | 使用 rerank() 进行文档重排序 |
middleware/ | 自定义中间件实现 |
registry/ | 提供者注册表设置和使用 |
telemetry/ | OpenTelemetry 集成 |
complex/ | 多组件示例(智能体、路由器) |
lib/ | 共享工具(非示例) |
tools/ | 可复用的工具定义 |
示例遵循以下模式:{provider}-{feature}.ts
| 模式 | 示例 | 描述 |
|---|---|---|
{provider}.ts | openai.ts | 基本提供者用法 |
{provider}-{feature}.ts | openai-tool-call.ts | 特定功能 |
{provider}-{sub-provider}.ts | amazon-bedrock-anthropic.ts | 包含子提供者的提供者 |
{provider}-{sub-provider}-{feature}.ts | google-vertex-anthropic-cache-control.ts | 包含功能的子提供者 |
所有示例都使用 lib/run.ts 中的 run() 包装器,该包装器:
.env 加载环境变量import { providerName } from '@ai-sdk/provider-name';
import { generateText } from 'ai';
import { run } from '../lib/run';
run(async () => {
const result = await generateText({
model: providerName('model-id'),
prompt: 'Your prompt here.',
});
console.log(result.text);
console.log('Token usage:', result.usage);
console.log('Finish reason:', result.finReason);
});
import { providerName } from '@ai-sdk/provider-name';
import { streamText } from 'ai';
import { printFullStream } from '../lib/print-full-stream';
import { run } from '../lib/run';
run(async () => {
const result = streamText({
model: providerName('model-id'),
prompt: 'Your prompt here.',
});
await printFullStream({ result });
});
import { providerName } from '@ai-sdk/provider-name';
import { generateText, tool } from 'ai';
import { z } from 'zod';
import { run } from '../lib/run';
run(async () => {
const result = await generateText({
model: providerName('model-id'),
tools: {
myTool: tool({
description: 'Tool description',
inputSchema: z.object({
param: z.string().describe('Parameter description'),
}),
execute: async ({ param }) => {
return { result: `Processed: ${param}` };
},
}),
},
prompt: 'Use the tool to...',
});
console.log(JSON.stringify(result, null, 2));
});
import { providerName } from '@ai-sdk/provider-name';
import { generateObject } from 'ai';
import { z } from 'zod';
import { run } from '../lib/run';
run(async () => {
const result = await generateObject({
model: providerName('model-id'),
schema: z.object({
name: z.string(),
items: z.array(z.string()),
}),
prompt: 'Generate a...',
});
console.log(JSON.stringify(result.object, null, 2));
console.log('Token usage:', result.usage);
});
在 examples/ai-functions 目录下运行:
pnpm tsx src/generate-text/openai.ts
pnpm tsx src/stream-text/openai-tool-call.ts
pnpm tsx src/agent/openai-generate.ts
在以下情况下编写示例:
添加新提供者 :为每个支持的 API(generateText、streamText、generateObject 等)创建基础示例
实现新功能 :至少用一个提供者示例来演示该功能
复现错误 :创建一个示例来展示问题以便调试
添加提供者特定选项 :展示如何使用 providerOptions 进行提供者特定设置
创建测试夹具 :使用示例生成 API 响应夹具(参见 capture-api-response-test-fixture 技能)
lib/ 目录包含共享工具:
| 文件 | 用途 |
|---|---|
run.ts | 带有 .env 加载功能的错误处理包装器 |
print.ts | 干净的对象打印(移除未定义的值) |
print-full-stream.ts | 用于工具调用、推理、文本的彩色流式输出 |
save-raw-chunks.ts | 保存流式数据块用于测试夹具 |
present-image.ts | 在终端中显示图像 |
save-audio.ts | 将音频文件保存到磁盘 |
import { print } from '../lib/print';
// 漂亮地打印对象,不包含未定义的值
print('Result:', result);
print('Usage:', result.usage, { depth: 2 });
import { printFullStream } from '../lib/print-full-stream';
const result = streamText({ ... });
await printFullStream({ result }); // 为文本、工具调用、推理提供彩色输出
tools/ 目录包含可复用的工具定义:
import { weatherTool } from '../tools/weather-tool';
const result = await generateText({
model: openai('gpt-4o'),
tools: { weather: weatherTool },
prompt: 'What is the weather in San Francisco?',
});
保持示例专注 :每个示例应演示一个功能或用例
使用描述性提示 :明确说明示例测试的内容
优雅地处理错误 :run() 包装器会自动处理
使用实际的模型 ID :使用适用于该提供者的实际模型 ID
为复杂逻辑添加注释 :解释非显而易见的代码模式
在适当时复用工具 :使用 weatherTool 或在 tools/ 中创建新的可复用工具
每周安装量
528
仓库
GitHub 星标
23.0K
首次出现
2026 年 1 月 23 日
安全审计
安装在
claude-code425
cursor382
opencode370
codex359
gemini-cli358
github-copilot321
The examples/ai-functions/ directory contains scripts for validating, testing, and iterating on AI SDK functions across providers.
Examples are organized by AI SDK function in examples/ai-functions/src/:
| Directory | Purpose |
|---|---|
generate-text/ | Non-streaming text generation with generateText() |
stream-text/ | Streaming text generation with streamText() |
generate-object/ | Structured output generation with generateObject() |
stream-object/ | Streaming structured output with streamObject() |
agent/ | ToolLoopAgent examples for agentic workflows |
embed/ | Single embedding generation with embed() |
embed-many/ | Batch embedding generation with embedMany() |
generate-image/ | Image generation with generateImage() |
generate-speech/ | Text-to-speech with generateSpeech() |
transcribe/ | Audio transcription with transcribe() |
rerank/ | Document reranking with rerank() |
middleware/ | Custom middleware implementations |
registry/ | Provider registry setup and usage |
telemetry/ | OpenTelemetry integration |
complex/ | Multi-component examples (agents, routers) |
lib/ | Shared utilities (not examples) |
tools/ | Reusable tool definitions |
Examples follow the pattern: {provider}-{feature}.ts
| Pattern | Example | Description |
|---|---|---|
{provider}.ts | openai.ts | Basic provider usage |
{provider}-{feature}.ts | openai-tool-call.ts | Specific feature |
{provider}-{sub-provider}.ts | amazon-bedrock-anthropic.ts | Provider with sub-provider |
{provider}-{sub-provider}-{feature}.ts |
All examples use the run() wrapper from lib/run.ts which:
.envimport { providerName } from '@ai-sdk/provider-name';
import { generateText } from 'ai';
import { run } from '../lib/run';
run(async () => {
const result = await generateText({
model: providerName('model-id'),
prompt: 'Your prompt here.',
});
console.log(result.text);
console.log('Token usage:', result.usage);
console.log('Finish reason:', result.finishReason);
});
import { providerName } from '@ai-sdk/provider-name';
import { streamText } from 'ai';
import { printFullStream } from '../lib/print-full-stream';
import { run } from '../lib/run';
run(async () => {
const result = streamText({
model: providerName('model-id'),
prompt: 'Your prompt here.',
});
await printFullStream({ result });
});
import { providerName } from '@ai-sdk/provider-name';
import { generateText, tool } from 'ai';
import { z } from 'zod';
import { run } from '../lib/run';
run(async () => {
const result = await generateText({
model: providerName('model-id'),
tools: {
myTool: tool({
description: 'Tool description',
inputSchema: z.object({
param: z.string().describe('Parameter description'),
}),
execute: async ({ param }) => {
return { result: `Processed: ${param}` };
},
}),
},
prompt: 'Use the tool to...',
});
console.log(JSON.stringify(result, null, 2));
});
import { providerName } from '@ai-sdk/provider-name';
import { generateObject } from 'ai';
import { z } from 'zod';
import { run } from '../lib/run';
run(async () => {
const result = await generateObject({
model: providerName('model-id'),
schema: z.object({
name: z.string(),
items: z.array(z.string()),
}),
prompt: 'Generate a...',
});
console.log(JSON.stringify(result.object, null, 2));
console.log('Token usage:', result.usage);
});
From the examples/ai-functions directory:
pnpm tsx src/generate-text/openai.ts
pnpm tsx src/stream-text/openai-tool-call.ts
pnpm tsx src/agent/openai-generate.ts
Write examples when:
Adding a new provider : Create basic examples for each supported API (generateText, streamText, generateObject, etc.)
Implementing a new feature : Demonstrate the feature with at least one provider example
Reproducing a bug : Create an example that shows the issue for debugging
Adding provider-specific options : Show how to use providerOptions for provider-specific settings
Creating test fixtures : Use examples to generate API response fixtures (see capture-api-response-test-fixture skill)
The lib/ directory contains shared utilities:
| File | Purpose |
|---|---|
run.ts | Error-handling wrapper with .env loading |
print.ts | Clean object printing (removes undefined values) |
print-full-stream.ts | Colored streaming output for tool calls, reasoning, text |
save-raw-chunks.ts | Save streaming chunks for test fixtures |
present-image.ts | Display images in terminal |
import { print } from '../lib/print';
// Pretty print objects without undefined values
print('Result:', result);
print('Usage:', result.usage, { depth: 2 });
import { printFullStream } from '../lib/print-full-stream';
const result = streamText({ ... });
await printFullStream({ result }); // Colored output for text, tool calls, reasoning
The tools/ directory contains reusable tool definitions:
import { weatherTool } from '../tools/weather-tool';
const result = await generateText({
model: openai('gpt-4o'),
tools: { weather: weatherTool },
prompt: 'What is the weather in San Francisco?',
});
Keep examples focused : Each example should demonstrate one feature or use case
Use descriptive prompts : Make it clear what the example is testing
Handle errors gracefully : The run() wrapper handles this automatically
Use realistic model IDs : Use actual model IDs that work with the provider
Add comments for complex logic : Explain non-obvious code patterns
Reuse tools when appropriate : Use weatherTool or create new reusable tools in tools/
Weekly Installs
528
Repository
GitHub Stars
23.0K
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code425
cursor382
opencode370
codex359
gemini-cli358
github-copilot321
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
140,500 周安装
google-vertex-anthropic-cache-control.ts |
| Sub-provider with feature |
save-audio.ts| Save audio files to disk |