iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
✨

Running Local LLMs in Chrome Extensions with Vercel AI SDK

に公開
2025/05/21
2件

Introduction

Tools that leverage LLMs for coding, such as Cursor and Cline, are becoming popular. Many of you might be starting to feel like you want to build your own tools using LLMs, rather than just using existing ones.

Conventionally, AI development has centered around the Python ecosystem. However, considering development efficiency for web applications, there are many cases where you might want to unify the frontend and backend using the same language. Therefore, in this article, I will introduce the Vercel AI SDK, which allows you to implement AI features with JavaScript.

https://sdk.vercel.ai/

Vercel AI SDK is an SDK designed to make it easy to use LLM features in web applications. It simplifies implementation between the client and server, making it easy to implement AI features, including chat-like UIs. This allows developers to focus on developing the core features of their applications without worrying about complex LLM model integrations.

In this article, I will explain the basic usage of the Vercel AI SDK and, as an application, how to utilize it in Chrome extensions.

Basic Usage of AI SDK

2025-05-21 Update: Sample code has been updated because the method for specifying GitHub Models endpoints and model IDs has changed.

Backend (Hono + GitHub Models)

First, let's try using the Vercel AI SDK on the backend. We will generate text using GitHub Models as the LLM.

GitHub Models is a service provided by GitHub for developers to easily try out various LLM models. While it is not suitable for production use due to limitations such as context length, it is ideal for trial purposes like this because it can be used for free as long as you have a GitHub token.

You can use any web server you are familiar with, but for this article, we will use Hono. You can call an LLM to generate text using the AI SDK's generateText.

// server.ts
import { Hono } from 'hono';
import { serve } from '@hono/node-server'
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';

const app = new Hono();
// Create an instance of the OpenAI model
const model = createOpenAI({
    baseURL: 'https://models.github.io/inference',
    apiKey: process.env.GITHUB_TOKEN
}).chat('openai/gpt-4o');

app.post('/generate', async (c) => {
  // Get the prompt from the request body
  const { prompt } = await c.req.json<{ prompt: string }>();

  // Generate text using the LLM
  const { text } = await generateText({ model, prompt, });
  return c.json({ text });
});

const PORT = 3000;
serve({
    fetch: app.fetch,
    port: PORT
})

console.log(`Server running at http://localhost:${PORT}/`);

Even though the LLM provider is GitHub Models, we are using createOpenAI, which seems specific to OpenAI. However, since GitHub Models is compatible with the OpenAI API, this works fine. I haven't confirmed if every single model provided by GitHub Models works this way, but at least for GPT-4o, the JS sample code on GitHub Models uses the official OpenAI SDK, so it doesn't seem to be an issue.

In this way, the AI SDK provides createXXX functions that wrap the respective APIs for each LLM provider. By passing the model to functions like generateText or the later-mentioned streamText, it allows developers to utilize LLM features without having to worry about the specific APIs of each individual LLM service. I will touch upon the convenience of this characteristic again later.

To actually run the server and check its operation, follow these steps. Although the code above is written in TypeScript, you can execute it directly without transpiling to JS by using the --experimental-strip-types option supported since Node.js v22.

# Set the gh token to GITHUB_TOKEN
export GITHUB_TOKEN=$(gh auth token)

# Start the server
node --experimental-strip-types server.ts

# Open another terminal and send JSON via POST
$ curl -X POST --json '{"prompt":"What is the capital of Japan?"}' http://localhost:3000/generate
{"text":"The capital of Japan is **Tokyo**. Tokyo is the political, economic, and cultural center of Japan and is considered one of the world's most important cities. Furthermore, since the Meiji Restoration in 1868, the functions of the capital were moved from Kyoto to Tokyo. Since then, Tokyo has fulfilled the role of Japan's capital."}

We have confirmed that GPT-4o from GitHub Models can be utilized using only a GITHUB_TOKEN.

Frontend (React + useChat)

https://sdk.vercel.ai/docs/ai-sdk-ui/chatbot

When using the AI SDK with React, you can easily implement the common chat UI by utilizing the useChat hook. useChat provides a comprehensive set of features required for a chat-style UI, such as message sending and receiving, state management, and states for loading indicators.

First, create a frontend project using Vite with npm create vite@latest. Then, replace the original App.tsx entirely to implement an extremely simple chat UI using the AI SDK.

// App.tsx
import { useChat } from '@ai-sdk/react';

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    // Specify the backend endpoint
    api: 'http://localhost:3000/api/chat',
  });

  return (
    <div>
      {messages.map(message => (
        <div key={message.id}>
          {message.role === 'user' ? 'User: ' : 'AI: '}
          {message.content}
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input
          name="prompt"
          placeholder="Enter your question"
          value={input}
          onChange={handleInputChange}
        />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

It's surprising how a minimal chat UI can be completed with just this much code. By default, useChat makes a request to /api/chat on the server where the frontend is running if the api parameter is omitted. In the current setup, it would point to the Vite dev server, so we need to specify localhost:3000/api/chat to point to the Hono backend we created earlier.

The backend connected to by useChat must return a response via streaming. By using the streamText function provided by the AI SDK, it's possible to return the LLM results as a stream.

// server.ts
import { Hono } from 'hono';
import { serve } from '@hono/node-server'
import { cors } from 'hono/cors'
import { createOpenAI } from '@ai-sdk/openai';
import { streamText } from 'ai';

const app = new Hono();
// Since the client is running on the Vite server at localhost:5173, CORS must be allowed
app.use('/api/*', cors())

// Create an instance of the OpenAI model
const model = createOpenAI({
    baseURL: 'https://models.github.io/inference',
    apiKey: process.env.GITHUB_TOKEN
}).chat('openai/gpt-4o');

// Add the /api/chat endpoint
app.post('/api/chat', async (c) => {
    const { messages } = await c.req.json();
    const result = streamText({
        model,
        system: 'You are a helpful assistant.',
        messages,
    });
    return result.toDataStreamResponse();
});

const PORT = 3000;
serve({
  fetch: app.fetch,
  port: PORT
})

console.log(`Server running at http://localhost:${PORT}/`);

Let's actually start the frontend and backend to check the operation.

# Set the gh token to GITHUB_TOKEN
export GITHUB_TOKEN=$(gh auth token)

# Start the Hono backend server on port 3000
node --experimental-strip-types server.ts

# Start the Vite frontend server on port 5173
npx vite

alt text

Since no CSS is applied at all, the UI is as simple as it gets, but you can confirm that you can properly ask the LLM questions via chat and the response is displayed bit by bit through streaming.

In this demo, only basic chat functionality was implemented, but it demonstrates how the foundation of a chat UI can be built with minimal code using the AI SDK. To create a practical UI, additional implementation such as Markdown rendering is required.

Switching to LLMs running on the local machine (Hono + Ollama)

Up until now, we have been using GitHub Models, but let's try switching to an LLM running on your local machine (hereafter referred to as a local LLM). In the previous backend code, we were using @ai-sdk/openai, but we will change this to ollama-ai-provider.

AI SDK treats the part that calls the LLM as a separate package called a Provider. In addition to the well-known LLM services officially supported, there are also community-created providers. While there are various tools for running local LLMs, for this article, I will explain assuming the use of the easy-to-use Ollama.

First, start Ollama and download some model. For this example, I'll download gemma3, which was just released at the time of writing, using ollama pull gemma3. Next, modify the backend code slightly to use ollama-ai-provider instead of @ai-sdk/openai.

// server.ts
import { Hono } from 'hono';
import { serve } from '@hono/node-server'
import { cors } from 'hono/cors'
// import { createOpenAI } from '@ai-sdk/openai';
import { createOllama } from 'ollama-ai-provider';
import { generateText, streamText } from 'ai';

const app = new Hono();
// Since the client is running on the Vite server at localhost:5173, CORS must be allowed
app.use('/api/*', cors())

// Create an instance of the OpenAI model
// const model = createOpenAI({
//     baseURL: 'https://models.github.io/inference',
//     apiKey: process.env.GITHUB_TOKEN
// }).chat('openai/gpt-4o');

// Create an instance of the Ollama model
const model = createOllama({
    baseURL: 'http://localhost:11434/api'
}).chat('gemma3')

// Add the /api/chat endpoint
app.post('/api/chat', async (c) => {
    const { messages } = await c.req.json();
    const result = streamText({
        model,
        system: 'You are a helpful assistant.',
        messages,
    });
    return result.toDataStreamResponse();
});

const PORT = 3000;
serve({
  fetch: app.fetch,
  port: PORT
})

console.log(`Server running at http://localhost:${PORT}/`);

The only part that required modification was the createOpenAI section. As you can see, the AI SDK allows you to change the LLM just by switching the Provider package.

Now, if you start the backend and frontend servers as before, gemma3 running via Ollama should respond to the chat. Since the local LLM is running on your own PC, unlike GitHub Models which required communication with GitHub, it will work even in an offline environment with the network disconnected.

Using AI SDK in Chrome Extensions

Now, everything up to this point has been a prelude; this is where the main topic begins.

Having read this far, I'm sure you're eager to build some kind of application using the AI SDK and LLMs. Simply re-implementing a chat UI app is a bit dull, so wouldn't you want to create something that streamlines your daily workflow? For example, it would be interesting to quickly offload tasks that are subtly time-consuming in your daily work—like searching through internal documents or creating meeting minutes—to an LLM.

However, since most of the tools used in daily work are SaaS, you generally cannot integrate custom features into them. While internally developed systems might be extensible, whether you are permitted to pass business data to external LLM providers likely depends on the industry and the nature of the data[1].

Chrome extensions are the solution that can solve these two problems simultaneously. With a Chrome extension, you can externally extend the UI and APIs even for SaaS services. Furthermore, by running the LLM on your local machine, you can utilize LLM features without passing business data externally. Leveraging LLMs is easy with the AI SDK, and since it's JavaScript, it's a perfect match for Chrome extensions.

Constraints in Chrome Extensions

Now, let's actually create a Chrome extension. Deciding on the UI is a consideration, but for this example, we will simply use the sidebar in Chrome and reuse the frontend code using useChat to display a chat UI.

<!-- sidebar.html -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>AI Chat</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="sidebar.js"></script>
  </body>
</html> 
// sidebar.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { useChat } from '@ai-sdk/react'

const Sidebar = () => {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    // Try pointing to a local path instead of a backend
    api: '/api/chat',
  });

  return (
    <div className="sidebar">
      <h1>AI Chat</h1>
      <div className="chat-container">
        {messages.map(message => (
          <div key={message.id} className="message">
            <strong>{message.role === 'user' ? 'You: ' : 'AI: '}</strong>
            <div>{message.content}</div>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit} className="input-form">
        <input
          name="prompt"
          placeholder="Enter your question"
          value={input}
          onChange={handleInputChange}
          className="chat-input"
        />
        <button type="submit" className="submit-button">Send</button>
      </form>
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Sidebar />
  </React.StrictMode>
) 

When you build this code with Vite, package it as a Chrome extension, and run it, the chat request results in an error.
alt text

Because we changed the api in useChat() to a local path in an attempt to keep everything within the Chrome extension without setting up a backend server, the request is now being sent to the Chrome extension's URL (chrome-extension://...). However, since there is no code to handle that request, it seems to have resulted in an error.

useChat is designed with the assumption that it sends a request from the client (browser) to a server-side API endpoint and processes the response. Therefore, it cannot be used as-is in a Chrome extension where a server cannot be hosted.

Implementation via Fetch Interception by Service Worker

To solve this problem, I came up with a way to utilize Service Workers. Since Service Workers can be used in Chrome extensions, we can use them to implement a mechanism for intercepting fetch requests. Specifically, we monitor fetch events in the Service Worker and return the response of the AI SDK's streamText for requests to /api/chat coming from useChat. By doing this, it looks to useChat exactly as if a response is coming back from a backend server executing streamText, so it should work without issues.

// background.ts
import { createOllama } from 'ollama-ai-provider';
import { streamText } from 'ai';

// Create an instance of the Ollama model
const model = createOllama({
    baseURL: 'http://localhost:11434/api'
}).chat('gemma3');

// Set up the Service Worker event listener
// @ts-ignore
self.addEventListener('fetch', (event: FetchEvent) => {
  // Intercept requests from useChat
  if (event.request.url.endsWith('/api/chat')) {
    event.respondWith(handleChat(event.request));
  }
});

async function handleChat(request: Request) {
  try {
    const { messages } = await request.json();
    const result = streamText({
      model,
      system: 'You are a helpful assistant.',
      messages,
    });
    return result.toDataStreamResponse();
  } catch (error) {
    console.error('Chat error:', error);
    return new Response(JSON.stringify({ error: String(error) }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

Let's add this Service Worker to the previous Chrome extension code (which only had the sidebar) and run it.

alt text

Now the response from the LLM is coming back properly! Checking the network requests, we can confirm that the response is indeed being returned from background.js, the Service Worker.

In this way, while it requires a little bit of ingenuity, we were able to integrate LLM features into a Chrome extension in almost the same way as using the AI SDK normally. From here, by making full use of Chrome extension APIs to extend the UI of services or extracting text from the DOM for the LLM to process, you can do all sorts of things depending on your ideas.

Summary

In this article, I explained the basic usage of the Vercel AI SDK and how to utilize it in Chrome extensions. By using the AI SDK, you can develop AI applications relatively easily even with JavaScript. Furthermore, by implementing it as a Chrome extension, you can leverage LLM features without modifying internal systems, and since it can be developed independently, it is also useful for creating PoCs before actually adding LLM features to an internal system.

In the future, with the performance improvements of locally executable models (such as DeepSeek-R1 and gemma3) and the spread of laptops equipped with NPUs and large-capacity VRAM, it is expected that practical AI applications can be developed without relying on LLM services like OpenAI or Anthropic[2].

Appendix

I'm providing the entire sample code for the final Chrome extension here.

sidebar.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>AI Chat</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="sidebar.js"></script>
  </body>
</html> 

sidebar.tsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import { useChat } from '@ai-sdk/react'

const Sidebar = () => {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: '/api/chat',
  });

  return (
    <div className="sidebar">
      <h1>AI Chat</h1>
      <div className="chat-container">
        {messages.map(message => (
          <div key={message.id} className="message">
            <strong>{message.role === 'user' ? 'You: ' : 'AI: '}</strong>
            <div>{message.content}</div>
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit} className="input-form">
        <input
          name="prompt"
          placeholder="Enter your question"
          value={input}
          onChange={handleInputChange}
          className="chat-input"
        />
        <button type="submit" className="submit-button">Send</button>
      </form>
    </div>
  )
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Sidebar />
  </React.StrictMode>
) 

background.ts

import { createOllama } from 'ollama-ai-provider';
import { streamText } from 'ai';

// Create an instance of the Ollama model
const model = createOllama({
    baseURL: 'http://localhost:11434/api'
}).chat('gemma3');

// Set up the Service Worker event listener
// @ts-ignore
self.addEventListener('fetch', (event: FetchEvent) => {
  // Intercept requests from useChat
  if (event.request.url.endsWith('/api/chat')) {
    event.respondWith(handleChat(event.request));
  }
});

async function handleChat(request: Request) {
  try {
    const { messages } = await request.json();
    const result = streamText({
      model,
      system: 'You are a helpful assistant.',
      messages,
    });
    return result.toDataStreamResponse();
  } catch (error) {
    console.error('Chat error:', error);
    return new Response(JSON.stringify({ error: String(error) }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

manifest.json

{
  "manifest_version": 3,
  "name": "AI Chat Extension",
  "version": "1.0",
  "description": "You can chat with LLMs in a Chrome extension",
  "permissions": [
    "sidePanel"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "action": {
    "default_title": "AI Chat"
  },
  "side_panel": {
    "default_path": "sidebar.html"
  }
} 

vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { copyFileSync } from 'fs'

export default defineConfig({
  plugins: [
    react(),
    {
      name: 'copy-files',
      writeBundle() {
        copyFileSync(
          resolve(__dirname, 'src/manifest.json'),
          resolve(__dirname, 'dist/manifest.json')
        )
        copyFileSync(
          resolve(__dirname, 'src/sidebar.html'),
          resolve(__dirname, 'dist/sidebar.html')
        )
      }
    }
  ],
  build: {
    rollupOptions: {
      input: {
        sidebar: resolve(__dirname, 'src/sidebar.tsx'),
        background: resolve(__dirname, 'src/background.ts'),
      },
      output: {
        entryFileNames: '[name].js',
        chunkFileNames: 'vendor-[hash].js',
        assetFileNames: '[name].[ext]'
      }
    },
    outDir: 'dist',
    emptyOutDir: true
  }
}) 
脚注
  1. Many well-known LLMs offer plans that do not use data for training, but even so, there are fields where passing data externally is simply not allowed. ↩︎

  2. In fact, MacBooks with plenty of memory are becoming capable of running local LLMs of a certain scale. However, outside of engineers, Windows PCs remain the mainstream, and I expect the true era of widespread adoption will begin once Copilot+ PCs become common and local LLM execution tools like Ollama are included in Windows by default. ↩︎

Discussion

ryoppippiryoppippi

こんにちは!
service workerの知見とてもためになりました!ありがとうございます。

一点気になったことがあったので質問させていただきます!
Chromeに組み込まれているGemini Nanoは使ってみましたでしょうか?
こちらだと通信が必要ないためもしかしたら簡単かもしれません。

やはりモデルサイズが小さいため十分な精度が得られなかったでしょうか?
https://developer.chrome.com/docs/ai/built-in?hl=ja

Kesin11Kesin11

Gemini Nanoは存在は知っていましたが使ったことはなかったです。
というのもここ半年の間だけでもgemma3のようなオープンモデルは数ヶ月ごとにより賢いモデルが公開され続けているので、自分はそれらをずっと試していたからです。

この機会に試してみようと思ってやってみたのですが、flagsで必要なものをオンにしてもchrome://componentsの方でOptimization Guide On Device Modelという必要な設定がなぜか表示されなくて自分は試すことができませんでした・・・
おそらくこのChromeのGemini nano用と思われるAI SDKのproviderもコミュニティで作成されているようなので、将来Stable版に降りてきて誰でも使えるようになったらまた面白いことになるかもしれないですね。
https://sdk.vercel.ai/providers/community-providers/chrome-ai

1