Readouble

Laravel 12.x Laravel AI SDK

導入Introduction

Laravel AI SDKは、OpenAI、Anthropic、GeminiなどのAIプロバイダとやり取りするための、統一された表現力豊かなAPIを提供します。AI SDKを使用すると、ツールや構造化出力を備えたインテリジェントなエージェントの構築、画像の生成、音声の合成と文字起こし、ベクトル埋め込みの作成などを、すべてLaravelフレンドリーな一貫したインターフェイスで行えます。The Laravel AI SDK[https://github.com/laravel/ai] provides a unified, expressive API for interacting with AI providers such as OpenAI, Anthropic, Gemini, and more. With the AI SDK, you can build intelligent agents with tools and structured output, generate images, synthesize and transcribe audio, create vector embeddings, and much more — all using a consistent, Laravel-friendly interface.

インストールInstallation

Composerを使い、Laravel AI SDKをインストールできます。You can install the Laravel AI SDK via Composer:

composer require laravel/ai

次に、vendor:publish Artisanコマンドを使用して、AI SDKの設定ファイルとマイグレーションファイルをリソース公開してください。Next, you should publish the AI SDK configuration and migration files using the vendor:publish Artisan command:

php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"

最後に、アプリケーションのデータベースマイグレーションを実行してください。これにより、AI SDKが会話の保存に使用するagent_conversationsテーブルとagent_conversation_messagesテーブルが作成されます。Finally, you should run your application's database migrations. This will create a agent_conversations and agent_conversation_messages table that the AI SDK uses to power its conversation storage:

php artisan migrate

設定Configuration

AIプロバイダの認証情報は、アプリケーションのconfig/ai.php設定ファイル、またはアプリケーションの.envファイル内の環境変数として定義できます。You may define your AI provider credentials in your application's config/ai.php configuration file or as environment variables in your application's .env file:

ANTHROPIC_API_KEY=
COHERE_API_KEY=
ELEVENLABS_API_KEY=
GEMINI_API_KEY=
MISTRAL_API_KEY=
OLLAMA_API_KEY=
OPENAI_API_KEY=
JINA_API_KEY=
VOYAGEAI_API_KEY=
XAI_API_KEY=

テキスト、画像、音声、文字起こし、埋め込みに使用されるデフォルトのモデルも、アプリケーションのconfig/ai.php設定ファイルで設定できます。The default models used for text, images, audio, transcription, and embeddings may also be configured in your application's config/ai.php configuration file.

カスタムベースURLCustom Base URLs

デフォルトでは、Laravel AI SDKは各プロバイダの公開APIエンドポイントへ直接接続します。しかし、APIキー管理の集約、レート制限の実装、または企業ゲートウェイを介したトラフィックのルーティングのためにプロキシサービスを使用する場合など、別のエンドポイントを介してリクエストをルーティングする必要があるかもしれません。By default, the Laravel AI SDK connects directly to each provider's public API endpoint. However, you may need to route requests through a different endpoint - for example, when using a proxy service to centralize API key management, implement rate limiting, or route traffic through a corporate gateway.

プロバイダ設定にurlパラメータを追加すると、カスタムベースURLを設定できます。You may configure custom base URLs by adding a url parameter to your provider configuration:

'providers' => [
    'openai' => [
        'driver' => 'openai',
        'key' => env('OPENAI_API_KEY'),
        'url' => env('OPENAI_BASE_URL'),
    ],

    'anthropic' => [
        'driver' => 'anthropic',
        'key' => env('ANTHROPIC_API_KEY'),
        'url' => env('ANTHROPIC_BASE_URL'),
    ],
],

これは、プロキシサービス(LiteLLMやAzure OpenAI Gatewayなど)を介してリクエストをルーティングする場合や、代替エンドポイントを使用する場合に便利です。This is useful when routing requests through a proxy service (such as LiteLLM or Azure OpenAI Gateway) or using alternative endpoints.

カスタムベースURLは、OpenAI、Anthropic、Gemini、Groq、Cohere、DeepSeek、xAI、OpenRouterのプロバイダでサポートしています。Custom base URLs are supported for the following providers: OpenAI, Anthropic, Gemini, Groq, Cohere, DeepSeek, xAI, and OpenRouter.

プロバイダのサポートProvider Support

AI SDKは、その機能全体でさまざまなプロバイダをサポートしています。以下の表は、各機能で利用可能なプロバイダをまとめたものです。The AI SDK supports a variety of providers across its features. The following table summarizes which providers are available for each feature:

機能Feature プロバイダProviders
テキストText OpenAI, Anthropic, Gemini, Groq, xAI, DeepSeek, Mistral, OllamaOpenAI, Anthropic, Gemini, Groq, xAI, DeepSeek, Mistral, Ollama
画像Images OpenAI, Gemini, xAIOpenAI, Gemini, xAI
TTSTTS OpenAI, ElevenLabsOpenAI, ElevenLabs
STTSTT OpenAI, ElevenLabs, MistralOpenAI, ElevenLabs, Mistral
埋め込みEmbeddings OpenAI, Gemini, Cohere, Mistral, Jina, VoyageAIOpenAI, Gemini, Cohere, Mistral, Jina, VoyageAI
リランクReranking Cohere, JinaCohere, Jina
ファイルFiles OpenAI, Anthropic, GeminiOpenAI, Anthropic, Gemini

エージェントAgents

エージェントは、Laravel AI SDKでAIプロバイダとやり取りするための基本的な構成要素です。各エージェントは、大規模言語モデルとやり取りするために必要な指示、会話コンテキスト、ツール、および出力スキーマをカプセル化した専用のPHPクラスです。エージェントを、セールスコーチ、ドキュメントアナライザー、サポートボットなどの特殊なアシスタントとして考えてください。一度設定すれば、アプリケーション全体で必要に応じてプロンプトを送れます。Agents are the fundamental building block for interacting with AI providers in the Laravel AI SDK. Each agent is a dedicated PHP class that encapsulates the instructions, conversation context, tools, and output schema needed to interact with a large language model. Think of an agent as a specialized assistant — a sales coach, a document analyzer, a support bot — that you configure once and prompt as needed throughout your application.

make:agent Artisanコマンドを使用して、エージェントを作成できます。You can create an agent via the make:agent Artisan command:

php artisan make:agent SalesCoach

php artisan make:agent SalesCoach --structured

生成されたエージェントクラス内で、システムプロンプト/指示、メッセージコンテキスト、利用可能なツール、および出力スキーマ(該当する場合)を定義できます。Within the generated agent class, you can define the system prompt / instructions, message context, available tools, and output schema (if applicable):

<?php

namespace App\Ai\Agents;

use App\Ai\Tools\RetrievePreviousTranscripts;
use App\Models\History;
use App\Models\User;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Contracts\HasTools;
use Laravel\Ai\Promptable;
use Stringable;

class SalesCoach implements Agent, Conversational, HasTools, HasStructuredOutput
{
    use Promptable;

    public function __construct(public User $user) {}

    /**
     * エージェントが従うべき指示を取得
     */
    public function instructions(): Stringable|string
    {
        return 'あなたはセールスコーチです。文字起こしを分析し、フィードバックと総合的なセールス強度スコアを提供してください。';
    }

    /**
     * これまでの会話を構成するメッセージリストを取得
     */
    public function messages(): iterable
    {
        return History::where('user_id', $this->user->id)
            ->latest()
            ->limit(50)
            ->get()
            ->reverse()
            ->map(function ($message) {
                return new Message($message->role, $message->content);
            })->all();
    }

    /**
     * エージェントが利用可能なツールを取得
     *
     * @return Tool[]
     */
    public function tools(): iterable
    {
        return [
            new RetrievePreviousTranscripts,
        ];
    }

    /**
     * エージェントの構造化出力スキーマ定義を取得
     */
    public function schema(JsonSchema $schema): array
    {
        return [
            'feedback' => $schema->string()->required(),
            'score' => $schema->integer()->min(1)->max(10)->required(),
        ];
    }
}

プロンプトPrompting

エージェントにプロンプトを送るには、まずmakeメソッドまたは標準的なインスタンス化を使用してインスタンスを作成し、次にpromptを呼び出します。To prompt an agent, first create an instance using the make method or standard instantiation, then call prompt:

$response = (new SalesCoach)
    ->prompt('このセールスの文字起こしを分析して...');

$response = SalesCoach::make()
    ->prompt('このセールスの文字起こしを分析して...');

return (string) $response;

makeメソッドはサービスコンテナからエージェントを解決するため、自動的な依存注入が可能です。エージェントのコンストラクタに引数を渡すこともできます。The make method resolves your agent from the container, allowing automatic dependency injection. You may also pass arguments to the agent's constructor:

$agent = SalesCoach::make(user: $user);

promptメソッドに追加の引数を渡すことで、プロンプト送信時にデフォルトのプロバイダ、モデル、またはHTTPタイムアウトをオーバーライドできます。By passing additional arguments to the prompt method, you may override the default provider, model, or HTTP timeout when prompting:

$response = (new SalesCoach)->prompt(
    'このセールスの文字起こしを分析して...',
    provider: 'anthropic',
    model: 'claude-haiku-4-5-20251001',
    timeout: 120,
);

会話コンテキストConversation Context

エージェントがConversationalインターフェイスを実装している場合、messagesメソッドを使用して、該当する以前の会話コンテキストを返せます。If your agent implements the Conversational interface, you may use the messages method to return the previous conversation context, if applicable:

use App\Models\History;
use Laravel\Ai\Messages\Message;

/**
 * これまでの会話を構成するメッセージリストを取得
 */
public function messages(): iterable
{
    return History::where('user_id', $this->user->id)
        ->latest()
        ->limit(50)
        ->get()
        ->reverse()
        ->map(function ($message) {
            return new Message($message->role, $message->content);
        })->all();
}

会話の記憶Remembering Conversations

注意: RemembersConversationsトレイトを使用する前に、vendor:publish Artisanコマンドを使用してAI SDKのマイグレーションを公開し、実行する必要があります。これらのマイグレーションにより、会話を保存するために必要なデータベーステーブルが作成されます。Note: Before using the RemembersConversations trait, you should publish and run the AI SDK migrations using the vendor:publish Artisan command. These migrations will create the necessary database tables to store conversations.

Laravelでエージェントの会話履歴を自動的に保存および取得したい場合は、RemembersConversationsトレイトを使用します。このトレイトは、Conversationalインターフェイスを手作業で実装しなくても、会話メッセージをデータベースへ永続化する簡単な方法を提供しています。If you would like Laravel to automatically store and retrieve conversation history for your agent, you may use the RemembersConversations trait. This trait provides a simple way to persist conversation messages to the database without manually implementing the Conversational interface:

<?php

namespace App\Ai\Agents;

use Laravel\Ai\Concerns\RemembersConversations;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Promptable;

class SalesCoach implements Agent, Conversational
{
    use Promptable, RemembersConversations;

    /**
     * エージェントが従うべき指示を取得
     */
    public function instructions(): string
    {
        return 'あなたはセールスコーチです...';
    }
}

あるユーザーで新しい会話を開始するには、プロンプトを送る前にforUserメソッドを呼び出してください。To start a new conversation for a user, call the forUser method before prompting:

$response = (new SalesCoach)->forUser($user)->prompt('こんにちは!');

$conversationId = $response->conversationId;

会話IDはレスポンスで返され、将来の参照のために保存できます。あるいは、agent_conversationsテーブルからユーザーのすべての会話を直接取得することもできます。The conversation ID is returned on the response and can be stored for future reference, or you can retrieve all of a user's conversations from the agent_conversations table directly.

既存の会話を継続するには、continueメソッドを使用してください。To continue an existing conversation, use the continue method:

$response = (new SalesCoach)
    ->continue($conversationId, as: $user)
    ->prompt('それについて詳しく教えてください。');

RemembersConversationsトレイトを使用すると、プロンプト送信時に以前のメッセージを自動的にロードし、会話コンテキストに含めます。新しいメッセージ(ユーザーとアシスタントの両方)は、各やり取りの後に自動的に保存します。When using the RemembersConversations trait, previous messages are automatically loaded and included in the conversation context when prompting. New messages (both user and assistant) are automatically stored after each interaction.

構造化出力Structured Output

エージェントから造化出力を返す場合は、HasStructuredOutputインターフェイスを実装してください。それには、エージェントでschemaメソッドを定義する必要があります。If you would like your agent to return structured output, implement the HasStructuredOutput interface, which requires that your agent define a schema method:

<?php

namespace App\Ai\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;

class SalesCoach implements Agent, HasStructuredOutput
{
    use Promptable;

    // ...

    /**
     * エージェントの構造化出力スキーマ定義を取得
     */
    public function schema(JsonSchema $schema): array
    {
        return [
            'score' => $schema->integer()->required(),
        ];
    }
}

構造化出力を返すエージェントにプロンプトを送る場合、返ってきたStructuredAgentResponseへ配列のようにアクセスできます。When prompting an agent that returns structured output, you can access the returned StructuredAgentResponse like an array:

$response = (new SalesCoach)->prompt('このセールスの文字起こしを分析して...');

return $response['score'];

添付ファイルAttachments

プロンプトを送信する際、モデルが画像やドキュメントを検査できるように添付ファイルを渡すこともできます。When prompting, you may also pass attachments with the prompt to allow the model to inspect images and documents:

use App\Ai\Agents\SalesCoach;
use Laravel\Ai\Files;

$response = (new SalesCoach)->prompt(
    '添付されたセールスの文字起こしを分析して...',
    attachments: [
        Files\Document::fromStorage('transcript.pdf') // ファイルシステムディスクからドキュメントを添付
        Files\Document::fromPath('/home/laravel/transcript.md') // ローカルパスからドキュメントを添付
        $request->file('transcript'), // アップロードされたファイルを添付
    ]
);

同様に、Laravel\Ai\Files\Imageクラスを使用してプロンプトに画像を添付できます。Likewise, the Laravel\Ai\Files\Image class may be used to attach images to a prompt:

use App\Ai\Agents\ImageAnalyzer;
use Laravel\Ai\Files;

$response = (new ImageAnalyzer)->prompt(
    'この画像には何が写っていますか?',
    attachments: [
        Files\Image::fromStorage('photo.jpg') // ファイルシステムディスクから画像を添付
        Files\Image::fromPath('/home/laravel/photo.jpg') // ローカルパスから画像を添付
        $request->file('photo'), // アップロードされたファイルを添付
    ]
);

ストリーミングStreaming

streamメソッドを呼び出すことで、エージェントのレスポンスをストリーミングできます。返ってきたStreamableAgentResponseをルートから返すと、ストリーミングレスポンス(SSE)をクライアントへ自動的に送信します。You may stream an agent's response by invoking the stream method. The returned StreamableAgentResponse may be returned from a route to automatically send a streaming response (SSE) to the client:

use App\Ai\Agents\SalesCoach;

Route::get('/coach', function () {
    return (new SalesCoach)->stream('このセールスの文字起こしを分析して...');
});

レスポンス全体がクライアントへストリーミングされたときに呼び出されるクロージャを指定するには、thenメソッドを使用します。The then method may be used to provide a closure that will be invoked when the entire response has been streamed to the client:

use App\Ai\Agents\SalesCoach;
use Laravel\Ai\Responses\StreamedAgentResponse;

Route::get('/coach', function () {
    return (new SalesCoach)
        ->stream('このセールスの文字起こしを分析して...')
        ->then(function (StreamedAgentResponse $response) {
            // $response->text, $response->events, $response->usage…
        });
});

あるいは、ストリーミングされたイベントを手作業で反復処理することもできます。Alternatively, you may iterate through the streamed events manually:

$stream = (new SalesCoach)->stream('このセールスの文字起こしを分析して...');

foreach ($stream as $event) {
    // ...
}

Vercel AI SDKプロトコルを使用したストリーミングStreaming Using the Vercel AI SDK Protocol

ストリーミング可能なレスポンスでusingVercelDataProtocolメソッドを呼び出すことで、Vercel AI SDKストリームプロトコルを使用してイベントをストリーミングできます。You may stream the events using the Vercel AI SDK stream protocol[https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol] by invoking the usingVercelDataProtocol method on the streamable response:

use App\Ai\Agents\SalesCoach;

Route::get('/coach', function () {
    return (new SalesCoach)
        ->stream('このセールスの文字起こしを分析して...')
        ->usingVercelDataProtocol();
});

ブロードキャストBroadcasting

ストリーミングされたイベントをいくつかの方法でブロードキャストできます。まず、ストリーミングされたイベントでbroadcastまたはbroadcastNowメソッドを呼び出すだけです。You may broadcast streamed events in a few different ways. First, you can simply invoke the broadcast or broadcastNow method on a streamed event:

use App\Ai\Agents\SalesCoach;
use Illuminate\Broadcasting\Channel;

$stream = (new SalesCoach)->stream('このセールスの文字起こしを分析して...');

foreach ($stream as $event) {
    $event->broadcast(new Channel('channel-name'));
}

または、エージェントのbroadcastOnQueueメソッドを呼び出してエージェントの操作をキューに入れ、ストリーミングされたイベントが利用可能になり次第ブロードキャストできます。Or, you can invoke an agent's broadcastOnQueue method to queue the agent operation and broadcast the streamed events as they are available:

(new SalesCoach)->broadcastOnQueue(
    'このセールスの文字起こしを分析して...'
    new Channel('channel-name'),
);

キューイングQueueing

エージェントのqueueメソッドを使用すると、エージェントにプロンプトを送りますが、レスポンスの処理をバックグラウンドで行わせることができ、アプリケーションの高速でレスポンシブな操作感を維持できます。thenおよびcatchメソッドを使用して、レスポンスが利用可能になったとき、または例外が発生したときに呼び出されるクロージャを登録できます。Using an agent's queue method, you may prompt the agent, but allow it to process the response in the background, keeping your application feeling fast and responsive. The then and catch methods may be used to register closures that will be invoked when a response is available or if an exception occurs:

use Illuminate\Http\Request;
use Laravel\Ai\Responses\AgentResponse;
use Throwable;

Route::post('/coach', function (Request $request) {
    return (new SalesCoach)
        ->queue($request->input('transcript'))
        ->then(function (AgentResponse $response) {
            // ...
        })
        ->catch(function (Throwable $e) {
            // ...
        });

    return back();
});

ツールTools

ツールを使用すると、プロンプトへの応答中にエージェントが利用できる追加機能をエージェントに与えることができます。ツールは、make:tool Artisanコマンドを使用して作成できます。Tools may be used to give agents additional functionality that they can utilize while responding to prompts. Tools can be created using the make:tool Artisan command:

php artisan make:tool RandomNumberGenerator

生成したツールは、アプリケーションのapp/Ai/Toolsディレクトリへ配置します。各ツールには、エージェントがツールを利用する必要があるときに呼び出すhandleメソッドを含みます。The generated tool will be placed in your application's app/Ai/Tools directory. Each tool contains a handle method that will be invoked by the agent when it needs to utilize the tool:

<?php

namespace App\Ai\Tools;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

class RandomNumberGenerator implements Tool
{
    /**
     * ツールの目的の説明を取得
     */
    public function description(): Stringable|string
    {
        return 'このツールは、暗号学的に安全な乱数を生成するために使用できます。';
    }

    /**
     * ツールを実行
     */
    public function handle(Request $request): Stringable|string
    {
        return (string) random_int($request['min'], $request['max']);
    }

    /**
     * ツールのスキーマ定義を取得
     */
    public function schema(JsonSchema $schema): array
    {
        return [
            'min' => $schema->integer()->min(0)->required(),
            'max' => $schema->integer()->required(),
        ];
    }
}

ツールを定義したら、エージェントのtoolsメソッドからそれを返します。Once you have defined your tool, you may return it from the tools method of any of your agents:

use App\Ai\Tools\RandomNumberGenerator;

/**
 * エージェントが利用可能なツールを取得
 *
 * @return Tool[]
 */
public function tools(): iterable
{
    return [
        new RandomNumberGenerator,
    ];
}

類似性検索Similarity Search

SimilaritySearchツールを使用すると、エージェントはデータベースに保存されているベクトル埋め込みを使用して、特定のクエリに類似したドキュメントを検索できます。これは、エージェントにアプリケーションのデータを検索するアクセス権を与えたい場合の検索拡張生成(RAG)に役立ちます。The SimilaritySearch tool allows agents to search for documents similar to a given query using vector embeddings stored in your database. This is useful for retrieval-augmented generation (RAG) when you want to give agents access to search your application's data.

類似性検索ツールを作成する最も簡単な方法は、ベクトル埋め込みを持つEloquentモデルでusingModelメソッドを使用することです。The simplest way to create a similarity search tool is using the usingModel method with an Eloquent model that has vector embeddings:

use App\Models\Document;
use Laravel\Ai\Tools\SimilaritySearch;

public function tools(): iterable
{
    return [
        SimilaritySearch::usingModel(Document::class, 'embedding'),
    ];
}

最初の引数はEloquentモデルクラス、2番目の引数はベクトル埋め込みを含むカラムです。The first argument is the Eloquent model class, and the second argument is the column containing the vector embeddings.

0.0から1.0の間の最小類似度しきい値や、クエリをカスタマイズするためのクロージャを指定することもできます。You may also provide a minimum similarity threshold between 0.0 and 1.0 and a closure to customize the query:

SimilaritySearch::usingModel(
    model: Document::class,
    column: 'embedding',
    minSimilarity: 0.7,
    limit: 10,
    query: fn ($query) => $query->where('published', true),
),

より詳細に制御するには、検索結果を返すカスタムクロージャを使用して類似性検索ツールを作成します。For more control, you may create a similarity search tool with a custom closure that returns the search results:

use App\Models\Document;
use Laravel\Ai\Tools\SimilaritySearch;

public function tools(): iterable
{
    return [
        new SimilaritySearch(using: function (string $query) {
            return Document::query()
                ->where('user_id', $this->user->id)
                ->whereVectorSimilarTo('embedding', $query)
                ->limit(10)
                ->get();
        }),
    ];
}

withDescriptionメソッドを使用して、ツールの説明をカスタマイズできます。You may customize the tool's description using the withDescription method:

SimilaritySearch::usingModel(Document::class, 'embedding')
    ->withDescription('関連する記事をナレッジベースで検索します。'),

プロバイダツールProvider Tools

プロバイダツールは、各AIプロバイダがネイティブに実装している特別なツールで、Web検索、URLフェッチ、ファイル検索などの機能を提供します。通常のツールとは異なり、プロバイダツールはアプリケーションではなくプロバイダ自身にが実行します。Provider tools are special tools implemented natively by AI providers, offering capabilities like web searching, URL fetching, and file searching. Unlike regular tools, provider tools are executed by the provider itself rather than your application.

プロバイダツールは、エージェントのtoolsメソッドから返します。Provider tools can be returned by your agent's tools method.

Web検索Web Search

WebSearchプロバイダツールを使用すると、エージェントはWebを検索してリアルタイムの情報を取得できます。これは、時事問題、最近のデータ、またはモデルのトレーニングカットオフ以降に変更された可能性のあるトピックに関する質問に答えるのに役立ちます。The WebSearch provider tool allows agents to search the web for real-time information. This is useful for answering questions about current events, recent data, or topics that may have changed since the model's training cutoff.

サポートしているプロバイダ: Anthropic, OpenAI, GeminiSupported Providers: Anthropic, OpenAI, Gemini

use Laravel\Ai\Providers\Tools\WebSearch;

public function tools(): iterable
{
    return [
        new WebSearch,
    ];
}

Web検索ツールを設定して、検索数を制限したり、結果を特定のドメインに制限したりできます。You may configure the web search tool to limit the number of searches or restrict results to specific domains:

(new WebSearch)->max(5)->allow(['laravel.com', 'php.net']),

ユーザーの場所に基づいて検索結果を絞り込むには、locationメソッドを使用してください。To refine search results based on user location, use the location method:

(new WebSearch)->location(
    city: 'New York',
    region: 'NY',
    country: 'US'
);

WebフェッチWeb Fetch

WebFetchプロバイダツールを使用すると、エージェントはWebページの内容を取得して読み取ることができます。これは、エージェントに特定のURLを分析させたり、既知のWebページから詳細な情報を取得させたりする必要がある場合に便利です。The WebFetch provider tool allows agents to fetch and read the contents of web pages. This is useful when you need the agent to analyze specific URLs or retrieve detailed information from known web pages.

サポートしているプロバイダ: Anthropic, GeminiSupported providers: Anthropic, Gemini

use Laravel\Ai\Providers\Tools\WebFetch;

public function tools(): iterable
{
    return [
        new WebFetch,
    ];
}

Webフェッチツールを設定して、フェッチ数を制限したり、特定のドメインに制限したりできます。You may configure the web fetch tool to limit the number of fetches or restrict to specific domains:

(new WebFetch)->max(3)->allow(['docs.laravel.com']),

ファイル検索File Search

FileSearchプロバイダツールを使用すると、エージェントはベクトルストアに保存されているファイル内を検索できます。これにより、エージェントがアップロード済みのドキュメントから関連情報を検索できるようになり、検索拡張生成(RAG)が可能になります。The FileSearch provider tool allows agents to search through files[#files] stored in vector stores[#vector-stores]. This enables retrieval-augmented generation (RAG) by allowing the agent to search your uploaded documents for relevant information.

サポートしているプロバイダ: OpenAI, GeminiSupported providers: OpenAI, Gemini

use Laravel\Ai\Providers\Tools\FileSearch;

public function tools(): iterable
{
    return [
        new FileSearch(stores: ['store_id']),
    ];
}

複数のストアにまたがって検索するには、複数のベクトルストアIDを指定します。You may provide multiple vector store IDs to search across multiple stores:

new FileSearch(stores: ['store_1', 'store_2']);

ファイルにメタデータがある場合、where引数を指定して検索結果をフィルタリングできます。単純な等値フィルタの場合は、配列を渡します。If your files have metadata[#adding-files-to-stores], you may filter the search results by providing a where argument. For simple equality filters, pass an array:

new FileSearch(stores: ['store_id'], where: [
    'author' => 'Taylor Otwell',
    'year' => 2026,
]);

より複雑なフィルタの場合は、FileSearchQueryインスタンスを受け取るクロージャを渡します。For more complex filters, you may pass a closure that receives a FileSearchQuery instance:

use Laravel\Ai\Providers\Tools\FileSearchQuery;

new FileSearch(stores: ['store_id'], where: fn (FileSearchQuery $query) =>
    $query->where('author', 'Taylor Otwell')
        ->whereNot('status', 'draft')
        ->whereIn('category', ['news', 'updates'])
);

ミドルウェアMiddleware

エージェントはミドルウェアをサポートしており、プロンプトがプロバイダへ送信する前に傍受して変更できます。エージェントにミドルウェアを追加するには、HasMiddlewareインターフェイスを実装し、ミドルウェアクラスの配列を返すmiddlewareメソッドを定義してください。Agents support middleware, allowing you to intercept and modify prompts before they are sent to the provider. To add middleware to an agent, implement the HasMiddleware interface and define a middleware method that returns an array of middleware classes:

<?php

namespace App\Ai\Agents;

use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasMiddleware;
use Laravel\Ai\Promptable;

class SalesCoach implements Agent, HasMiddleware
{
    use Promptable;

    // ...

    /**
     * エージェントのミドルウェアを取得
     */
    public function middleware(): array
    {
        return [
            new LogPrompts,
        ];
    }
}

各ミドルウェアクラスは、AgentPromptと、プロンプトを次のミドルウェアに渡すためのClosureを受け取るhandleメソッドを定義する必要があります。Each middleware class should define a handle method that receives the AgentPrompt and a Closure to pass the prompt to the next middleware:

<?php

namespace App\Ai\Middleware;

use Closure;
use Laravel\Ai\Prompts\AgentPrompt;

class LogPrompts
{
    /**
     * 送信されてきたプロンプトを処理
     */
    public function handle(AgentPrompt $prompt, Closure $next)
    {
        Log::info('エージェントにプロンプトを送信中', ['prompt' => $prompt->prompt]);

        return $next($prompt);
    }
}

レスポンスでthenメソッドを使用して、エージェントが処理を終えた後にコードを実行できます。これは、同期レスポンスとストリーミングレスポンスの両方で機能します。You may use the then method on the response to execute code after the agent has finished processing. This works for both synchronous and streaming responses:

public function handle(AgentPrompt $prompt, Closure $next)
{
    return $next($prompt)->then(function (AgentResponse $response) {
        Log::info('エージェントが応答しました', ['text' => $response->text]);
    });
}

匿名エージェントAnonymous Agents

専用のエージェントクラスを作成せずに、モデルと素早くやり取りしたい場合があります。agent関数を使用して、アドホックな匿名エージェントを作成できます。Sometimes you may want to quickly interact with a model without creating a dedicated agent class. You can create an ad-hoc, anonymous agent using the agent function:

use function Laravel\Ai\{agent};

$response = agent(
    instructions: 'あなたはソフトウェア開発のエキスパートです。',
    messages: [],
    tools: [],
)->prompt('Laravelについて教えてください')

匿名エージェントも構造化出力を生成できます。Anonymous agents may also produce structured output:

use Illuminate\Contracts\JsonSchema\JsonSchema;

use function Laravel\Ai\{agent};

$response = agent(
    schema: fn (JsonSchema $schema) => [
        'number' => $schema->integer()->required(),
    ],
)->prompt('100未満の乱数を生成して')

エージェント設定Agent Configuration

PHP属性を使用して、エージェントのテキスト生成オプションを設定できます。以下の属性が利用可能です。You may configure text generation options for an agent using PHP attributes. The following attributes are available:

  • MaxSteps: ツールを使用する際にエージェントが実行できる最大ステップ数MaxSteps: The maximum number of steps the agent may take when using tools.
  • MaxTokens: モデルが生成できる最大トークン数MaxTokens: The maximum number of tokens the model may generate.
  • Model: エージェントが使用すべきモデルModel: The model the agent should use.
  • Provider: エージェントに使用するAIプロバイダ(またはフェイルオーバ用のプロバイダ)Provider: The AI provider (or providers for failover) to use for the agent.
  • Temperature: 生成に使用するサンプリング温度(0.0~1.0)Temperature: The sampling temperature to use for generation (0.0 to 1.0).
  • Timeout: エージェントリクエストのHTTPタイムアウト(秒単位、デフォルトは60)Timeout: The HTTP timeout in seconds for agent requests (default: 60).
  • UseCheapestModel: コスト最適化のため、プロバイダの最も安価なテキストモデルを使用UseCheapestModel: Use the provider's cheapest text model for cost optimization.
  • UseSmartestModel: 複雑なタスクのため、プロバイダの最も有能なテキストモデルを使用UseSmartestModel: Use the provider's most capable text model for complex tasks.
<?php

namespace App\Ai\Agents;

use Laravel\Ai\Attributes\MaxSteps;
use Laravel\Ai\Attributes\MaxTokens;
use Laravel\Ai\Attributes\Model;
use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Attributes\Temperature;
use Laravel\Ai\Attributes\Timeout;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;

#[Provider('anthropic')]
#[Model('claude-haiku-4-5-20251001')]
#[MaxSteps(10)]
#[MaxTokens(4096)]
#[Temperature(0.7)]
#[Timeout(120)]
class SalesCoach implements Agent
{
    use Promptable;

    // ...
}

UseCheapestModel属性とUseSmartestModel属性を使用すると、モデル名を指定せずに、特定のプロバイダに対して最もコスト効率の高いモデル、または最も有能なモデルを自動的に選択できます。これは、異なるプロバイダ間でコストや能力を最適化したい場合に便利です。The UseCheapestModel and UseSmartestModel attributes allow you to automatically select the most cost-effective or most capable model for a given provider without specifying a model name. This is useful when you want to optimize for cost or capability across different providers:

use Laravel\Ai\Attributes\UseCheapestModel;
use Laravel\Ai\Attributes\UseSmartestModel;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;

#[UseCheapestModel]
class SimpleSummarizer implements Agent
{
    use Promptable;

    // 最も安価なモデル(例:Haiku)を使用
}

#[UseSmartestModel]
class ComplexReasoner implements Agent
{
    use Promptable;

    // 最も有能なモデル(例:Opus)を使用
}

画像Images

Laravel\Ai\Imageクラスを使用して、openaigemini、またはxaiプロバイダを用いた画像生成を行えます。The Laravel\Ai\Image class may be used to generate images using the openai, gemini, or xai providers:

use Laravel\Ai\Image;

$image = Image::of('キッチンカウンターに置いてあるドーナツ')->generate();

$rawContent = (string) $image;

squareportraitlandscapeメソッドで画像の比率を制御でき、qualityメソッドで最終的な画質(highmediumlow)をモデルに指示できます。timeoutメソッドを使用して、HTTPタイムアウトを秒単位で指定できます。The square, portrait, and landscape methods may be used to control the aspect ratio of the image, while the quality method may be used to guide the model on final image quality (high, medium, low). The timeout method may be used to specify the HTTP timeout in seconds:

use Laravel\Ai\Image;

$image = Image::of('キッチンカウンターに置いてあるドーナツ')
    ->quality('high')
    ->landscape()
    ->timeout(120)
    ->generate();

attachmentsメソッドを使用して参照画像を添付できます。You may attach reference images using the attachments method:

use Laravel\Ai\Files;
use Laravel\Ai\Image;

$image = Image::of('この私の写真を印象派の絵画のようなスタイルに更新して。')
    ->attachments([
        Files\Image::fromStorage('photo.jpg'),
        // Files\Image::fromPath('/home/laravel/photo.jpg'),
        // Files\Image::fromUrl('[https://example.com/photo.jpg](https://example.com/photo.jpg)'),
        // $request->file('photo'),
    ])
    ->landscape()
    ->generate();

生成された画像は、アプリケーションのconfig/filesystems.php設定ファイルで設定しているデフォルトのディスクへ簡単に保存できます。Generated images may be easily stored on the default disk configured in your application's config/filesystems.php configuration file:

$image = Image::of('キッチンカウンターに置いてあるドーナツ');

$path = $image->store();
$path = $image->storeAs('image.jpg');
$path = $image->storePublicly();
$path = $image->storePubliclyAs('image.jpg');

画像生成をキューへ投入することもできます。Image generation may also be queued:

use Laravel\Ai\Image;
use Laravel\Ai\Responses\ImageResponse;

Image::of('キッチンカウンターに置いてあるドーナツ')
    ->portrait()
    ->queue()
    ->then(function (ImageResponse $image) {
        $path = $image->store();

        // ...
    });

音声Audio

Laravel\Ai\Audioクラスを使用して、指定したテキストから音声を生成できます。The Laravel\Ai\Audio class may be used to generate audio from the given text:

use Laravel\Ai\Audio;

$audio = Audio::of('Laravelでコーディングするのが大好きです。')->generate();

$rawContent = (string) $audio;

malefemalevoiceメソッドを使用して、生成される音声の声を決定できます。The male, female, and voice methods may be used to determine the voice of the generated audio:

$audio = Audio::of('Laravelでコーディングするのが大好きです。')
    ->female()
    ->generate();

$audio = Audio::of('Laravelでコーディングするのが大好きです。')
    ->voice('voice-id-or-name')
    ->generate();

同様に、instructionsメソッドを使用して、生成される音声がどのように聞こえるべきかを動的にモデルにコーチングできます。Similarly, the instructions method may be used to dynamically coach the model on how the generated audio should sound:

$audio = Audio::of('Laravelでコーディングするのが大好きです。')
    ->female()
    ->instructions('海賊のように話して')
    ->generate();

生成された音声は、アプリケーションのconfig/filesystems.php設定ファイルで設定したデフォルトのディスクへ単に保存できます。Generated audio may be easily stored on the default disk configured in your application's config/filesystems.php configuration file:

$audio = Audio::of('Laravelでコーディングするのが大好きです。')->generate();

$path = $audio->store();
$path = $audio->storeAs('audio.mp3');
$path = $audio->storePublicly();
$path = $audio->storePubliclyAs('audio.mp3');

音声生成もキューに投入できます。Audio generation may also be queued:

use Laravel\Ai\Audio;
use Laravel\Ai\Responses\AudioResponse;

Audio::of('Laravelでコーディングするのが大好きです。')
    ->queue()
    ->then(function (AudioResponse $audio) {
        $path = $audio->store();

        // ...
    });

文字起こしTranscriptions

Laravel\Ai\Transcriptionクラスを使用して、指定した音声の文字起こしを生成できます。The Laravel\Ai\Transcription class may be used to generate a transcript of the given audio:

use Laravel\Ai\Transcription;

$transcript = Transcription::fromPath('/home/laravel/audio.mp3')->generate();
$transcript = Transcription::fromStorage('audio.mp3')->generate();
$transcript = Transcription::fromUpload($request->file('audio'))->generate();

return (string) $transcript;

diarizeメソッドを使用して、生のテキストの文字起こしに加えてダイアリゼーション(話者分離)された文字起こしをレスポンスに含めるように指示でき、話者ごとに区切られた文字起こしにアクセスできるようになります。The diarize method may be used to indicate you would like the response to include the diarized transcript in addition to the raw text transcript, allowing you to access the segmented transcript by speaker:

$transcript = Transcription::fromStorage('audio.mp3')
    ->diarize()
    ->generate();

文字起こしの生成もキューに入れることができます。Transcription generation may also be queued:

use Laravel\Ai\Transcription;
use Laravel\Ai\Responses\TranscriptionResponse;

Transcription::fromStorage('audio.mp3')
    ->queue()
    ->then(function (TranscriptionResponse $transcript) {
        // ...
    });

埋め込みEmbeddings

LaravelのStringableクラスで利用可能な新しいtoEmbeddingsメソッドを使用して、任意の文字列のベクトル埋め込みを簡単に生成できます。You may easily generate vector embeddings for any given string using the new toEmbeddings method available via Laravel's Stringable class:

use Illuminate\Support\Str;

$embeddings = Str::of('ナパバレーには素晴らしいワインがあります。')->toEmbeddings();

あるいは、Embeddingsクラスを使用して、複数の入力に対して一度に埋め込みを生成することもできます。Alternatively, you may use the Embeddings class to generate embeddings for multiple inputs at once:

use Laravel\Ai\Embeddings;

$response = Embeddings::for([
    'ナパバレーには素晴らしいワインがあります。',
    'LaravelはPHPのフレームワークです。',
])->generate();

$response->embeddings; // [[0.123, 0.456, ...], [0.789, 0.012, ...]]

埋め込みの次元数とプロバイダを指定できます。You may specify the dimensions and provider for the embeddings:

$response = Embeddings::for(['ナパバレーには素晴らしいワインがあります。'])
    ->dimensions(1536)
    ->generate('openai', 'text-embedding-3-small');

埋め込みのクエリQuerying Embeddings

埋め込みを生成したら、通常は後でクエリするためにデータベースのvectorカラムに保存します。Laravelは、pgvector拡張機能を介してPostgreSQLのベクトルカラムをネイティブにサポートしています。開始するには、マイグレーションでvectorカラムを定義し、次元数を指定します。Once you have generated embeddings, you will typically store them in a vector column in your database for later querying. Laravel provides native support for vector columns on PostgreSQL via the pgvector extension. To get started, define a vector column in your migration, specifying the number of dimensions:

Schema::ensureVectorExtensionExists();

Schema::create('documents', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->vector('embedding', dimensions: 1536);
    $table->timestamps();
});

類似性検索を高速化するために、ベクトルインデックスを追加することもできます。ベクトルカラムでindexを呼び出すと、Laravelはコサイン距離を使用したHNSWインデックスを自動的に作成します。You may also add a vector index to speed up similarity searches. When calling index on a vector column, Laravel will automatically create an HNSW index with cosine distance:

$table->vector('embedding', dimensions: 1536)->index();

Eloquentモデルでは、ベクトルカラムをarrayにキャストしてください。On your Eloquent model, you should cast the vector column to an array:

protected function casts(): array
{
    return [
        'embedding' => 'array',
    ];
}

類似したレコードを検索するには、whereVectorSimilarToメソッドを使用します。このメソッドは、最小コサイン類似度(0.0から1.0の間。1.0は同一)で結果をフィルタリングし、類似度順に結果を並べ替えます。To query for similar records, use the whereVectorSimilarTo method. This method filters results by a minimum cosine similarity (between 0.0 and 1.0, where 1.0 is identical) and orders the results by similarity:

use App\Models\Document;

$documents = Document::query()
    ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
    ->limit(10)
    ->get();

$queryEmbeddingは浮動小数点数の配列、またはプレーンな文字列です。文字列が指定された場合、Laravelはその文字列の埋め込みを自動的に生成します。The $queryEmbedding may be an array of floats or a plain string. When a string is given, Laravel will automatically generate embeddings for it:

$documents = Document::query()
    ->whereVectorSimilarTo('embedding', 'ナパバレーで最高のワイナリー')
    ->limit(10)
    ->get();

より詳細な制御が必要な場合は、低レベルのwhereVectorDistanceLessThanselectVectorDistanceorderByVectorDistanceメソッドを独立して使用できます。If you need more control, you may use the lower-level whereVectorDistanceLessThan, selectVectorDistance, and orderByVectorDistance methods independently:

$documents = Document::query()
    ->select('*')
    ->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
    ->whereVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)
    ->orderByVectorDistance('embedding', $queryEmbedding)
    ->limit(10)
    ->get();

エージェントにツールとして類似性検索を実行する能力を与えたい場合は、類似性検索ツールのドキュメントを確認してください。If you would like to give an agent the ability to perform similarity searches as a tool, check out the Similarity Search[#similarity-search] tool documentation.

note Note: ベクトルクエリは現在、pgvector拡張機能を使用しているPostgreSQL接続でのみサポートしています。[!NOTE] Vector queries are currently only supported on PostgreSQL connections using the pgvector extension.

埋め込みのキャッシュCaching Embeddings

埋め込み生成をキャッシュして、同一の入力に対する冗長なAPI呼び出しを回避できます。キャッシュを有効にするには、ai.caching.embeddings.cache設定オプションをtrueに設定してください。Embedding generation can be cached to avoid redundant API calls for identical inputs. To enable caching, set the ai.caching.embeddings.cache configuration option to true:

'caching' => [
    'embeddings' => [
        'cache' => true,
        'store' => env('CACHE_STORE', 'database'),
        // ...
    ],
],

キャッシュが有効な場合、埋め込みを30日間キャッシュします。キャッシュキーは、プロバイダ、モデル、次元数、および入力内容に基づいており、同一のリクエストはキャッシュされた結果を返し、異なる設定の場合は新しい埋め込みを生成することを保証します。When caching is enabled, embeddings are cached for 30 days. The cache key is based on the provider, model, dimensions, and input content, ensuring that identical requests return cached results while different configurations generate fresh embeddings.

グローバルキャッシュが無効な場合でも、cacheメソッドを使用して特定のリクエストに対してキャッシュを有効にできます。You may also enable caching for a specific request using the cache method, even when global caching is disabled:

$response = Embeddings::for(['ナパバレーには素晴らしいワインがあります。'])
    ->cache()
    ->generate();

カスタムのキャッシュ期間を秒単位で指定できます。You may specify a custom cache duration in seconds:

$response = Embeddings::for(['ナパバレーには素晴らしいワインがあります。'])
    ->cache(seconds: 3600) // 1時間キャッシュ
    ->generate();

toEmbeddings Stringableメソッドもcache引数を受け入れます。The toEmbeddings Stringable method also accepts a cache argument:

// デフォルト期間でキャッシュ...
$embeddings = Str::of('ナパバレーには素晴らしいワインがあります。')->toEmbeddings(cache: true);

// 特定の期間でキャッシュ...
$embeddings = Str::of('ナパバレーには素晴らしいワインがあります。')->toEmbeddings(cache: 3600);

リランクReranking

リランクを使用すると、特定のクエリとの関連性に基づいてドキュメントのリストを並べ替えることができます。これは、セマンティックな理解を使用して検索結果を改善するのに役立ちます。Reranking allows you to reorder a list of documents based on their relevance to a given query. This is useful for improving search results by using semantic understanding:

Laravel\Ai\Rerankingクラスを使用して、ドキュメントをリランクできます。The Laravel\Ai\Reranking class may be used to rerank documents:

use Laravel\Ai\Reranking;

$response = Reranking::of([
    'DjangoはPythonのWebフレームワークです。',
    'LaravelはPHPのWebアプリケーションフレームワークです。',
    'Reactはユーザーインターフェイスを構築するためのJavaScriptライブラリです。',
])->rerank('PHPフレームワーク');

// 最上位の結果にアクセス...
$response->first()->document; // "LaravelはPHPのWebアプリケーションフレームワークです。"
$response->first()->score;    // 0.95
$response->first()->index;    // 1 (元の位置)

limitメソッドを使用して、返される結果の数を制限できます。The limit method may be used to restrict the number of results returned:

$response = Reranking::of($documents)
    ->limit(5)
    ->rerank('検索クエリ');

コレクションのリランクReranking Collections

利便性のために、Laravelコレクションはrerankマクロを使用してリランクできます。最初の引数はリランクに使用するフィールドを指定し、2番目の引数はクエリです。For convenience, Laravel collections may be reranked using the rerank macro. The first argument specifies which field(s) to use for reranking, and the second argument is the query:

// 単一のフィールドでリランク
$posts = Post::all()
    ->rerank('body', 'Laravelのチュートリアル');

// 複数のフィールドでリランク(JSONとして送信)
$reranked = $posts->rerank(['title', 'body'], 'Laravelのチュートリアル');

// クロージャを使用してドキュメントを構築し、リランク
$reranked = $posts->rerank(
    fn ($post) => $post->title.': '.$post->body,
    'Laravelのチュートリアル'
);

結果の数を制限したり、プロバイダを指定したりすることもできます。You may also limit the number of results and specify a provider:

$reranked = $posts->rerank(
    by: 'content',
    query: 'Laravelのチュートリアル',
    limit: 10,
    provider: 'cohere'
);

ファイルFiles

Laravel\Ai\Filesクラス、または個別のファイルクラスを使用して、後で会話で使用するためにAIプロバイダにファイルを保存できます。これは、再アップロードせずに複数回参照したい大きなドキュメントやファイルに便利です。The Laravel\Ai\Files class or the individual file classes may be used to store files with your AI provider for later use in conversations. This is useful for large documents or files you want to reference multiple times without re-uploading:

use Laravel\Ai\Files\Document;
use Laravel\Ai\Files\Image;

// ローカルパスからファイルを保存
$response = Document::fromPath('/home/laravel/document.pdf')->put();
$response = Image::fromPath('/home/laravel/photo.jpg')->put();

// ファイルシステムディスクに保存されているファイルを保存
$response = Document::fromStorage('document.pdf', disk: 'local')->put();
$response = Image::fromStorage('photo.jpg', disk: 'local')->put();

// リモートURLに保存されているファイルを保存
$response = Document::fromUrl('[https://example.com/document.pdf')-](https://example.com/document.pdf')-)>put();
$response = Image::fromUrl('[https://example.com/photo.jpg')-](https://example.com/photo.jpg')-)>put();

return $response->id;

生のコンテンツやアップロード済みファイルを保存することもできます。You may also store raw content or uploaded files:

use Laravel\Ai\Files;
use Laravel\Ai\Files\Document;

// 生のコンテンツを保存
$stored = Document::fromString('Hello, World!', 'text/plain')->put();

// アップロード済みファイルを保存
$stored = Document::fromUpload($request->file('document'))->put();

ファイルを保存すると、ファイルを再アップロードする代わりに、エージェントを介してテキストを生成する際にそのファイルを参照できます。Once a file has been stored, you may reference the file when generating text via agents instead of re-uploading the file:

use App\Ai\Agents\SalesCoach;
use Laravel\Ai\Files;

$response = (new SalesCoach)->prompt(
    '添付されたセールスの文字起こしを分析して...'
    attachments: [
        Files\Document::fromId('file-id') // 保存済みのドキュメントを添付
    ]
);

以前に保存したファイルを取得するには、ファイルインスタンスでgetメソッドを使用します。To retrieve a previously stored file, use the get method on a file instance:

use Laravel\Ai\Files\Document;

$file = Document::fromId('file-id')->get();

$file->id;
$file->mimeType();

プロバイダからファイルを削除するには、deleteメソッドを使用します。To delete a file from the provider, use the delete method:

Document::fromId('file-id')->delete();

デフォルトでは、Filesクラスはアプリケーションのconfig/ai.php設定ファイルで設定しているデフォルトのAIプロバイダを使用します。ほとんどの操作において、provider引数を使用して別のプロバイダを指定できます。By default, the Files class uses the default AI provider configured in your application's config/ai.php configuration file. For most operations, you may specify a different provider using the provider argument:

$response = Document::fromPath(
    '/home/laravel/document.pdf'
)->put(provider: 'anthropic');

会話での保存済みファイルの使用Using Stored Files in Conversations

プロバイダにファイルを保存したら、DocumentまたはImageクラスのfromIdメソッドを使用して、エージェントの会話でそれを参照できます。Once a file has been stored with a provider, you may reference it in agent conversations using the fromId method on the Document or Image classes:

use App\Ai\Agents\DocumentAnalyzer;
use Laravel\Ai\Files;
use Laravel\Ai\Files\Document;

$stored = Document::fromPath('/path/to/report.pdf')->put();

$response = (new DocumentAnalyzer)->prompt(
    'このドキュメントを要約して。',
    attachments: [
        Document::fromId($stored->id),
    ],
);

同様に、保存された画像はImageクラスを使用して参照できます。Similarly, stored images may be referenced using the Image class:

use Laravel\Ai\Files;
use Laravel\Ai\Files\Image;

$stored = Image::fromPath('/path/to/photo.jpg')->put();

$response = (new ImageAnalyzer)->prompt(
    'この画像には何が写っていますか?',
    attachments: [
        Image::fromId($stored->id),
    ],
);

ベクトルストアVector Stores

ベクトルストアを使用すると、検索拡張生成(RAG)に使用できる検索可能なファイルのコレクションを作成できます。Laravel\Ai\Storesクラスは、ベクトルストアの作成、取得、および削除のためのメソッドを提供します。Vector stores allow you to create searchable collections of files that can be used for retrieval-augmented generation (RAG). The Laravel\Ai\Stores class provides methods for creating, retrieving, and deleting vector stores:

use Laravel\Ai\Stores;

// 新しいベクトルストアを作成...
$store = Stores::create('ナレッジベース');

// 追加オプションを指定してストアを作成...
$store = Stores::create(
    name: 'ナレッジベース',
    description: 'ドキュメントと参照資料。',
    expiresWhenIdleFor: days(30),
);

return $store->id;

IDを指定して既存のベクトルストアを取得するには、getメソッドを使用します。To retrieve an existing vector store by its ID, use the get method:

use Laravel\Ai\Stores;

$store = Stores::get('store_id');

$store->id;
$store->name;
$store->fileCounts;
$store->ready;

ベクトルストアを削除するには、Storesクラスまたはストアインスタンスでdeleteメソッドを使用します。To delete a vector store, use the delete method on the Stores class or the store instance:

use Laravel\Ai\Stores;

// IDで削除...
Stores::delete('store_id');

// またはストアインスタンスを介して削除...
$store = Stores::get('store_id');

$store->delete();

ストアへのファイル追加Adding Files to Stores

ベクトルストアを作成したら、addメソッドを使用してそれにファイルを追加できます。ストアに追加されたファイルは、ファイル検索プロバイダツールを使用したセマンティック検索のために自動的にインデックス化されます。Once you have a vector store, you may add files[#files] to it using the add method. Files added to a store are automatically indexed for semantic searching using the file search provider tool[#file-search]:

use Laravel\Ai\Files\Document;
use Laravel\Ai\Stores;

$store = Stores::get('store_id');

// プロバイダに保存済みのファイルを追加
$document = $store->add('file_id');
$document = $store->add(Document::fromId('file_id'));

// または、保存と追加を1ステップで実行
$document = $store->add(Document::fromPath('/path/to/document.pdf'));
$document = $store->add(Document::fromStorage('manual.pdf'));
$document = $store->add($request->file('document'));

$document->id;
$document->fileId;

注意: 通常、以前に保存されたファイルをベクトルストアに追加する場合、返されるドキュメントIDは、以前に割り当てられたファイルのIDと一致します。ただし、一部のベクトルストレージプロバイダは、新しく異なる「ドキュメントID」を返す場合があります。したがって、将来の参照のために両方のIDをデータベースに保存しておくことをお勧めします。Note: Typically, when adding previously stored files to vector stores, the returned document ID will match the file's previously assigned ID; however, some vector storage providers may return a new, different "document ID". Therefore, it's recommended that you always store both IDs in your database for future reference.

ファイルをストアに追加する際にメタデータを添付できます。このメタデータは、後でファイル検索プロバイダツールを使用する際に検索結果をフィルタリングするために使用できます。You may attach metadata to files when adding them to a store. This metadata can later be used to filter search results when using the file search provider tool[#file-search]:

$store->add(Document::fromPath('/path/to/document.pdf'), metadata: [
    'author' => 'Taylor Otwell',
    'department' => 'Engineering',
    'year' => 2026,
]);

ストアからファイルを削除するには、removeメソッドを使用します。To remove a file from a store, use the remove method:

$store->remove('file_id');

ベクトルストアからファイルを削除しても、プロバイダのファイルストレージからは削除されません。ベクトルストアからファイルを削除し、ファイルストレージからも完全に削除するには、deleteFile引数を使用してください。Removing a file from a vector store does not remove it from the provider's file storage[#files]. To remove a file from the vector store and delete it permanently from file storage, use the deleteFile argument:

$store->remove('file_abc123', deleteFile: true);

フェイルオーバFailover

プロンプト送信や他のメディア生成を行う際、プロバイダ/モデルの配列を指定することで、プライマリプロバイダでサービスの中断やレート制限が発生した場合に、バックアップのプロバイダ/モデルへ自動的にフェイルオーバできます。When prompting or generating other media, you may provide an array of providers / models to automatically failover to a backup provider / model if a service interruption or rate limit is encountered on the primary provider:

use App\Ai\Agents\SalesCoach;
use Laravel\Ai\Image;

$response = (new SalesCoach)->prompt(
    'このセールスの文字起こしを分析して...',
    provider: ['openai', 'anthropic'],
);

$image = Image::of('キッチンカウンターに置いてあるドーナツ')
    ->generate(provider: ['gemini', 'xai']);

テストTesting

エージェントAgents

テスト中にエージェントのレスポンスをFakeするには、エージェントクラスでfakeメソッドを呼び出します。オプションで、レスポンスの配列またはクロージャを指定できます。To fake an agent's responses during tests, call the fake method on the agent class. You may optionally provide an array of responses or a closure:

use App\Ai\Agents\SalesCoach;
use Laravel\Ai\Prompts\AgentPrompt;

// すべてのプロンプトに対して、固定のレスポンスを自動的に生成
SalesCoach::fake();

// プロンプトレスポンスのリストを提供
SalesCoach::fake([
    '最初のレスポンス',
    '2番目のレスポンス',
]);

// 入ってきたプロンプトに基づいて、プロンプトレスポンスを動的に処理
SalesCoach::fake(function (AgentPrompt $prompt) {
    return 'レスポンス内容: '.$prompt->prompt;
});

注意: 構造化出力を返すエージェントに対してAgent::fake()を呼び出すと、Laravelはエージェントが定義した出力スキーマに一致するフェイクデータを自動的に生成します。Note: When Agent::fake() is invoked on an agent that returns structured output, Laravel will automatically generate fake data that matches your agent's defined output schema.

エージェントにプロンプトを送った後、受け取ったプロンプトについてアサートできます。After prompting the agent, you may make assertions about the prompts that were received:

use Laravel\Ai\Prompts\AgentPrompt;

SalesCoach::assertPrompted('これを分析して...');

SalesCoach::assertPrompted(function (AgentPrompt $prompt) {
    return $prompt->contains('分析');
});

SalesCoach::assertNotPrompted('存在しないプロンプト');

SalesCoach::assertNeverPrompted();

キュー投入したエージェント呼び出しについては、キュー用のアサートメソッドを使用してください。For queued agent invocations, use the queued assertion methods:

use Laravel\Ai\QueuedAgentPrompt;

SalesCoach::assertQueued('これを分析して...');

SalesCoach::assertQueued(function (QueuedAgentPrompt $prompt) {
    return $prompt->contains('分析');
});

SalesCoach::assertNotQueued('存在しないプロンプト');

SalesCoach::assertNeverQueued();

すべてのエージェント呼び出しに対応するフェイクレスポンスがあることを確認するには、preventStrayPromptsを使用できます。フェイクレスポンスが定義されていない状態でエージェントを呼び出すと、例外を投げます。To ensure all agent invocations have a corresponding fake response, you may use preventStrayPrompts. If an agent is invoked without a defined fake response, an exception will be thrown:

SalesCoach::fake()->preventStrayPrompts();

画像Images

画像生成は、Imageクラスのfakeメソッドを呼び出すことでFakeにできます。画像をFakeにしたら、記録済みの画像生成プロンプトに対してさまざまなアサートを実行できます。Image generations may be faked by invoking the fake method on the Image class. Once image has been faked, various assertions may be performed against the recorded image generation prompts:

use Laravel\Ai\Image;
use Laravel\Ai\Prompts\ImagePrompt;
use Laravel\Ai\Prompts\QueuedImagePrompt;

// すべてのプロンプトに対して、固定のレスポンスを自動的に生成
Image::fake();

// プロンプトレスポンスのリストを提供
Image::fake([
    base64_encode($firstImage),
    base64_encode($secondImage),
]);

// 入ってきたプロンプトに基づいて、プロンプトレスポンスを動的に処理
Image::fake(function (ImagePrompt $prompt) {
    return base64_encode('...');
});

画像を生成した後、受け取ったプロンプトについてアサートを行えます。After generating images, you may make assertions about the prompts that were received:

Image::assertGenerated(function (ImagePrompt $prompt) {
    return $prompt->contains('夕焼け') && $prompt->isLandscape();
});

Image::assertNotGenerated('存在しないプロンプト');

Image::assertNothingGenerated();

キューに投入した画像生成については、キュー用のアサートメソッドを使用してください。For queued image generations, use the queued assertion methods:

Image::assertQueued(
    fn (QueuedImagePrompt $prompt) => $prompt->contains('夕焼け')
);

Image::assertNotQueued('存在しないプロンプト');

Image::assertNothingQueued();

すべての画像生成に対応するフェイクレスポンスがあることを確認するには、preventStrayImagesを使用できます。フェイクレスポンスが定義されていない状態で画像を生成すると、例外を投げます。To ensure all image generations have a corresponding fake response, you may use preventStrayImages. If an image is generated without a defined fake response, an exception will be thrown:

Image::fake()->preventStrayImages();

音声Audio

音声生成は、Audioクラスのfakeメソッドを呼び出すことでFakeにできます。音声をFakeにしたら、記録済みの音声生成プロンプトに対してさまざまなアサートを実行できます。Audio generations may be faked by invoking the fake method on the Audio class. Once audio has been faked, various assertions may be performed against the recorded audio generation prompts:

use Laravel\Ai\Audio;
use Laravel\Ai\Prompts\AudioPrompt;
use Laravel\Ai\Prompts\QueuedAudioPrompt;

// すべてのプロンプトに対して、固定のレスポンスを自動的に生成
Audio::fake();

// プロンプトレスポンスのリストを提供
Audio::fake([
    base64_encode($firstAudio),
    base64_encode($secondAudio),
]);

// 入ってきたプロンプトに基づいて、プロンプトレスポンスを動的に処理
Audio::fake(function (AudioPrompt $prompt) {
    return base64_encode('...');
});

音声を生成した後、受け取ったプロンプトについてアサートできます。After generating audio, you may make assertions about the prompts that were received:

Audio::assertGenerated(function (AudioPrompt $prompt) {
    return $prompt->contains('こんにちは') && $prompt->isFemale();
});

Audio::assertNotGenerated('存在しないプロンプト');

Audio::assertNothingGenerated();

キューに投入した音声生成については、キュー用のアサートメソッドを使用してください。For queued audio generations, use the queued assertion methods:

Audio::assertQueued(
    fn (QueuedAudioPrompt $prompt) => $prompt->contains('こんにちは')
);

Audio::assertNotQueued('存在しないプロンプト');

Audio::assertNothingQueued();

すべての音声生成に対応するフェイクレスポンスがあることを確認するには、preventStrayAudioを使用できます。フェイクレスポンスが定義されていない状態で音声を生成すると、例外を投げます。To ensure all audio generations have a corresponding fake response, you may use preventStrayAudio. If audio is generated without a defined fake response, an exception will be thrown:

Audio::fake()->preventStrayAudio();

文字起こしTranscriptions

文字起こしの生成は、Transcriptionクラスのfakeメソッドを呼び出すことでFakeできます。文字起こしをFakeにしたら、記録済みの文字起こし生成プロンプトに対してさまざまなアサートを実行できます。Transcription generations may be faked by invoking the fake method on the Transcription class. Once transcription has been faked, various assertions may be performed against the recorded transcription generation prompts:

use Laravel\Ai\Transcription;
use Laravel\Ai\Prompts\TranscriptionPrompt;
use Laravel\Ai\Prompts\QueuedTranscriptionPrompt;

// すべてのプロンプトに対して、固定のレスポンスを自動的に生成
Transcription::fake();

// プロンプトレスポンスのリストを提供
Transcription::fake([
    '最初の文字起こしテキスト。',
    '2番目の文字起こしテキスト。',
]);

// 入ってきたプロンプトに基づいて、プロンプトレスポンスを動的に処理...
Transcription::fake(function (TranscriptionPrompt $prompt) {
    return '文字起こしされたテキスト...';
});

文字起こしを生成した後、受け取ったプロンプトについてアサートを行えます。After generating transcriptions, you may make assertions about the prompts that were received:

Transcription::assertGenerated(function (TranscriptionPrompt $prompt) {
    return $prompt->language === 'en' && $prompt->isDiarized();
});

Transcription::assertNotGenerated(
    fn (TranscriptionPrompt $prompt) => $prompt->language === 'fr'
);

Transcription::assertNothingGenerated();

キュー投入した文字起こし生成については、キュー用のアサートメソッドを使用してください。For queued transcription generations, use the queued assertion methods:

Transcription::assertQueued(
    fn (QueuedTranscriptionPrompt $prompt) => $prompt->isDiarized()
);

Transcription::assertNotQueued(
    fn (QueuedTranscriptionPrompt $prompt) => $prompt->language === 'fr'
);

Transcription::assertNothingQueued();

すべての文字起こし生成に対応するフェイクレスポンスがあることを確認するには、preventStrayTranscriptionsを使用できます。フェイクレスポンスが定義されていない状態で文字起こしを生成する、例外を投げます。To ensure all transcription generations have a corresponding fake response, you may use preventStrayTranscriptions. If a transcription is generated without a defined fake response, an exception will be thrown:

Transcription::fake()->preventStrayTranscriptions();

埋め込みEmbeddings

埋め込み生成は、Embeddingsクラスのfakeメソッドを呼び出すことでFakeにできます。埋め込みをFakeにしたら、記録済みの埋め込み生成プロンプトに対してさまざまなアサートを実行できます。Embeddings generations may be faked by invoking the fake method on the Embeddings class. Once embeddings has been faked, various assertions may be performed against the recorded embeddings generation prompts:

use Laravel\Ai\Embeddings;
use Laravel\Ai\Prompts\EmbeddingsPrompt;
use Laravel\Ai\Prompts\QueuedEmbeddingsPrompt;

// すべてのプロンプトに対して、適切な次元のフェイク埋め込みを自動的に生成
Embeddings::fake();

// プロンプトレスポンスのリストを提供
Embeddings::fake([
    [$firstEmbeddingVector],
    [$secondEmbeddingVector],
]);

// 入ってきたプロンプトに基づいて、プロンプトレスポンスを動的に処理
Embeddings::fake(function (EmbeddingsPrompt $prompt) {
    return array_map(
        fn () => Embeddings::fakeEmbedding($prompt->dimensions),
        $prompt->inputs
    );
});

埋め込みを生成した後、受け取ったプロンプトについてアサートを行えます。After generating embeddings, you may make assertions about the prompts that were received:

Embeddings::assertGenerated(function (EmbeddingsPrompt $prompt) {
    return $prompt->contains('Laravel') && $prompt->dimensions === 1536;
});

Embeddings::assertNotGenerated(
    fn (EmbeddingsPrompt $prompt) => $prompt->contains('Other')
);

Embeddings::assertNothingGenerated();

キュー投入した埋め込み生成については、キュー用のアサートメソッドを使用してください。For queued embeddings generations, use the queued assertion methods:

Embeddings::assertQueued(
    fn (QueuedEmbeddingsPrompt $prompt) => $prompt->contains('Laravel')
);

Embeddings::assertNotQueued(
    fn (QueuedEmbeddingsPrompt $prompt) => $prompt->contains('Other')
);

Embeddings::assertNothingQueued();

すべての埋め込み生成に対応するフェイクレスポンスがあることを確認するには、preventStrayEmbeddingsを使用できます。フェイクレスポンスが定義されていない状態で埋め込みを生成する、例外を投げます。To ensure all embeddings generations have a corresponding fake response, you may use preventStrayEmbeddings. If embeddings are generated without a defined fake response, an exception will be thrown:

Embeddings::fake()->preventStrayEmbeddings();

リランクReranking

リランク操作は、Rerankingクラスのfakeメソッドを呼び出すことでFフェイクにできます。Reranking operations may be faked by invoking the fake method on the Reranking class:

use Laravel\Ai\Reranking;
use Laravel\Ai\Prompts\RerankingPrompt;
use Laravel\Ai\Responses\Data\RankedDocument;

// フェイクのリランクレスポンスを自動的に生成
Reranking::fake();

// カスタムレスポンスを提供
Reranking::fake([
    [
        new RankedDocument(index: 0, document: '最初', score: 0.95),
        new RankedDocument(index: 1, document: '2番目', score: 0.80),
    ],
]);

リランク後、実行された操作についてアサートを行えます。After reranking, you may make assertions about the operations that were performed:

Reranking::assertReranked(function (RerankingPrompt $prompt) {
    return $prompt->contains('Laravel') && $prompt->limit === 5;
});

Reranking::assertNotReranked(
    fn (RerankingPrompt $prompt) => $prompt->contains('Django')
);

Reranking::assertNothingReranked();

ファイルFiles

ファイル操作は、Filesクラスのfakeメソッドを呼び出すことでFakeにできます。File operations may be faked by invoking the fake method on the Files class:

use Laravel\Ai\Files;

Files::fake();

ファイル操作をFakeにした後、発生したアップロードや削除についてアサートを行えます。Once file operations have been faked, you may make assertions about the uploads and deletions that occurred:

use Laravel\Ai\Contracts\Files\StorableFile;
use Laravel\Ai\Files\Document;

// ファイルを保存
Document::fromString('Hello, Laravel!', mime: 'text/plain')
    ->as('hello.txt')
    ->put();

// アサートを実行
Files::assertStored(fn (StorableFile $file) =>
    (string) $file === 'Hello, Laravel!' &&
        $file->mimeType() === 'text/plain';
);

Files::assertNotStored(fn (StorableFile $file) =>
    (string) $file === 'Hello, World!'
);

Files::assertNothingStored();

ファイルの削除に対するアサートでは、ファイルIDを渡せます。For asserting against file deletions, you may pass a file ID:

Files::assertDeleted('file-id');
Files::assertNotDeleted('file-id');
Files::assertNothingDeleted();

ベクトルストアVector Stores

ベクトルストアの操作は、Storesクラスのfakeメソッドを呼び出すことでFakeにできます。ストアをFakeにすると、ファイル操作も自動的にFakeになります。Vector store operations may be faked by invoking the fake method on the Stores class. Faking stores will also fake file operations[#files] automatically:

use Laravel\Ai\Stores;

Stores::fake();

ストア操作をFakeにした後、作成または削除したストアについてアサートを行えます。Once store operations have been faked, you may make assertions about the stores that were created or deleted:

use Laravel\Ai\Stores;

// ストアを作成
$store = Stores::create('ナレッジベース');

// アサートを実行
Stores::assertCreated('ナレッジベース');

Stores::assertCreated(fn (string $name, ?string $description) =>
    $name === 'ナレッジベース'
);

Stores::assertNotCreated('別のストア');

Stores::assertNothingCreated();

ストアの削除に対するアサートでは、ストアIDを指定できます。For asserting against store deletions, you may provide the store ID:

Stores::assertDeleted('store_id');
Stores::assertNotDeleted('other_store_id');
Stores::assertNothingDeleted();

ファイルをストアに追加または削除したことをアサートするには、指定したStoreインスタンスのアサートメソッドを使用します。To assert files were added or removed from a store, use the assertion methods on a given Store instance:

Stores::fake();

$store = Stores::get('store_id');

// ファイルを追加/削除
$store->add('added_id');
$store->remove('removed_id');

// アサートを実行
$store->assertAdded('added_id');
$store->assertRemoved('removed_id');

$store->assertNotAdded('other_file_id');
$store->assertNotRemoved('other_file_id');

ファイルをプロバイダのファイルストレージに保存し、同じリクエスト内でベクトルストアに追加した場合、ファイルのプロバイダIDがわからないことがあります。この場合、assertAddedメソッドにクロージャを渡し、追加したファイルの内容に対してアサートを実行できます。If a file is stored in the provider's file storage[#files] and added to a vector store in the same request, you may not know the file's provider ID. In this case, you can pass a closure to the assertAdded method to assert against the content of the added file:

use Laravel\Ai\Contracts\Files\StorableFile;
use Laravel\Ai\Files\Document;

$store->add(Document::fromString('Hello, World!', 'text/plain')->as('hello.txt'));

$store->assertAdded(fn (StorableFile $file) => $file->name() === 'hello.txt');
$store->assertAdded(fn (StorableFile $file) => $file->content() === 'Hello, World!');

イベントEvents

Laravel AI SDKは、以下を含むさまざまなイベントをディスパッチします。The Laravel AI SDK dispatches a variety of events[/docs/{{version}}/events], including:

  • AddingFileToStoreAddingFileToStore
  • AgentPromptedAgentPrompted
  • AgentStreamedAgentStreamed
  • AudioGeneratedAudioGenerated
  • CreatingStoreCreatingStore
  • EmbeddingsGeneratedEmbeddingsGenerated
  • FileAddedToStoreFileAddedToStore
  • FileDeletedFileDeleted
  • FileRemovedFromStoreFileRemovedFromStore
  • FileStoredFileStored
  • GeneratingAudioGeneratingAudio
  • GeneratingEmbeddingsGeneratingEmbeddings
  • GeneratingImageGeneratingImage
  • GeneratingTranscriptionGeneratingTranscription
  • ImageGeneratedImageGenerated
  • InvokingToolInvokingTool
  • PromptingAgentPromptingAgent
  • RemovingFileFromStoreRemovingFileFromStore
  • RerankedReranked
  • RerankingReranking
  • StoreCreatedStoreCreated
  • StoringFileStoringFile
  • StreamingAgentStreamingAgent
  • ToolInvokedToolInvoked
  • TranscriptionGeneratedTranscriptionGenerated

これらのイベントをリスニングして、AI SDKの使用情報をログに記録したり保存したりできます。You can listen to any of these events to log or store AI SDK usage information.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
JSのみ表示

(JSが存在しない場合は、他を全表示)

和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作