jpskill.com
🛠️ 開発・MCP コミュニティ

Rig製LLMアプリ開発

rig

Rigは、Rust製のAIフレームワークで、エージェント構築、RAGパイプライン、ツール連携、構造化抽出、ストリーミング補完など、様々なLLM活用アプリを統一APIで開発効率化するSkill。

📜 元の英語説明(参考)

Build LLM-powered applications with Rig, the Rust AI framework. Use when creating agents, RAG pipelines, tool-calling workflows, structured extraction, or streaming completions. Covers all providers with a unified API.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Rigは、Rust製のAIフレームワークで、エージェント構築、RAGパイプライン、ツール連携、構造化抽出、ストリーミング補完など、様々なLLM活用アプリを統一APIで開発効率化するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o rig.zip https://jpskill.com/download/5980.zip && unzip -o rig.zip && rm rig.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/5980.zip -OutFile "$d\rig.zip"; Expand-Archive "$d\rig.zip" -DestinationPath $d -Force; ri "$d\rig.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して rig.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → rig フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Rig を使った構築

Rig は、プロバイダーに依存しない API を使用して LLM 搭載アプリケーションを構築するための Rust ライブラリです。 すべてのパターンは、ビルダーパターンと tokio を介した async/await を使用しています。

クイックスタート

use rig::completion::Prompt;
use rig::providers::openai;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let client = openai::Client::from_env();

    let agent = client
        .agent(openai::GPT_4O)
        .preamble("You are a helpful assistant.")
        .build();

    let response = agent.prompt("Hello!").await?;
    println!("{}", response);
    Ok(())
}

コアパターン

1. シンプルなエージェント

let agent = client.agent(openai::GPT_4O)
    .preamble("System prompt")
    .temperature(0.7)
    .max_tokens(2000)
    .build();

let response = agent.prompt("Your question").await?;

2. ツールを持つエージェント

Tool トレイトを実装してツールを定義し、それをアタッチします。

let agent = client.agent(openai::GPT_4O)
    .preamble("You can use tools.")
    .tool(MyTool)
    .build();

Tool トレイトの完全なシグネチャについては、references/tools.md を参照してください。

3. RAG (Retrieval-Augmented Generation)

let embedding_model = client.embedding_model(openai::TEXT_EMBEDDING_ADA_002);
let index = vector_store.index(embedding_model);

let agent = client.agent(openai::GPT_4O)
    .preamble("Answer using the provided context.")
    .dynamic_context(5, index)  // top-5 similar docs per query
    .build();

ベクターストアの設定と Embed derive マクロについては、references/rag.md を参照してください。

4. ストリーミング

use futures::StreamExt;
use rig::streaming::StreamedAssistantContent;
use rig::agent::prompt_request::streaming::MultiTurnStreamItem;

let mut stream = agent.stream_prompt("Tell me a story").await?;

while let Some(chunk) = stream.next().await {
    match chunk? {
        MultiTurnStreamItem::StreamAssistantItem(
            StreamedAssistantContent::Text(text)
        ) => print!("{}", text.text),
        MultiTurnStreamItem::FinalResponse(resp) => {
            println!("\n{}", resp.response());
        }
        _ => {}
    }
}

5. 構造化抽出

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, JsonSchema)]
struct Person {
    pub name: Option<String>,
    pub age: Option<u8>,
}

let extractor = client.extractor::<Person>(openai::GPT_4O).build();
let person = extractor.extract("John is 30 years old.").await?;

6. 履歴付きチャット

use rig::completion::Chat;

let history = vec![
    Message::from("Hi, I'm Alice."),
    // ...previous messages
];
let response = agent.chat("What's my name?", history).await?;

エージェントビルダーメソッド

メソッド 説明
.preamble(str) システムプロンプトを設定します
.context(str) 静的コンテキストドキュメントを追加します
.dynamic_context(n, index) トップ n 検索による RAG を追加します
.tool(impl Tool) 呼び出し可能なツールをアタッチします
.tools(Vec<Box<dyn ToolDyn>>) 複数のツールをアタッチします
.temperature(f64) 温度 (0.0-1.0) を設定します
.max_tokens(u64) 最大出力トークンを設定します
.additional_params(json!{...}) プロバイダー固有のパラメーター
.tool_choice(ToolChoice) ツールの使用を制御します
.build() エージェントを構築します

利用可能なプロバイダー

ProviderName::Client::from_env() または ProviderName::Client::new("key") でクライアントを作成します。

プロバイダー モジュール モデル定数の例
OpenAI openai GPT_4O, GPT_4O_MINI
Anthropic anthropic CLAUDE_4_OPUS, CLAUDE_4_SONNET
Cohere cohere COMMAND_R_PLUS
Mistral mistral MISTRAL_LARGE
Gemini gemini モデル文字列
Groq groq モデル文字列
Ollama ollama モデル文字列
DeepSeek deepseek モデル文字列
xAI xai モデル文字列
Together together モデル文字列
Perplexity perplexity モデル文字列
OpenRouter openrouter モデル文字列
HuggingFace huggingface モデル文字列
Azure azure デプロイ文字列
Hyperbolic hyperbolic モデル文字列
Galadriel galadriel モデル文字列
Moonshot moonshot モデル文字列
Mira mira モデル文字列
Voyage AI voyageai 埋め込みのみ

ベクターストアクレート

バックエンド クレート
インメモリ rig-core (組み込み)
MongoDB rig-mongodb
LanceDB rig-lancedb
Qdrant rig-qdrant
SQLite rig-sqlite
Neo4j rig-neo4j
Milvus rig-milvus
SurrealDB rig-surrealdb

主要なルール

  • すべての非同期コードは tokio 上で実行されます。
  • WASM 互換性のため、生の Send / Sync の代わりに WasmCompatSend / WasmCompatSync を使用してください。
  • thiserror を使用して適切なエラー型を使用してください — Result<(), String> は決して使用しないでください。
  • .unwrap() は避けてください — ? 演算子を使用してください。

詳細なリファレンス

詳細な API ドキュメント (Claude Code スキル経由でインストールした場合に利用可能):

  • tools — Tool トレイト、ToolDefinition、ToolEmbedding、アタッチメントパターン
  • rag — ベクターストア、Embed derive、EmbeddingsBuilder、検索リクエスト
  • providers — プロバイダー固有の初期化、モデル定数、環境変数
  • patterns — マルチエージェント、フック、ストリーミングの詳細、チェイニング、抽出

完全なリファレンスについては、rig-core/examples/ または https://docs.rig.rs の Rig の例を参照してください。

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Building with Rig

Rig is a Rust library for building LLM-powered applications with a provider-agnostic API. All patterns use the builder pattern and async/await via tokio.

Quick Start

use rig::completion::Prompt;
use rig::providers::openai;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let client = openai::Client::from_env();

    let agent = client
        .agent(openai::GPT_4O)
        .preamble("You are a helpful assistant.")
        .build();

    let response = agent.prompt("Hello!").await?;
    println!("{}", response);
    Ok(())
}

Core Patterns

1. Simple Agent

let agent = client.agent(openai::GPT_4O)
    .preamble("System prompt")
    .temperature(0.7)
    .max_tokens(2000)
    .build();

let response = agent.prompt("Your question").await?;

2. Agent with Tools

Define a tool by implementing the Tool trait, then attach it:

let agent = client.agent(openai::GPT_4O)
    .preamble("You can use tools.")
    .tool(MyTool)
    .build();

See references/tools.md for the full Tool trait signature.

3. RAG (Retrieval-Augmented Generation)

let embedding_model = client.embedding_model(openai::TEXT_EMBEDDING_ADA_002);
let index = vector_store.index(embedding_model);

let agent = client.agent(openai::GPT_4O)
    .preamble("Answer using the provided context.")
    .dynamic_context(5, index)  // top-5 similar docs per query
    .build();

See references/rag.md for vector store setup and the Embed derive macro.

4. Streaming

use futures::StreamExt;
use rig::streaming::StreamedAssistantContent;
use rig::agent::prompt_request::streaming::MultiTurnStreamItem;

let mut stream = agent.stream_prompt("Tell me a story").await?;

while let Some(chunk) = stream.next().await {
    match chunk? {
        MultiTurnStreamItem::StreamAssistantItem(
            StreamedAssistantContent::Text(text)
        ) => print!("{}", text.text),
        MultiTurnStreamItem::FinalResponse(resp) => {
            println!("\n{}", resp.response());
        }
        _ => {}
    }
}

5. Structured Extraction

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, JsonSchema)]
struct Person {
    pub name: Option<String>,
    pub age: Option<u8>,
}

let extractor = client.extractor::<Person>(openai::GPT_4O).build();
let person = extractor.extract("John is 30 years old.").await?;

6. Chat with History

use rig::completion::Chat;

let history = vec![
    Message::from("Hi, I'm Alice."),
    // ...previous messages
];
let response = agent.chat("What's my name?", history).await?;

Agent Builder Methods

Method Description
.preamble(str) Set system prompt
.context(str) Add static context document
.dynamic_context(n, index) Add RAG with top-n retrieval
.tool(impl Tool) Attach a callable tool
.tools(Vec<Box<dyn ToolDyn>>) Attach multiple tools
.temperature(f64) Set temperature (0.0-1.0)
.max_tokens(u64) Set max output tokens
.additional_params(json!{...}) Provider-specific params
.tool_choice(ToolChoice) Control tool usage
.build() Build the agent

Available Providers

Create a client with ProviderName::Client::from_env() or ProviderName::Client::new("key").

Provider Module Example Model Constant
OpenAI openai GPT_4O, GPT_4O_MINI
Anthropic anthropic CLAUDE_4_OPUS, CLAUDE_4_SONNET
Cohere cohere COMMAND_R_PLUS
Mistral mistral MISTRAL_LARGE
Gemini gemini model string
Groq groq model string
Ollama ollama model string
DeepSeek deepseek model string
xAI xai model string
Together together model string
Perplexity perplexity model string
OpenRouter openrouter model string
HuggingFace huggingface model string
Azure azure deployment string
Hyperbolic hyperbolic model string
Galadriel galadriel model string
Moonshot moonshot model string
Mira mira model string
Voyage AI voyageai embeddings only

Vector Store Crates

Backend Crate
In-memory rig-core (built-in)
MongoDB rig-mongodb
LanceDB rig-lancedb
Qdrant rig-qdrant
SQLite rig-sqlite
Neo4j rig-neo4j
Milvus rig-milvus
SurrealDB rig-surrealdb

Key Rules

  • All async code runs on tokio.
  • Use WasmCompatSend / WasmCompatSync instead of raw Send / Sync for WASM compatibility.
  • Use proper error types with thiserror — never Result<(), String>.
  • Avoid .unwrap() — use ? operator.

Further Reference

Detailed API documentation (available when installed via Claude Code skills):

  • tools — Tool trait, ToolDefinition, ToolEmbedding, attachment patterns
  • rag — Vector stores, Embed derive, EmbeddingsBuilder, search requests
  • providers — Provider-specific initialization, model constants, env vars
  • patterns — Multi-agent, hooks, streaming details, chaining, extraction

For the full reference, see the Rig examples at rig-core/examples/ or https://docs.rig.rs