develop-ai-functions-example

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI Functions Examples

AI Functions 示例

The
examples/ai-functions/
directory contains scripts for validating, testing, and iterating on AI SDK functions across providers.
examples/ai-functions/
目录包含用于跨供应商验证、测试和迭代AI SDK功能的脚本。

Example Categories

示例分类

Examples are organized by AI SDK function in
examples/ai-functions/src/
:
DirectoryPurpose
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/ai-functions/src/
中按AI SDK功能进行组织:
目录用途
generate-text/
使用
generateText()
实现非流式文本生成
stream-text/
使用
streamText()
实现流式文本生成
generate-object/
使用
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/
可复用工具定义

File Naming Convention

文件命名规范

Examples follow the pattern:
{provider}-{feature}.ts
PatternExampleDescription
{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
google-vertex-anthropic-cache-control.ts
Sub-provider with feature
示例遵循以下命名模式:
{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
子供应商的特定功能演示

Example Structure

示例结构

All examples use the
run()
wrapper from
lib/run.ts
which:
  • Loads environment variables from
    .env
  • Provides error handling with detailed API error logging
所有示例均使用
lib/run.ts
中的
run()
包装器,该包装器:
  • .env
    加载环境变量
  • 提供带有详细API错误日志的错误处理

Basic Template

基础模板

typescript
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.finishReason);
});
typescript
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.finishReason);
});

Streaming Template

流式模板

typescript
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 });
});
typescript
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 });
});

Tool Calling Template

工具调用模板

typescript
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));
});
typescript
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));
});

Structured Output Template

结构化输出模板

typescript
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);
});
typescript
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);
});

Running Examples

运行示例

From the
examples/ai-functions
directory:
bash
pnpm tsx src/generate-text/openai.ts
pnpm tsx src/stream-text/openai-tool-call.ts
pnpm tsx src/agent/openai-generate.ts
examples/ai-functions
目录下执行以下命令:
bash
pnpm tsx src/generate-text/openai.ts
pnpm tsx src/stream-text/openai-tool-call.ts
pnpm tsx src/agent/openai-generate.ts

When to Write Examples

编写示例的场景

Write examples when:
  1. Adding a new provider: Create basic examples for each supported API (
    generateText
    ,
    streamText
    ,
    generateObject
    , etc.)
  2. Implementing a new feature: Demonstrate the feature with at least one provider example
  3. Reproducing a bug: Create an example that shows the issue for debugging
  4. Adding provider-specific options: Show how to use
    providerOptions
    for provider-specific settings
  5. Creating test fixtures: Use examples to generate API response fixtures (see
    capture-api-response-test-fixture
    skill)
在以下场景中编写示例:
  1. 添加新供应商:为每个支持的API创建基础示例(
    generateText
    streamText
    generateObject
    等)
  2. 实现新功能:至少使用一个供应商示例来演示该功能
  3. 复现Bug:创建示例以展示问题用于调试
  4. 添加供应商特定选项:展示如何使用
    providerOptions
    设置供应商特定配置
  5. 创建测试夹具:使用示例生成API响应夹具(参考
    capture-api-response-test-fixture
    技能)

Utility Helpers

工具助手

The
lib/
directory contains shared utilities:
FilePurpose
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
save-audio.ts
Save audio files to disk
lib/
目录包含共享工具:
文件用途
run.ts
带有.env加载的错误处理包装器
print.ts
简洁的对象打印(移除undefined值)
print-full-stream.ts
用于工具调用、推理过程和文本的彩色流式输出
save-raw-chunks.ts
保存流式数据块用于测试夹具
present-image.ts
在终端中显示图像
save-audio.ts
将音频文件保存到磁盘

Using print utilities

使用打印工具

typescript
import { print } from '../lib/print';

// Pretty print objects without undefined values
print('Result:', result);
print('Usage:', result.usage, { depth: 2 });
typescript
import { print } from '../lib/print';

// 优雅打印对象,自动移除undefined值
print('Result:', result);
print('Usage:', result.usage, { depth: 2 });

Using printFullStream

使用printFullStream

typescript
import { printFullStream } from '../lib/print-full-stream';

const result = streamText({ ... });
await printFullStream({ result }); // Colored output for text, tool calls, reasoning
typescript
import { printFullStream } from '../lib/print-full-stream';

const result = streamText({ ... });
await printFullStream({ result }); // 文本、工具调用、推理过程的彩色输出

Reusable Tools

可复用工具

The
tools/
directory contains reusable tool definitions:
typescript
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?',
});
tools/
目录包含可复用工具定义:
typescript
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?',
});

Best Practices

  1. Keep examples focused: Each example should demonstrate one feature or use case
  2. Use descriptive prompts: Make it clear what the example is testing
  3. Handle errors gracefully: The
    run()
    wrapper handles this automatically
  4. Use realistic model IDs: Use actual model IDs that work with the provider
  5. Add comments for complex logic: Explain non-obvious code patterns
  6. Reuse tools when appropriate: Use
    weatherTool
    or create new reusable tools in
    tools/