mcpField
A
ai-sdk-6-skills

ai-sdk-6-skills

github.com/gocallum開発23481 回インストール40 週間前に更新
リポジトリ

ai-sdk-6-skills について

ai-sdk-6-skillsは、エージェントや生成AIアプリを開発する人向けに、Vercel AI SDK 6 Betaの開発情報をまとめています。ツールループ、構造化出力、Groq、AI Gatewayに加え、プロバイダーのルーティングやフォールバック、React UI連携を扱います。

主な機能

  1. 01ToolLoopAgentと実行フロー制御
  2. 02ツール実行の承認と構造化出力
  3. 03Groqプロバイダーの設定例
  4. 04AI Gatewayのプロバイダールーティング
  5. 05React UI連携パターン

活用シーン

  1. 01ツールを呼び出すエージェントの構築
  2. 02機密性の高いツール操作での確認要求
  3. 03モデルプロバイダー間のフォールバック設定
  4. 04Groqでのテキストや構造化データの生成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/gocallum/nextjs16-agent-skills --skill ai-sdk-6-skills

インストール後、Claude Code で/ai-sdk-6-skillsを入力して読み込まれたか確認します。

詳細

リンク

インストール

pnpm add ai@beta @ai-sdk/openai@beta @ai-sdk/react@beta @ai-sdk/groq@beta

注:ベータ期間中は、パッチリリースで破壊的変更が発生する可能性があるため、バージョンを固定してください。

AI SDK 6 の新機能

1. エージェントの抽象化(新機能)

実行フロー、ツールループ、状態管理を完全に制御できる、エージェント構築のための統一インターフェースです。

import { ToolLoopAgent } from 'ai';
import { tool } from 'ai';
import { z } from 'zod';

const weatherTool = tool({
  description: 'Get weather for a location',
  inputSchema: z.object({ city: z.string() }),
  execute: async ({ city }) => ({ temperature: 72, condition: 'sunny' }),
});

const agent = new ToolLoopAgent({
  model: 'groq/llama-3.3-70b-versatile', // or any model
  instructions: 'You are a helpful weather assistant.',
  tools: { weather: weatherTool },
});

// Use the agent
const result = await agent.generate({
  prompt: 'What is the weather in San Francisco?',
});

console.log(result.output);
2. ツール実行の承認(新機能)

機密性の高いツールを実行する前に、ユーザーに確認を求めます。

import { tool } from 'ai';
import { z } from 'zod';

const paymentTool = tool({
  description: 'Process a payment',
  inputSchema: z.object({
    amount: z.number(),
    recipient: z.string(),
  }),
  needsApproval: true, // Require approval
  execute: async ({ amount, recipient }) => {
    return { success: true, id: 'txn-123' };
  },
});

クライアント側の承認 UI:

export function PaymentToolView({ invocation, addToolApprovalResponse }) {
  if (invocation.state === 'approval-requested') {
    return (
      <div>
        <p>Process payment of ${invocation.input.amount} to {invocation.input.recipient}?</p>
        <button
          onClick={() =>
            addToolApprovalResponse({
              id: invocation.approval.id,
              approved: true,
            })
          }
        >
          Approve
        </button>
        <button
          onClick={() =>
            addToolApprovalResponse({
              id: invocation.approval.id,
              approved: false,
            })
          }
        >
          Deny
        </button>
      </div>
    );
  }
  return null;
}
3. 構造化出力とツール呼び出し(安定版)

ツール呼び出しと構造化出力の生成を組み合わせます:

import { ToolLoopAgent, Output } from 'ai';
import { z } from 'zod';

const agent = new ToolLoopAgent({
  model: 'groq/llama-3.3-70b-versatile',
  tools: { /* ... */ },
  output: Output.object({
    schema: z.object({
      summary: z.string(),
      temperature: z.number(),
      recommendation: z.string(),
    }),
  }),
});

const { output } = await agent.generate({
  prompt: 'What is the weather in San Francisco and what should I wear?',
});

console.log(output);
// { summary: '...', temperature: 72, recommendation: '...' }
4. 再ランキングのサポート(新機能)

ドキュメントを並べ替えて、検索の関連性を高めます:

import { rerank } from 'ai';
import { cohere } from '@ai-sdk/cohere';

const { ranking } = await rerank({
  model: cohere.reranking('rerank-v3.5'),
  documents: [
    'sunny day at the beach',
    'rainy afternoon in the city',
    'snowy night in the mountains',
  ],
  query: 'talk about rain',
  topN: 2,
});

console.log(ranking);
// [
//   { originalIndex: 1, score: 0.9, document: 'rainy afternoon...' },
//   { originalIndex: 0, score: 0.3, document: 'sunny day...' }
// ]

AI SDK 5 からの移行

最小限の破壊的変更が予想されます。ほとんどの AI SDK 5 のコードは、わずかな変更で動作します。

主な違い:

  • エージェントの抽象化により、その場しのぎのパターンが置き換えられます。ToolLoopAgent への移行を検討してください。
  • 構造化出力が generateText / streamText で使えるようになりました(stopWhen が必要です)。
  • @ai-sdk/* パッケージの API は、ベータ期間中に小規模な調整が加えられる可能性があります。

Groq プロバイダー(オープンウェイトモデル)

セットアップ
pnpm add @ai-sdk/groq

環境:

GROQ_API_KEY=your_groq_api_key
利用可能なオープンウェイトモデル

AI SDK 6 で利用できる、Groq の人気モデル:

  • llama-3.3-70b-versatile(Llama 3.3、70B、バランス型)
  • llama-3.1-8b-instant(Llama 3.1、8B、高速)
  • mixtral-8x7b-32768(Mixture of Experts)
  • gemma2-9b-it(Google Gemma 2)
  • qwen/qwen3-32b(Qwen 3)

一覧はGroq コンソールを参照してください。

Llama の基本的な例
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';

const { text } = await generateText({
  model: groq('llama-3.3-70b-versatile'),
  prompt: 'Write a TypeScript function to compute Fibonacci.',
});

console.log(text);
Llama による構造化出力(Groq)
import { groq } from '@ai-sdk/groq';
import { generateObject } from 'ai';
import { z } from 'zod';

const result = await generateObject({
  model: groq('llama-3.3-70b-versatile'),
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(z.string()),
      instructions: z.array(z.string()),
    }),
  }),
  prompt: 'Generate a simple pasta recipe.',
  providerOptions: {
    groq: {
      structuredOutputs: true, // Enable for supported models
    },
  },
});

console.log(JSON.stringify(result.object, null, 2));
Llama によるツールの使用(Groq)
import { groq } from '@ai-sdk/groq';
import { generateText, tool } from 'ai';
import { z } from 'zod';

const weatherTool = tool({
  description: 'Get weather for a city',
  inputSchema: z.object({ city: z.string() }),
  execute: async ({ city }) => ({ temp: 72, condition: 'sunny' }),
});

const { text } = await generateText({
  model: groq('llama-3.3-70b-versatile'),
  prompt: 'What is the weather in NYC and LA?',
  tools: { weather: weatherTool },
});

console.log(text);
推論モデル(Groq)

Groq では、qwen/qwen3-32b や deepseek-r1-distill-llama-70b などの推論モデルを利用できます:

import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';

const { text } = await generateText({
  model: groq('qwen/qwen3-32b'),
  providerOptions: {
    groq: {
      reasoningFormat: 'parsed', // 'parsed', 'hidden', or 'raw'
      reasoningEffort: 'default', // low, medium, high
    },
  },
  prompt: 'How many "r"s are in the word "strawberry"?',
});

console.log(text);
Llama での画像入力(Groq マルチモーダル)
import { groq } from '@ai-sdk/groq';
import { generateText } from 'ai';

const { text } = await generateText({
  model: groq('meta-llama/llama-4-scout-17b-16e-instruct'), // Multi-modal model
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'What is in this image?' },
        { type: 'image', image: 'https://example.com/image.jpg' },
      ],
    },
  ],
});

console.log(text);

Vercel AI Gateway

概要

単一の API を通じて、20 以上のプロバイダー(OpenAI、Anthropic、Google、Groq、xAI、Mistral など)のモデルにアクセスできる統一インターフェースです。Vercel アカウントとクレジットカードが必要です。

セットアップ
AI_GATEWAY_API_KEY=your_gateway_api_key

Vercel Dashboard > AI Gateway からキーを取得してください。

⚠️ 注:Gateway の利用にはクレジットカードが必要です。Gateway 経由でルーティングされるモデル呼び出しには料金が発生します。

認証
API キー認証

環境変数またはコード内で直接設定します:

import { createGateway } from 'ai';

const gateway = createGateway({
  apiKey: process.env.AI_GATEWAY_API_KEY,
});
OIDC 認証(Vercel デプロイ)

Vercel にデプロイした場合は、OIDC トークンを使って自動認証できます(API キーは不要です):

本番環境/プレビュー:OIDC は自動的に処理されるため、設定は不要です。

ローカル開発:

  1. Vercel CLI をインストールして認証します:vercel login
  2. OIDC トークンを取得します:vercel env pull
  3. vercel dev を使用して開発サーバーを起動します(トークンの更新は自動で処理されます)

注:OIDC トークンの有効期限は 12 時間です。自動更新には vercel dev を使用するか、手動で再度 vercel env pull を実行してください。

# Start dev with automatic token management
vercel dev
基本的な使い方
import { generateText } from 'ai';

// Plain model string format: creator/model-name
const { text } = await generateText({
  model: 'openai/gpt-5',
  prompt: 'Explain quantum computing.',
});

console.log(text);
Gateway インスタンス
import { createGateway } from 'ai';

const gateway = createGateway({
  apiKey: process.env.AI_GATEWAY_API_KEY,
});

const { text } = await generateText({
  model: gateway('anthropic/claude-sonnet-4'),
  prompt: 'Write a haiku about AI.',
});

console.log(text);
モデルの動的な検出
import { gateway } from 'ai';

const availableModels = await gateway.getAvailableModels();

availableModels.models.forEach((model) => {
  console.log(`${model.id}: ${model.name}`);
  if (model.pricing) {
    console.log(`  Input: $${model.pricing.input}/token`);
    console.log(`  Output: $${model.pricing.output}/token`);
  }
});

// Use first model
const { text } = await generateText({
  model: availableModels.models[0].id,
  prompt: 'Hello world',
});
クレジットの使用状況を確認する
import { gateway } from 'ai';

const credits = await gateway.getCredits();
console.log(`Balance: ${credits.balance} credits`);
console.log(`Total used: ${credits.total_used} credits`);
Gateway でのストリーミング
import { streamText } from 'ai';

const { textStream } = await streamText({
  model: 'openai/gpt-5',
  prompt: 'Explain serverless architecture.',
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}
Gateway でのツールの使用
import { generateText, tool } from 'ai';
import { z } from 'zod';

const weatherTool = tool({
  description: 'Get weather',
  inputSchema: z.object({ location: z.string() }),
  execute: async ({ location }) => `Sunny in ${location}`,
});

const { text } = await generateText({
  model: 'xai/grok-4', // Via Gateway
  prompt: 'What is the weather in SF?',
  tools: { getWeather: weatherTool },
});

console.log(text);
独自のキーを使用する(BYOK)

Gateway に独自のプロバイダー認証情報を接続して、プライベートリソースにアクセスします:

import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';

const { text } = await generateText({
  model: 'anthropic/claude-sonnet-4',
  prompt: 'Use my Anthropic account',
  providerOptions: {
    gateway: {
      byok: {
        anthropic: [{ apiKey: 'sk-ant-...' }],
      },
    } satisfies GatewayProviderOptions,
  },
});

Vercel チームの AI Gateway 設定で BYOK 認証情報を設定すれば、その後コードを変更する必要はありません。

プロバイダー側で実行されるツール

一部のプロバイダーでは、サーバー側で実行されるツール(例:OpenAI のウェブ検索)が提供されています。プロバイダーをインポートして Gateway 経由で使用します:

import { generateText, stepCountIs } from 'ai';
import { openai } from '@ai-sdk/openai';

const result = await generateText({
  model: 'openai/gpt-5-mini',
  prompt: 'What is the Vercel AI Gateway?',
  stopWhen: stepCountIs(10),
  tools: {
    web_search: openai.tools.webSearch({}),
  },
});

console.log(result.text);

注:アカウント固有の設定が必要なツール(例:Claude Agent Skills)では、BYOK を介してプロバイダーに直接アクセスする必要がある場合があります。

プロバイダーのルーティングとフォールバック

コアのルーティングオプション:

  • order:プロバイダーを順番に試します(フォールバックの優先順位)
  • only:特定のプロバイダーのみに制限します
  • models:プライマリモデルが失敗した場合、代替モデルにフォールバックします
  • user:エンドユーザーごとに使用状況を追跡します
  • tags:分析用にリクエストを分類します
  • zeroDataRetention:データを保持しないプロバイダーのみを使用します
  • byok:リクエスト単位の BYOK 認証情報
例:プロバイダーとモデルのフォールバック
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';

const { text } = await generateText({
  model: 'openai/gpt-4o', // Primary model
  prompt: 'Write a TypeScript haiku',
  providerOptions: {
    gateway: {
      order: ['vertex', 'anthropic'], // Try Vertex AI first, then Anthropic
      only: ['vertex', 'anthropic'], // Only allow these providers
      models: ['openai/gpt-5-nano', 'gemini-2.0-flash'], // Fallback models
      user: 'user-123',
      tags: ['code-gen', 'v2'],
    } satisfies GatewayProviderOptions,
  },
});

// Fallback sequence:
// 1. Try vertex with openai/gpt-4o
// 2. Try anthropic with openai/gpt-4o
// 3. Try vertex with openai/gpt-5-nano
// 4. Try anthropic with openai/gpt-5-nano
// etc.
例:使用状況の追跡
import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';

const { text } = await generateText({
  model: 'anthropic/claude-sonnet-4',
  prompt: 'Summarize this document...',
  providerOptions: {
    gateway: {
      user: 'user-abc-123', // Track per end-user
      tags: ['document-summary', 'premium-feature'],
    } satisfies GatewayProviderOptions,
  },
});

// View analytics by user and feature in Vercel Dashboard
ゼロデータ保持

機密データについて、ゼロデータ保持ポリシーを持つプロバイダーのみにリクエストをルーティングします:

import { generateText } from 'ai';
import type { GatewayProviderOptions } from '@ai-sdk/gateway';

const { text } = await generateText({
  model: 'anthropic/claude-sonnet-4',
  prompt: 'Process sensitive document...',
  providerOptions: {
    gateway: {
      zeroDataRetention: true, // Enforce zero data retention
    } satisfies GatewayProviderOptions,
  },
});

zeroDataRetention: true の場合、Gateway はデータを保持しないプロバイダーのみにリクエストをルーティングします。省略するか false に設定した場合、強制されません。

主要な概念

エージェント向けの呼び出しオプション

実行時にエージェントを動的に設定します:

import { ToolLoopAgent } from 'ai';
import { z } from 'zod';

const supportAgent = new ToolLoopAgent({
  model: 'groq/llama-3.3-70b-versatile',
  callOptionsSchema: z.object({
    userId: z.string(),
    accountType: z.enum(['free', 'pro', 'enterprise']),
  }),
  instructions: 'You are a support agent.',
  prepareCall: ({ options, ...settings }) => ({
    ...settings,
    instructions:
      settings.instructions +
      `\nUser: ${options.userId}, Account: ${options.accountType}`,
  }),
});

const result = await supportAgent.generate({
  prompt: 'How do I upgrade?',
  options: {
    userId: 'user-456',
    accountType: 'free',
  },
});
React との UI 統合
import { createAgentUIStreamResponse } from 'ai';
import { useChat } from '@ai-sdk/react';
import { InferAgentUIMessage } from 'ai';

// Server-side
export async function POST(request: Request) {
  const { messages } = await request.json();
  return createAgentUIStreamResponse({
    agent: weatherAgent,
    messages,
  });
}

// Client-side
type AgentMessage = InferAgentUIMessage<typeof weatherAgent>;
const { messages, sendMessage } = useChat<AgentMessage>();

ベストプラクティス

Groq
  • パフォーマンスとコストのバランスを取るには、llama-3.3-70b-versatile を使用します。
  • 低レイテンシーの軽量なタスクには、llama-3.1-8b-instant を使用します。
  • 複数ツールの実行を高速化するには、parallelToolCalls: true(デフォルト)を有効にします。
  • ときどき失敗しても許容できる場合は、レート制限を 10 倍にするために serviceTier: 'flex' を使用します。
Vercel AI Gateway
  • 必ずクレジットカードを登録してください。ゲートウェイはトークンごとに課金されます。
  • ルーティングとコストを制御するには、only / order を使用します。
  • 使用料金の追跡とデバッグには、user と tags を使用します。
  • 機密データには zeroDataRetention を有効にします。
  • 使用状況を監視するため、gateway.getCredits() を定期的に確認します。
エージェント
  • まずは ToolLoopAgent を使用し、必要な場合にのみ拡張します。
  • 構造化出力とツール呼び出しを組み合わせて、充実した応答を生成します。
  • 支払い/削除操作にはツールの承認を使用します。
  • ループの反復回数を制御するには、stopWhen を設定します(デフォルト:stepCountIs(20))。

一般的なパターン

RAG エージェント
const ragAgent = new ToolLoopAgent({
  model: 'groq/llama-3.3-70b-versatile',
  tools: {
    searchDocs: tool({
      description: 'Search documentation',
      inputSchema: z.object({ query: z.string() }),
      execute: async ({ query }) => {
        // Call vector DB (Upstash, Pinecone, etc.)
        return { docs: [/* ... */] };
      },
    }),
  },
  instructions: 'Answer questions by searching docs.',
});
複数プロバイダーでのフォールバック
const { text } = await generateText({
  model: 'anthropic/claude-sonnet-4',
  prompt: 'Complex task requiring reasoning',
  providerOptions: {
    gateway: {
      models: ['openai/gpt-5', 'gemini-2.0-flash'],
    },
  },
});
コストを最適化した選択
const isSensitive = userQuery.includes('payment');
const model = isSensitive 
  ? 'anthropic/claude-sonnet-4' 
  : 'openai/gpt-5-nano';

const { text } = await generateText({
  model,
  prompt: userQuery,
});

タイムライン

  • AI SDK 6 Beta:現在利用可能です(バージョンを固定してください)
  • 安定版リリース:2025 年末

コメント