こんにちは、私は HolySheep AI の開発チームに所属しているエンジニアです。本日は、Electron を使ってゼロからデスクトップ AI 助手アプリケーションを作る方法を、ステップバイステップで解説します。この記事は、プログラミング初心者が最短距離で AI アプリケーションを作成できることを目標にしています。

1. Electron とは?なぜ Electron なのか

Electron は、ウェブ技術(HTML、CSS、JavaScript)を使ってデスクトップアプリケーションを作れるフレームワークです。Electron を使えば、同じコードで Windows、macOS、Linux 対応のアプリを一括開発できます。

本記事では、Electron と HolySheep AI API を組み合わせて、リアルタイムで AI と会話できる помощник(アシスタント)アプリケーションを作成します。HolySheep AI を選定した理由は、レートが ¥1=$1(他社比85%節約)で、WeChat Pay や Alipay に対応しており、レイテンシが <50ms と高速だからです。さらに、今すぐ登録 で無料クレジットが付与されるため、コストリスクなしで開発を始められます。

2. 開発環境の準備

必要なツール

スクリーンショットヒント: Node.js のインストール後、ターミナル(Windows は PowerShell、Mac は Terminal)で node --version と打ち込んでバージョン番号が表示されれば正常にインストールされています。

3. プロジェクトの作成

まず、プロジェクト用のフォルダを作成し、初期化します。以下のコマンドをターミナルで実行してください。

# プロジェクトフォルダの作成と移動
mkdir ai-assistant
cd ai-assistant

package.json の生成(すべて Enter でデフォルト設定即可)

npm init -y

Electron のインストール(開発用)

npm install --save-dev electron

необходимые dependencies のインストール

npm install electron-log

4. メインプロセスの作成(main.js)

Electron アプリケーションの核となるファイルを生成します。main.js はウィンドウ管理やシステム連携を担当します。

// main.js — Electron メインプロセス
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const log = require('electron-log');

// HolySheep AI API 設定
const HOLYSHEEP_API_KEY = 'YOUR_HOLYSHEEP_API_KEY';
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 900,
    height: 700,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');
  mainWindow.setMenuBarVisibility(false);
  
  log.info('AI Assistant ウィンドウを生成しました');
}

// AI API との通信処理
async function callHolySheepAPI(messages) {
  const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': Bearer ${HOLYSHEEP_API_KEY}
    },
    body: JSON.stringify({
      model: 'gpt-4.1',
      messages: messages,
      max_tokens: 1000
    })
  });

  if (!response.ok) {
    throw new Error(APIエラー: ${response.status});
  }

  return await response.json();
}

// IPC 通信のセットアップ
app.whenReady().then(() => {
  createWindow();

  ipcMain.handle('send-message', async (event, userMessage, conversationHistory) => {
    try {
      log.info('HolySheep AI にリクエスト送信中...');
      const data = await callHolySheepAPI(conversationHistory);
      log.info('レスポンス受信完了');
      return { success: true, data: data };
    } catch (error) {
      log.error('API呼び出しエラー:', error.message);
      return { success: false, error: error.message };
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

5. コンテキスト隔離用の preload.js

セキュリティを確保するため、renderer プロセスと main プロセスを分離する preload.js を作成します。

// preload.js — セキュアなIPC通信
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  sendMessage: (userMessage, conversationHistory) => {
    return ipcRenderer.invoke('send-message', userMessage, conversationHistory);
  }
});

6. UI 部分の作成(index.html)

メイン画面となる index.html を作成します。モダンでクリーンなチャット UI を実装します。

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HolySheep AI Assistant</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      color: #fff;
      height: 100vh;
      display: flex;
      flex-direction: column;
    }
    
    .header {
      background: rgba(255,255,255,0.1);
      padding: 15px 20px;
      text-align: center;
      border-bottom: 1px solid rgba(255,255,255,0.1);
    }
    
    .header h1 {
      font-size: 1.4rem;
      background: linear-gradient(90deg, #f093fb, #f5576c);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    
    .chat-container {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
    
    .message {
      max-width: 75%;
      padding: 12px 16px;
      border-radius: 15px;
      line-height: 1.5;
      animation: fadeIn 0.3s ease;
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }
    
    .user-message {
      align-self: flex-end;
      background: #4a90e2;
      border-bottom-right-radius: 5px;
    }
    
    .ai-message {
      align-self: flex-start;
      background: rgba(255,255,255,0.15);
      border-bottom-left-radius: 5px;
    }
    
    .input-area {
      padding: 15px 20px;
      background: rgba(255,255,255,0.05);
      display: flex;
      gap: 10px;
    }
    
    .input-area input {
      flex: 1;
      padding: 12px 16px;
      border: none;
      border-radius: 25px;
      background: rgba(255,255,255,0.1);
      color: #fff;
      font-size: 1rem;
      outline: none;
    }
    
    .input-area input::placeholder {
      color: rgba(255,255,255,0.5);
    }
    
    .input-area button {
      padding: 12px 24px;
      border: none;
      border-radius: 25px;
      background: linear-gradient(90deg, #f093fb, #f5576c);
      color: #fff;
      font-weight: bold;
      cursor: pointer;
      transition: transform 0.2s;
    }
    
    .input-area button:hover {
      transform: scale(1.05);
    }
    
    .input-area button:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
    
    .typing-indicator {
      display: flex;
      gap: 5px;
      padding: 15px;
    }
    
    .typing-dot {
      width: 8px;
      height: 8px;
      background: rgba(255,255,255,0.5);
      border-radius: 50%;
      animation: typing 1.4s infinite;
    }
    
    @keyframes typing {
      0%, 60%, 100% { transform: translateY(0); }
      30% { transform: translateY(-10px); }
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>🐑 HolySheep AI Assistant</h1>
  </div>
  
  <div class="chat-container" id="chatContainer">
    <div class="message ai-message">
      こんにちは!HolySheep AI です。何かお手伝いできることはありますか?<br>
      <small style="opacity:0.6">Powered by HolySheep AI — ¥1=$1 でお得に活用中</small>
    </div>
  </div>
  
  <div class="input-area">
    <input type="text" id="messageInput" placeholder="メッセージを入力してください..." onkeypress="handleKeyPress(event)">
    <button id="sendButton" onclick="sendMessage()">送信</button>
  </div>

  <script>
    let conversationHistory = [
      { role: 'system', content: 'あなたは親切で有用的なAIアシスタントです。' }
    ];

    async function sendMessage() {
      const input = document.getElementById('messageInput');
      const button = document.getElementById('sendButton');
      const message = input.value.trim();
      
      if (!message) return;

      // ユーザー消息を追加
      addMessage(message, 'user');
      conversationHistory.push({ role: 'user', content: message });
      input.value = '';
      button.disabled = true;

      // ローディング表示
      const typingDiv = document.createElement('div');
      typingDiv.className = 'message ai-message typing-indicator';
      typingDiv.innerHTML = '<div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div>';
      document.getElementById('chatContainer').appendChild(typingDiv);
      scrollToBottom();

      try {
        const result = await window.electronAPI.sendMessage(message, conversationHistory);
        typingDiv.remove();

        if (result.success) {
          const aiResponse = result.data.choices[0].message.content;
          addMessage(aiResponse, 'ai');
          conversationHistory.push({ role: 'assistant', content: aiResponse });
        } else {
          addMessage('エラー: ' + result.error, 'ai');
        }
      } catch (error) {
        typingDiv.remove();
        addMessage('通信エラー: ' + error.message, 'ai');
      }

      button.disabled = false;
      input.focus();
    }

    function addMessage(text, type) {
      const div = document.createElement('div');
      div.className = 'message ' + (type === 'user' ? 'user-message' : 'ai-message');
      div.innerHTML = text.replace(/\n/g, '<br>');
      document.getElementById('chatContainer').appendChild(div);
      scrollToBottom();
    }

    function scrollToBottom() {
      const container = document.getElementById('chatContainer');
      container.scrollTop = container.scrollHeight;
    }

    function handleKeyPress(event) {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
      }
    }
  </script>
</body>
</html>

7. パッケージ.jsonの確認と修正

生成された package.json を開き、scripts セクションを以下のように修正します。

{
  "name": "ai-assistant",
  "version": "1.0.0",
  "description": "HolySheep AI Powered Desktop Assistant",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "build": "electron-builder",
    "build:win": "electron-builder --win",
    "build:mac": "electron-builder --mac"
  },
  "build": {
    "appId": "com.holysheep.ai-assistant",
    "productName": "HolySheep AI Assistant",
    "directories": {
      "output": "dist"
    },
    "win": {
      "target": "nsis"
    },
    "mac": {
      "target": "dmg"
    },
    "linux": {
      "target": "AppImage"
    }
  }
}

8. アプリケーションの起動テスト

以下のコマンドでアプリケーションを起動します。

npm start

ウィンドウが表示され、メッセージを入力して送信すれば、AI からの返答が得られます。HolySheep AI の api.openai.com 互換エンドポイントを活用しているため、OpenAI SDK でも利用可能です。

💡 スクリーンショットヒント: 初回起動時に黒いコンソールウィンドウとメインウィンドウの2つが表示されます。コンソールウィンドウには electron-log によるログが出力され、デバッグに便利です。

9. ビルドとパッケージング

開発テストが完了したら、 distributable ファイル(.exe や .app)を作成します。

# Windows 用のビルド
npm install --save-dev electron-builder
npm run build:win

macOS 用のビルド

npm run build:mac

Linux 用のビルド

npm run build

ビルドが成功すると、dist/ フォルダに変換済みファイルが生成されます。

10. コスト最適化のためのモデル選択

HolySheep AI では用途に応じて最適なモデルを選べます。以下は出力単価の比較表です(2026年最新)。

モデル出力価格 ($/MTok)用途
DeepSeek V3.2$0.42費用重視の長文生成
Gemini 2.5 Flash$2.50高速応答が求められる場合
GPT-4.1$8汎用的な高品質応答
Claude Sonnet 4.5$15複雑な推論や分析

私は日常的な質問応答には Gemini 2.5 Flash を推奨しています。レイテンシが <50ms と高速で、コストも DeepSeek 以外に 비해安価です。コード生成など高品質したい場合は GPT-4.1 を選ぶと良いでしょう。

よくあるエラーと対処法

エラー1: API Key が無効

Error: APIエラー: 401

原因: API キーが未設定または無効

解決策: HolySheep AI のダッシュボードで API キーを再生成し、

main.js の HOLYSHEEP_API_KEY を新しいキーに置き換える

エラー2: CORS エラー

Error: Failed to fetch

原因: 直接ブラウザから API を呼び出そうとしている

解決策: Electron では IPC 通信を通じて main.js から API を呼び出す必要がある。

preload.js と ipcMain.handle の設定を確認する

エラー3: Cannot find module 'electron'

Error: Cannot find module 'electron'

原因: npm install が実行されていない

解決策: プロジェクトフォルダで以下を実行

npm install npm install --save-dev electron

エラー4: Rate Limit Exceeded

Error: APIエラー: 429

原因: リクエスト頻度が上限を超えている

解決策: リクエスト間に setTimeout でディレイを追加する。

HolySheep AI の場合はレート制限が寛容だが、1秒待つ程度で回避可能

エラー5: ビルド時のアセットが見つからない

Error: Unable to find electron app

原因: package.json の main フィールドが main.js を指していない

解決策: package.json の "main": "main.js" を確認

まとめ

本記事では、Electron を使って HolySheep AI API を組み込んだデスクトップ AI 助手アプリケーションを作成しました。ポイントをおさらいします:

開発したアプリケーションは、npm run build:win で Windows 実行ファイルとして配布可能です。

次はメッセージ履歴の保存機能、画像認識対応、通知システムなどの拡張機能を試してみてください。HolySheep AI の低コスト・低レイテンシ環境を活かした、より高度なアプリケーション開発に挑戦しましょう!

👉 HolySheep AI に登録して無料クレジットを獲得