크롬 확장 프로그램에서 Transformers.js 사용하기

크롬 확장 프로그램에서 Transformers.js 사용하기

Hugging Face는 Gemma 4 E2B로 구동되는 데모 브라우저 확장 프로그램을 출시하여 Chrome 확장 프로그램 내에서 로컬 AI 기능을 실행하는 방법을 보여줍니다. 이 구현은 Manifest V3 제약 조건 하에서 Transformers.js를 활용하며, 백그라운드 서비스 워커가 모델 오케스트레이션을 관리하고 UI 및 콘텐츠 스크립트는 얇은 클라이언트로 유지되는 분리된 아키텍처를 사용합니다.

크롬 확장 프로그램 아키텍처 (Manifest V3)

핵심 아키텍처 전략은 UI 응답성을 보장하고 중복 모델 로드를 방지하기 위해 세 가지 주요 Chrome 런타임 컨텍스트 간에 관심사의 분리를 수행하는 것입니다.

런타임 컨텍스트 및 진입점

As defined in the manifest.json, the extension utilizes three entry points:

  • Background Service Worker (background.js): 에이전트 생명 주기, 모델 초기화, 도구 실행을 위한 제어 평면으로 작동합니다.
  • Side Panel (sidebar.html): 채팅 입력/출력 및 스트리밍 업데이트를 위한 상호작용 계층으로 작동합니다.
  • Content Script (content.js): DOM 추출 및 하이라이트 작업을 위한 페이지 브리지로 기능합니다.

메시징 및 오케스트레이션

Because these runtimes are isolated, a typed messaging contract (defined via enums) coordinates actions. The background service worker acts as the single coordinator:

  1. The side panel sends a request (e.g., AGENT_GENERATE_TEXT).
  2. The background worker appends the message to the conversation history, runs inference, and executes tools.
  3. The background worker emits an update (e.g., MESSAGES_UPDATE) back to the side panel for rendering.

Transformers.js 통합 세부 사항

모델 역할 및 책임

확장 프로그램은 추론과 검색의 균형을 맞추기 위해 두 가지 서로 다른 모델을 사용합니다:

  • Text Generation (LLM): onnx-community/gemma-4-E2B-it-ONNX (q4f16)는 추론 및 도구 호출 결정을 처리합니다.
  • Vector Embeddings: onnx-community/all-MiniLM-L6-v2-ONNX (fp32)는 기록 및 웹사이트 콘텐츠에서의 의미적 유사도 검색을 위한 임베딩을 생성합니다.

추론 및 캐싱

모든 추론은 pipeline("text-generation", ...)과 일관된 KV 캐싱을 위한 DynamicCache 클래스를 사용한 백그라운드 서비스 워커 내에서 실행되며, 임베딩을 위해서는 pipeline("feature-extraction", ...)가 사용됩니다.

Hosting inference in the background worker ensures that model artifacts are cached under the extension origin (chrome-extension://<extension-id>) rather than per-website origins, providing a shared cache across the entire installation. Developers must account for the Manifest V3 lifecycle, as service workers can be suspended and restarted, requiring model runtime state to be recoverable.

에이전트 및 도구 실행 루프

도구 호출 메커니즘

Transformers.js는 모델별 채팅 템플릿을 사용하여 프롬프트를 포맷합니다. Gemma 4의 경우, 모델이 도구를 호출하기로 결정하면 특수 도구 호출 토큰 블록(예: <|tool_call>call:getWeather{location:<|">Bern<|">}<tool_call|>)을 방출합니다. 확장은 이러한 모델 출력을 결정적 실행으로 변환하기 위해 정규화 레이어(webMcp)와 파서(extractToolCalls)를 사용합니다.

루프 설계 (Agent.runAgent)

확장은 내부 모델 트랜스크립트와 사용자向け 채팅 메시지를 분리합니다:

  • Internal Transcript: generator(...) 함수에 사용되는 시스템, 사용자, 도구, 어시스턴트 턴을 포함합니다.
  • UI Transcript: 스트리밍된 어시스턴트 텍스트, 도구 실행 메타데이터, 성능 지표를 포함합니다.

The execution flow follows a loop: user input is added $ ightarrow$ tokens are streamed $ ightarrow$ tool calls are parsed and executed in the background $ ightarrow$ results are fed back into the prompt $ ightarrow$ the loop repeats until no tool calls remain.

데이터 경계 및 지속성

성능과 내구성을 최적화하기 위해 라이프사이클 및 액세스 패턴에 따라 상태가 분배됩니다:

  • Conversation State: 빠른 오케스트레이션을 위해 백그라운드 메모리(Agent.chatMessages)에 저장됩니다.
  • Tool Preferences: 세션 간에 chrome.storage.local에 지속됩니다.
  • Semantic History Vectors: 로컬 검색을 위해 IndexedDB(VectorHistoryDB)에 저장됩니다.
  • Extracted Page Content: 활성 URL을 키로 하는 백그라운드 캐시(WebsiteContentManager)에서 관리됩니다.

빌드 및 패키징

Manifest V3 요구 사항을 충족하기 위해 프로젝트는 Vite를 사용한 멀티 엔트리 빌드를 사용하여 Chrome 엔트리 포인트당 하나의 아티팩트를 보장합니다. 콘텐츠 스크립트는 런타임 청크 로딩 문제를 방지하기 위해 자체 포함 출력으로 유지되며, 출력 이름은 manifest.json 정의와 정확히 일치합니다.

Sources