クライアントサイド技術でLLM搭載Webアプリを構築する
オープンソースのローカルソフトウェアを使用し、LangChainの人気ユースケースであるRAG(文書検索拡張生成)を実装し、文書との対話を可能にする方法を紹介。
キーポイント
クライアントサイド技術のみでLLMアプリを構築する手法を実証
ローカル実行によるコスト削減とプライバシー保護の利点を提示
LangChain、Transformers.js、Voyなどのブラウザ対応ツールを活用したRAG実装
Web開発者向けのAI実装の新たな可能性を示す
影響分析・編集コメントを表示
影響分析
この記事は、AIアプリケーション開発の民主化をさらに進める可能性を示しており、サーバー依存からの脱却とプライバシー重視のAI実装という新たなトレンドを先導する内容です。特にWeb開発者コミュニティへのAI技術の普及を加速させる重要な実証例と言えます。
編集コメント
Python中心のAI開発からJavaScript/Web技術へのシフトを象徴する実践的なガイド。開発コストとデータプライバシーの両面で業界に新たな選択肢を提示している。
タイトル: クライアントサイド技術を用いたLLM搭載Webアプリの構築
本記事は、LangChainAIのJS/TSメンテナーであり、元Google PhotosエンジニアのJacob Leeによる寄稿である。従来、機械学習はPythonが主流であったが、ChatGPTの登場により多くの新規開発者、特に世界で最も広く使われるJavaScriptを扱うウェブ開発者がこの分野に参入している。LLMを活用したアプリ構築については、OpenAIやAnthropicなどへのAPI呼び出しによる方法が広く論じられてきたが、ここではあえてローカルモデルとブラウザ内で動作する技術のみを使用してウェブアプリを構築するアプローチを探る。
このクライアントサイド中心のアプローチには、主に3つの利点がある。
- コスト: 計算と推論が全てユーザーの端末で行われるため、開発者は安価なホスティング費用以外の追加コストを負担しない。
- プライバシー: ユーザーのデータがローカルマシンから外部に送信されることがない。
- 速度: HTTP呼び出しのオーバーヘッドがなく、潜在的な速度向上が期待できる(ただし、ユーザーのハードウェア性能により推論速度が低下する可能性もある)。
具体的な実証として、著者はオープンソースのローカルソフトウェアを用いて、LangChainで人気のユースケースであるRetrieval-Augmented Generation(RAG)、すなわち「文書と対話する」チェーンの再構築に挑戦した。RAGは、PDFやウェブページなどの非構造化データから情報を抽出し、自然言語で質問に答えることを可能にする。
実装は大きく2段階に分けられる。
第一段階は「データ準備」で、以下の手順を含む。
- 文書を意味的なまとまり(チャンク)に分割する。
- 埋め込みモデルを用いて各チャンクのベクトル表現を作成する。
- チャンクとベクトルを、ベクトル専用データベース(ベクトルストア)に格納する。
この工程では、LangChainの文書ローダーとスプリッター、XenovaのTransformers.jsパッケージでブラウザ動作可能に量子化されたHuggingFaceの小型埋め込みモデル、そしてWebAssemblyベースのベクトルストア「Voy」を組み合わせた。
第二段階は「質問応答」である。
- ユーザーの質問を受け取り、準備したベクトルストアから質問と意味的に最も類似する文書チャンクを検索する。
- 検索で得た文書チャンクと元の質問をLLMに与え、文書に基づいた最終的な回答を生成させる。
- 続く質問(代名詞や前文の参照を含む可能性がある)に対応するため、チャット履歴を考慮して質問を独立した形に書き換える「履歴依存質問チェーン」の追加ステップも必要となる。
この実験は、主要な処理をブラウザに移行させることで、コスト、プライバシー、レイテンシーの課題に同時に取り組む可能性を示している。必要な技術コンポーネントは既にJavaScript/WebAssemblyエコシステム内に存在しており
原文を表示
Building LLM-Powered Web Apps with Client-Side Technology
This is a guest blog post by Jacob Lee, JS/TS maintainer at @LangChainAI, formerly co-founder & CTO at @Autocode, engineer on Google photos.
The initial version of this blog post was a talk for Google’s internal WebML Summit 2023, which you can check out here:
It’s no secret that for a long time machine learning has been mostly a Python game, but the recent surge in popularity of ChatGPT has brought many new developers into the field. With JavaScript being the most widely-used programming language, it’s no surprise that this has included many web developers, who have naturally tried to build web apps.
There’s been a ton of ink spilled on building with LLMs via API calls to the likes of OpenAI, Anthropic, Google, and others, so I thought I’d try a different approach and try to build a web app using exclusively local models and technologies, preferably those that run in the browser!
Some major advantages to building this way are:
Cost. Since all compute and inference would be done client-side, there would be no additional cost to the developer building the app other than (very cheap) hosting.
Privacy. Nothing needs to leave the user’s local machine!
Potential speed increases due to no HTTP call overhead. This may be offset by slower inference due to user hardware limitations.
I decided to try recreating one of the most popular LangChain use-cases with open source, locally running software: a chain that performs Retrieval-Augmented Generation, or RAG for short, and allows you to “chat with your documents”. This allows you to glean information from data locked away in a variety of unstructured formats.
The first steps are to load our data and format it in a way that is later queryable using natural language. This involves the following:
Split a document (PDF, webpages, or some other data) into semantic chunks
Create a vector representation of each chunk using an embeddings model
Load the chunks and vectors into a specialized database called a vector store
These first steps required a few pieces: text splitters, an embeddings model, and a vectorstore. Fortunately, these all already existed in browser-friendly JS!
LangChain took care of the document loading and splitting. For embeddings, I used a small HuggingFace embeddings model quantized to run in the browser using Xenova’s Transformers.js package, and for the vectorstore, I used a really neat Web Assembly vectorstore called Voy.
Now that I had a pipeline set up for loading my data, the next step was to query it:
The general idea here is to take the user’s input question, search our prepared vectorstore for document chunks most semantically similar to the query, and use the retrieved chunks plus the original question to guide the LLM to a final answer based on our input data.
There’s an additional step required for followup questions, which may contain pronouns or other references to prior chat history. Because vectorstores perform retrieval by semantic similarity, these references can throw off retrieval. Therefore, we add an additional dereferencing step that rephrases the initial step into a “standalone” question before using that question to search our vectorstore.
Finding an LLM that could run in the browser proved difficult - powerful LLMs are massive, and the ones available via HuggingFace failed to generate good responses. There is also the Machine Learning Compilation’s WebLLM project, which looked promising but required a massive, multi-GB download on page load, which added a ton of latency.
I had experimented with Ollama as an easy, out-of-the-box way to run local models in the past, and was pleasantly surprised when I heard there was support for exposing a locally running model to a web app via a shell command. I plugged it in and it turned out to be the missing piece! I spun up the more recent, state-of-the-art Mistral 7B model, which ran comfortably on my 16GB M2 Macbook Pro, and ended up with the following local stack:
You can try out a live version of the Next.js app on Vercel:
You’ll need to have a Mistral instance running via Ollama on your local machine and make it accessible to the domain in question by running the following commands to avoid CORS issues:
$ ollama run mistral $ OLLAMA_ORIGINS=https://webml-demo.vercel.app OLLAMA_HOST=127.0.0.1:11435 ollama serve Here are some example traces in LangSmith, our observability and tracing platform, for a few questions. I used my personal resume as an input document:
“Who is this about?” https://smith.langchain.com/public/2386b1de-7afb-48a2-8c83-205162bfcac0/r
“Do they know JavaScript?” https://smith.langchain.com/public/18cec162-d12c-4034-aa9a-39b1cd2011ea/r
Overall, this worked out well. A few observations:
Open source models are advancing rapidly - I built the initial version of this app with Llama 2, and Mistral was announced just weeks later.
More and more consumer hardware manufacturers are inc
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み