> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/deployment/ja/self-hosted/sdks/web-browser/web-inference-sdk.md).

# Web inference-sdk

既存の Serverless Video Streaming 連携向けの JavaScript WebRTC リファレンス。新しい管理されたライブカメラのデプロイには Cloud Streaming を使用してください。

{% hint style="info" %}
以下のホスト型 WebRTC インテグレーションでは、非推奨の [Serverless Video Streaming API](https://docs.roboflow.com/deployment/ja/roboflow-cloud/serverless-api/serverless-video-streaming-api.md)を使用します。新しいマネージド型ライブカメラのデプロイには、 [Cloud Streaming](https://docs.roboflow.com/deployment/ja/roboflow-cloud/cloud-streaming.md)を使用してください。ソース、ジョブ、結果のインターフェースは、このページの WebRTC メソッドとは別個のものです。
{% endhint %}

### WebRTC ストリーミングとは？

`@roboflow/inference-sdk` を使用すると、WebRTC によりブラウザーから Roboflow の推論サーバーへリアルタイムで動画をストリーミングできます。これにより、次のことが可能になります。

* **ワークフローの実行** - 複雑な複数ステップのコンピュータービジョンパイプラインを実行
* **すべてのモデルにアクセス** - Roboflow のあらゆる種類のモデルを使用
* **サーバーサイド処理** - 高性能な GPU を活用
* **低レイテンシ** - WebRTC により、ほぼリアルタイムで結果を取得
* **双方向通信** - ストリーミング中にデータを送受信

### インストール

```bash
npm install @roboflow/inference-sdk
```

### クイックスタート

使い始めるには、以下の動画／サンプルコードをご覧ください。

{% embed url="<https://www.loom.com/share/48b7c442a69c49e081d0dbec49e1ab57>" %}

```typescript
import { connectors, webrtc, streams } from '@roboflow/inference-sdk';

// ⚠️ Use withApiKey for development only
// ⚠️ Do not use this in production, because it will expose your API key
// For production, use a backend proxy (see next section)
const connector = connectors.withApiKey("your-api-key");

// Get camera stream
const stream = await streams.useCamera({
  video: {
    facingMode: { ideal: "environment" },
    width: { ideal: 640 },
    height: { ideal: 480 }
  }
});

// Start WebRTC connection
const connection = await webrtc.useStream({
  source: stream,
  connector,
  wrtcParams: {
    workspaceName: "your-workspace",
    workflowId: "your-workflow",
    imageInputName: "image",
    streamOutputNames: ["output"],
    dataOutputNames: ["predictions"]
  },
  onData: (data) => {
    console.log("Inference results:", data);
  }
});

// Display processed video
const videoElement = document.getElementById('video');
videoElement.srcObject = await connection.remoteStream();

// Clean up when done
await connection.cleanup();
```

### 🔐 セキュリティのベストプラクティス

**本番環境のアプリケーションでは、API キーをフロントエンドのコードに絶対に含めないでください。**

この `connectors.withApiKey()` メソッドはデモには便利ですが、ブラウザー上で API キーが公開されます。 **本番環境では、必ずバックエンドプロキシを使用してください。**

#### 本番環境向けの安全なパターン

**フロントエンド:**

```typescript
import { connectors, webrtc, streams } from '@roboflow/inference-sdk';

// APIキーを直接使わず、プロキシエンドポイントを使用する
const connector = connectors.withProxyUrl('/api/init-webrtc');

const stream = await streams.useCamera({ video: true });
const connection = await webrtc.useStream({
  source: stream,
  connector,
  wrtcParams: { /* ... */ }
});
```

**バックエンド（Express）:**

```typescript
import { InferenceHTTPClient } from '@roboflow/inference-sdk/api';

app.post('/api/init-webrtc', async (req, res) => {
  const { offer, wrtcparams } = req.body;

  // APIキーはサーバー上で安全に保持される
  const client = InferenceHTTPClient.init({
    apiKey: process.env.ROBOFLOW_API_KEY
  });

  const answer = await client.initializeWebrtcWorker({
    offer,
    workspaceName: wrtcparams.workspaceName,
    workflowId: wrtcparams.workflowId,
    config: {
      imageInputName: wrtcparams.imageInputName,
      streamOutputNames: wrtcparams.streamOutputNames,
      dataOutputNames: wrtcparams.dataOutputNames
    }
  });

  res.json(answer);
});
```

### 主な機能

#### 出力の動的な再設定

再起動せずに、実行時にストリーム出力とデータ出力を変更できます。

```typescript
// 別のビジュアライゼーションに切り替える
connection.reconfigureOutputs({
  streamOutput: ["blur_visualization"]
});

// すべてのデータ出力を有効にする
connection.reconfigureOutputs({
  dataOutput: ["*"]
});

// ストリーム出力とデータ出力を同時に変更する
connection.reconfigureOutputs({
  streamOutput: ["annotated_image"],
  dataOutput: ["predictions", "counts"]
});
```

### 完全な動作例

フロントエンドとバックエンドのコードを含む完全な動作例については、 [サンプルアプリケーションのリポジトリ](https://github.com/roboflow/inferenceSampleApp)をご覧ください。サンプルアプリでは、次の内容を紹介しています。

* APIキーを安全に保つための適切なバックエンドプロキシの設定
* カメラストリーミングの連携
* エラー処理と接続管理
* 本番環境に対応したパターン

### リソース

* [サンプルアプリケーション](https://github.com/roboflow/inferenceSampleApp)
* [NPM パッケージ](https://www.npmjs.com/package/@roboflow/inference-sdk)
