# Web inference-sdk

### WebRTC Streaming이란?

`@roboflow/inference-sdk` 은 WebRTC를 사용하여 브라우저에서 Roboflow의 inference servers로 실시간 비디오 스트리밍을 가능하게 합니다. 이를 통해 다음이 가능합니다:

* **Workflows 실행** - 복잡한 다단계 computer vision 파이프라인 실행
* **모든 Model 접근** - 모든 Roboflow model type 사용
* **Server-Side Processing** - 강력한 GPU 활용
* **낮은 지연 시간** - WebRTC는 거의 실시간에 가까운 결과를 제공합니다
* **양방향 통신** - 스트리밍 중 데이터 송수신

### 설치

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

### 빠른 시작

시작하려면 아래의 video/sample code를 확인하세요:

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

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

// ⚠️ 개발용으로만 withApiKey를 사용하세요
// ⚠️ 프로덕션에서는 API key가 노출되므로 이 코드를 사용하지 마세요
// 프로덕션에서는 backend proxy를 사용하세요(다음 섹션 참조)
const connector = connectors.withApiKey("your-api-key");

// 카메라 stream 가져오기
const stream = await streams.useCamera({
  video: {
    facingMode: { ideal: "environment" },
    width: { ideal: 640 },
    height: { ideal: 480 }
  }
});

// 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 결과:", data);
  }
});

// 처리된 video 표시
const videoElement = document.getElementById('video');
videoElement.srcObject = await connection.remoteStream();

// 완료되면 정리
await connection.cleanup();
```

### 🔐 보안 모범 사례

**프로덕션 애플리케이션의 frontend code에서 API key를 절대 노출하지 마세요.**

다음 `connectors.withApiKey()` 메서드는 데모에는 편리하지만 브라우저에 API key를 노출합니다. **프로덕션에서는 항상 backend proxy를 사용하세요:**

#### 보안이 적용된 프로덕션 패턴

**Frontend:**

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

// 직접 API key 대신 proxy endpoint 사용
const connector = connectors.withProxyUrl('/api/init-webrtc');

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

**Backend (Express):**

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

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

  // API key는 서버에서 안전하게 유지됩니다
  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);
});
```

### 주요 기능

#### 동적 Output 재구성

재시작 없이 런타임에 stream 및 data output을 변경합니다:

```typescript
// 다른 visualization으로 전환
connection.reconfigureOutputs({
  streamOutput: ["blur_visualization"]
});

// 모든 data output 활성화
connection.reconfigureOutputs({
  dataOutput: ["*"]
});

// 둘 다 한 번에 변경
connection.reconfigureOutputs({
  streamOutput: ["annotated_image"],
  dataOutput: ["predictions", "counts"]
});
```

### 완전한 동작 예제

frontend와 backend code를 모두 포함한 전체 동작 예제는 [sample application repository](https://github.com/roboflow/inferenceSampleApp)를 참조하세요. 이 sample app은 다음을 보여줍니다:

* API key 보안을 위한 적절한 backend proxy 설정
* 카메라 streaming 통합
* 오류 처리 및 connection 관리
* 프로덕션에 바로 사용할 수 있는 패턴

### 리소스

* [예제 애플리케이션](https://github.com/roboflow/inferenceSampleApp)
* [NPM의 패키지](https://www.npmjs.com/package/@roboflow/inference-sdk)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.roboflow.com/roboflow/roboflow-ko/deploy/sdks/web-browser/web-inference-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
