목차
transformersjs는 서버 없이 브라우저에서 직접 트랜스포머 모델을 실행하는 JavaScript 라이브러리다. 모델은 최초 다운로드 후 로컬에 캐시되어 오프라인에서도 동작한다. 이 튜토리얼은 pipeline() API를 사용해 세 가지 NLP 과제를 구현하는 방법을 다룬다.
설치
<!-- CDN (별도 빌드 과정 없이 바로 사용) -->
<script type="module">
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3/dist/transformers.min.js';
</script># npm 프로젝트
npm install @huggingface/transformersPython의 pipeline() 사용 경험이 있다면 JavaScript API가 거의 동일하게 느껴진다.
// Python과 거의 동일한 구조
import { pipeline } from '@huggingface/transformers';
const classifier = await pipeline('sentiment-analysis');
const result = await classifier('I love transformers!');Task 1: 텍스트 분류 (감성 분석)
<!DOCTYPE html>
<html>
<body>
<input id="text" placeholder="분석할 텍스트 입력" />
<button onclick="analyze()">분석</button>
<pre id="result"></pre>
<script type="module">
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3/dist/transformers.min.js';
let classifier;
async function init() {
classifier = await pipeline('sentiment-analysis');
}
window.analyze = async () => {
const text = document.getElementById('text').value;
const result = await classifier(text);
document.getElementById('result').textContent = JSON.stringify(result, null, 2);
};
init();
</script>
</body>
</html>출력 예시:
[{ "label": "POSITIVE", "score": 0.9998 }]Task 2: 제로샷 레이블링 (Zero-shot Classification)
훈련 데이터 없이 임의의 카테고리로 텍스트를 분류한다. 레이블을 런타임에 자유롭게 지정할 수 있어 유연하다.
const classifier = await pipeline('zero-shot-classification');
const result = await classifier(
'서버가 다운되어 결제가 안 됩니다', // 분류할 텍스트
['기술 지원', '결제 문제', '계정 문의', '기타'] // 후보 레이블
);
console.log(result.labels[0]); // "결제 문제"
console.log(result.scores[0]); // 0.91 (해당 레이블의 확률)Task 3: 질의응답 (Question Answering)
주어진 컨텍스트 안에서 질문의 답을 추출한다.
const qa = await pipeline('question-answering');
const result = await qa({
question: '이 제품의 가격은 얼마인가?',
context: '스탠다드 플랜은 월 9,900원이며, 프로 플랜은 월 29,900원입니다.'
});
console.log(result.answer); // "월 9,900원"
console.log(result.score); // 0.87실전 예시: 고객 지원 티켓 라우팅
세 파이프라인을 결합해 인입 티켓을 자동으로 분류하고 담당팀에 배정한다.
async function routeTicket(ticketText) {
const sentiment = await sentimentPipeline(ticketText);
const category = await zeroShotPipeline(ticketText, ['기술', '결제', '계정', '환불']);
const isUrgent = sentiment[0].label === 'NEGATIVE' && sentiment[0].score > 0.9;
const team = category.labels[0];
return {
team,
priority: isUrgent ? 'HIGH' : 'NORMAL',
confidence: category.scores[0]
};
}한계와 주의사항
- 모델 파일이 수백 MB이므로 첫 실행 시 다운로드 시간이 걸린다
- 브라우저 WASM 기반 실행이라 GPU 가속은 WebGPU 지원 브라우저에서만 동작
- 복잡한 추론이 필요한 작업은 여전히 서버 측 모델이 유리
관련 문서
- transformersjs — Transformers.js 개요 및 설치 가이드
- transformersjs-tutorial-chrome-extension — Manifest V3 크롬 확장에 AI 통합하기
참고 자료
- Practical NLP in the Browser with Transformers.js — KDnuggets (2026-05-29)