0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ローカルLLM × FastAPI × Dify:クラウド不要の日本語チャット環境構築

Last updated at Posted at 2025-06-22

1. はじめに(目的)

  • API利用コストを抑えたローカル実行環境を構築したい
  • 機密性の高いデータを扱えるよう、ローカル環境で処理を完結させたい

2. 構成概要(システム全体)

構成要素 内容
言語モデル オープンソースの日本語対応LLM
APIサーバー Python製FastAPIをローカルで構築・常駐化
フロントエンド Dify(自己ホスト環境/Docker Compose利用)

3. 実装と構築方法

3.1 モデルとAPIの構築

使用モデル:


cyberagent/open-calm-small

このモデルをローカルに読み込み、FastAPIでAPIエンドポイントを提供しています。

FastAPI 実装例(抜粋):

from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

app = FastAPI()
tokenizer = AutoTokenizer.from_pretrained("cyberagent/open-calm-small", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("cyberagent/open-calm-small", trust_remote_code=True)
model = model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))

@app.post("/v1/chat/completions")
async def chat_completion(request: Request):
    data = await request.json()
    user_message = data["messages"][-1]["content"]
    input_ids = tokenizer.encode(user_message, return_tensors="pt").to(model.device)
    output_ids = model.generate(input_ids, max_new_tokens=100, do_sample=True, top_p=0.95, temperature=0.7)
    result = tokenizer.decode(output_ids[0], skip_special_tokens=True)[len(user_message):].strip()
    return {
        "id": "chatcmpl-opencalm",
        "object": "chat.completion",
        "choices": [{"message": {"role": "assistant", "content": result}}],
        "model": "cyberagent/open-calm-small"
    }

3.2 Dify(セルフホスト構成)

  • Difyは公式のDocker Compose構成を利用して、自己ホスト型で構築しています。
  • Difyからは、HTTPリクエストノードを用いてFastAPIエンドポイントに接続し、プロンプトを送信して応答を取得しています。
  • OpenAI互換のレスポンス形式で構成しているため、GUI上でスムーズに動作させることができます。

4. 実行結果と観察

✅ 動作確認

  • DifyのUIからプロンプトを送信し、ローカルLLMから応答を取得できました。
  • 応答形式はOpenAI互換であるため、追加の実装を行うことなく連携できました。

✅ 処理性能と品質

  • 応答速度は、CPU環境でおおよそ数秒〜十数秒でした。
  • 応答の文構造は成立していますが、期待した内容には届いていない場面も確認されました。

今回使用したモデルは小型で扱いやすい反面、応答の一貫性や知識の網羅性には課題が見られました。
今後、上位のLLMモデルやそれに適したハードウェアを利用することで、速度と品質の向上が期待できる可能性があります。

実行環境(検証マシン)

項目 内容
OS Windows 10(64bit)
CPU Intel Core i5(第6世代相当)
メモリ 16GB
GPU NVIDIA GTX 1050(2GB)

5. おわりに

本検証により、ローカル環境のみで構成された日本語LLMチャット基盤を構築できることを確認しました。
また、DifyのGUIを活用することで、非エンジニアでも対話形式の操作が可能となり、利便性が高まることも分かりました。

応答品質には課題が残るものの、構成としての再現性や導入のしやすさは十分に確認できました。
さらに、利用可能範囲をプライベートネットワーク内にすることで企業内での活用にも応用可能と考えます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?