FastAPI × LangChain × MongoDB の使い方

Dev.to / 2026/4/17

💬 オピニオンDeveloper Stack & InfrastructureTools & Practical UsageModels & Research

要点

  • このチュートリアルでは、FastAPI・LangChain・MongoDBを統合した動作するアプリの完全なサンプルを、コピペでそのまま実行できる形で提供しています。
  • 既存の類似サービスを提供する企業の調査と、パーソナライズされた提案(推薦)を組み合わせることで、新しいアイデアを生み出す提案アプリを想定しています。
  • FastAPIは最小限のコードでバックエンドのREST API層を素早く構築でき、AIやマイクロサービスのような現代的な用途に適しています。
  • MongoDBは柔軟でドキュメント指向のデータベースとして機能し、アプリの情報を保存することでスケーラブルかつデータ構造の変化に強い設計を可能にします。
  • LangChainは、LLMを中心に「ツール連携・メモリ・外部データ・段階的推論」を組み合わせてAI機能を構築するために用いられます。

この記事はCarlos Barbozaによって書かれました。

このチュートリアルへようこそ! このデモでは、FastAPI、LangChain、MongoDBを統合する完全に動作する例を紹介します。ぜひすべてのテクノロジー愛好家の皆さんに共有したいと思っています。

本ガイドの価値は、実際に動くサンプルを提供している点です。コードをそのままコピー&ペーストすれば、追加の設定なしでスムーズに動作します。さらに、これらの強力なツールを使って構築できるアプリケーションの種類について、分かりやすく実用的な全体像も掴めるようになります。

私は、世界中のお客様が新しいアイデアを生み出すのを支援することを目的とした提案(サジェスト)アプリケーションを開発しています。具体的には、個別に最適化されたおすすめの提示と、同様のサービスを提供している既存企業の有無の確認を行います。

必要条件

  • Python、virtualenvの基礎
  • REST APIの基本的な理解
  • MongoDBの基礎(コレクション、ドキュメント)
  • アカウント/キー
    • MongoDB Atlas またはローカルのMongoDB
    • LLMプロバイダーのAPIキー

プロジェクトのアーキテクチャ


FastAPIは、少ないコードで、素早く効率的にAPIを構築するためのPythonフレームワークです。

名前のとおり高速で、使いやすく、AI、マイクロサービス、バックエンドAPIのような現代的なアプリケーションに最適だと言われています。この例では、バックエンド側のAPIクエリを処理します。

MongoDBは、SQLのような堅いテーブルではなく、柔軟なJSONライクなドキュメントとしてデータを保存するNoSQLのドキュメントベースのデータベースです。これにより、開発が速く、スケールしやすく、データ構造の変化にも強いのが特長です。今回のケースでは、必要な情報をすべてここに保存します。

LangChainは、LLM(GPT、LLaMA、Ollama、Mistralなど)によって駆動されるアプリケーションを構築するためのフレームワークで、モデルをツール、メモリ、外部データ、そして複数ステップの推論とつなぐことを可能にします。AIモデルを利用するために必要なツールをPythonで提供します。

プロジェクトのセットアップ

MongoDB Atlas

このガイド用のMongoDBインスタンスを最も簡単に用意する方法は、公式サイトで登録することです。これにより、M0インスタンスが提供されます。これは、このガイドを実行するのに十分な内容です。

Docker

Dockerをインストールしていない場合は、公式のリンクに、OSに基づいたインストール手順が掲載されています。

docker-composeファイルは、MongoDBコンテナをセットアップするように設定されています。このコンテナは公式のバージョン7.0を使用し、名前はmongodb、認証情報としてユーザー名にはroot、パスワードにはexampleを使用します。さらに、コンテナの再読み込み後もデータが保持されるように、ボリュームが定義されています。

version: "3.3"
services:
  mongo:
    image: mongo:7.0
    container_name: mongodb
    restart: unless-stopped
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      # 永続化するための名前付きボリューム
      - mongo_data:/data/db

volumes:
  mongo_data:

次のコマンドを実行してDockerを起動します。

docker compose up -d

最後に、接続文字列を使ってMongoDBインスタンスへ接続できます。あなたの環境ではmongodb://root:example@localhost:27017です。

LLMs

大規模言語モデル(LLM)は、大量のテキストで学習されたAIモデルであり、言語を理解し、テキストを生成し、コードを書き、質問に答え、人間のように会話をすることができます。

LLMは考えるのではなく、学習したパターンに基づいて次の単語を賢く予測します。今回のケースでは、ローカルマシンで例を実行できるようにOllamaを使用します。
別のLLMとしてOpenAIを選ぶこともできますが、その場合は追加の費用がかかる可能性があります。

Ollamaのインストール

お使いのOSに応じて、公式の手順に従う必要があります。最終的には、ターミナルでOllamaのコマンドを実行できるはずです。

ollama list # ターミナルで利用可能なすべてのモデルを表示します
ollama pull llama3.2 # llama3.2モデルをダウンロードします

開発

Requirements.txt

プロジェクトに必要なライブラリはすべてこちらです。

aiohappyeyeballs==2.6.1
aiohttp==3.13.2
aiosignal==1.4.0
annotated-doc==0.0.4
annotated-types==0.7.0
anyio==4.12.0
attrs==25.4.0
bcrypt==3.2.2
certifi==2025.11.12
cffi==2.0.0
charset-normalizer==3.4.4
click==8.3.1
colorama==0.4.6
cryptography==46.0.3
dataclasses-json==0.6.7
distro==1.9.0
dnspython==2.8.0
ecdsa==0.19.1
email-validator==2.3.0
fastapi==0.123.0
frozenlist==1.8.0
greenlet==3.2.4
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
httpx-sse==0.4.3
idna==3.11
jiter==0.12.0
jsonpatch==1.33
jsonpointer==3.0.0
langchain==1.1.0
langchain-classic==1.0.0
langchain-community==0.4.1
langchain-core==1.1.0
langchain-openai==1.1.0
langchain-text-splitters==1.0.0
langgraph==1.0.4
langgraph-checkpoint==3.0.1
langgraph-prebuilt==1.0.5
langgraph-sdk==0.2.10
langsmith==0.4.49
marshmallow==3.26.1
motor==3.7.1
multidict==6.7.0
mypy_extensions==1.1.0
numpy==2.3.5
openai==2.8.1
orjson==3.11.4
ormsgpack==1.12.0
packaging==25.0
passlib==1.7.4
propcache==0.4.1
pyasn1==0.6.1
pycparser==2.23
pydantic==2.12.5
pydantic-settings==2.12.0
pydantic_core==2.41.5
pymongo==4.15.4
python-dotenv==1.2.1
python-jose==3.5.0
python-multipart==0.0.20
PyYAML==6.0.3
regex==2025.11.3
requests==2.32.5
requests-toolbelt==1.0.0
rsa==4.9.1
six==1.17.0
sniffio==1.3.1
SQLAlchemy==2.0.44
starlette==0.50.0
tenacity==9.1.2
tiktoken==0.12.0
tqdm==4.67.1
typing-inspect==0.9.0
typing-inspection==0.4.2
typing_extensions==4.15.0
urllib3==2.5.0
uvicorn==0.38.0
xxhash==3.6.0
yarl==1.22.0
zstandard==0.25.0

環境ファイル

MongoDB URI、JWT Secret Key、その他の設定などの機密情報を含む .env ファイルを用意しておくことを推奨します。このファイルは git.ignore から除外する必要があり、メインの場所に設定してください。

MONGO_URI=mongodb+srv://admin:admin@atlascluster.f3spasq.mongodb.net/
MONGO_DB_NAME=fastapi_demo
JWT_SECRET_KEY=super-secret-key
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60
OLLAMA_HOST=http://host.docker.internal:11434 # fastAPI を docker と一緒に動かしている場合のみ

.gitignore

# ---------------------
# 環境変数
# ---------------------
.env
.env.local
.env.*.local

# ---------------------
# Python
# ---------------------
__pycache__/
*.pyc
*.pyo
*.pyd
*.pdb
*.pkl
*.db

# 仮想環境
venv/
.venv/

# バイトコンパイル済み
*.py[cod]
*$py.class

# ---------------------
# FastAPI / Uvicorn ログ
# ---------------------
*.log

# ---------------------
# IDE & エディタのファイル
# ---------------------
.vscode/
.idea/
*.swp

# ---------------------
# OS ファイル
# ---------------------
.DS_Store
Thumbs.db

# ---------------------
# Docker
# ---------------------
/data/
docker-data/
*.pid

# ---------------------
# 任意のキャッシュフォルダ
# ---------------------
cache/
logs/

スキーマフォルダ

chat.py
from pydantic import BaseModel

class ChatRequest(BaseModel):
    question: str

class ChatResponse(BaseModel):
    answer: str
    used_context: bool
item.py
from pydantic import BaseModel

class Item(BaseModel):
    id: str
    name: str
    price: float
user.py
from pydantic import BaseModel, EmailStr

class UserCreate(BaseModel):
    email: EmailStr
    password: str

class UserPublic(BaseModel):
    id: str
    email: EmailStr

class Token(BaseModel):
    access_token: str
    token_type: str = "bearer"

class UserInDB(BaseModel):
    id: str
    email: EmailStr
    hashed_password: str
notes.py
from pydantic import BaseModel

class NotesCreate(BaseModel):
    text: str

class NotesInDB(BaseModel):
    id: str
    user_id: str
    text: str

コアフォルダ

config.py
import os

返却形式: {"translated": "翻訳されたHTML"}MONGO_URI = os.getenv("MONGO_URI", "mongodb+srv://admin:admin@atlascluster.f3spasq.mongodb.net/")
MONGO_DB_NAME = os.getenv("MONGO_DB_NAME", "fastapi_demo")

JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "change-me")
JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
llm.py
import os
from langchain_community.chat_models import ChatOllama

OLLAMA_HOST = os.getenv("OLLAMA_HOST", "http://localhost:11434")

llm = ChatOllama(
    model="llama3.2"
    ,base_url=OLLAMA_HOST,
)
security.py
from datetime import datetime, timedelta, timezone
from typing import Optional

from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from passlib.context import CryptContext

from app.core.config import JWT_SECRET_KEY, JWT_ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")

def hash_password(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def create_access_token(
    data: dict,
    expires_delta: Optional[timedelta] = None,
) -> str:
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (
        expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    )
    to_encode.update({"exp": expire})
    encoded_jwt

返却形式: {"translated": "翻訳されたHTML"}= jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)
    return encoded_jwt

dbフォルダ

from motor.motor_asyncio import AsyncIOMotorClient
from app.core import config as core_config

client = AsyncIOMotorClient(core_config.MONGO_URI)
db = client[core_config.MONGO_DB_NAME]

users_collection = db["users"]
notes_collection = db["notes"]
items_collection = db["items"]

depsフォルダ

auth.py
from typing import Optional, Annotated

from fastapi import Depends, HTTPException, status
from jose import JWTError, jwt

from app.core.config import JWT_SECRET_KEY, JWT_ALGORITHM
from app.core.security import oauth2_scheme, hash_password, verify_password
from app.db.mongo import users_collection
from app.schemas.user import UserInDB, UserCreate

async def get_user_by_email(email: str) -> Optional[UserInDB]:
    doc = await users_collection.find_one({"email": email})
    if not doc:
        return None
    return UserInDB(
        id=str(doc["_id"]),
        email=doc["email"],
        hashed_password=doc["hashed_password"],
    )

async def create_user(user: UserCreate) -> UserInDB:
    existing = await get_user_by_email(user.email)
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email already registered",
        )
    hashed = hash_password(user.password)
    res = await users_collection.insert_one(
        {"email": user.email, "hashed_password": hashed}
    )
    return UserInDB(id=str(res.inserted_id), email=user.email, hashed_password=hashed)

返却形式: {"translated": "翻訳されたHTML"}async def get_current_user(
    token: Annotated[str, Depends(oauth2_scheme)]
) -> UserInDB:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
        email: str = payload.get("sub")
        if email is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception

    user = await get_user_by_email(email)
    if user is None:
        raise credentials_exception
    return user

ルーターフォルダ

auth.py
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

from app.core.security import create_access_token, verify_password
from app.deps.auth import create_user, get_user_by_email, get_current_user
from app.schemas.user import UserCreate, UserPublic, Token, UserInDB

router = APIRouter(prefix="/auth", tags=["auth"])

@router.post("/register", response_model=UserPublic)
async def register(user: UserCreate):
    new_user = await create_user(user)
    return UserPublic(id=new_user.id, email=new_user.email)

@router.post("/login", response_model=Token)
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    # I am using email as the username field in the OAuth2 form.
    user = await get_user_by_email(form_data.username)
    if not user or not verify_password(form_data.password, user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
        )
    access_token = create_access_token(data={"sub": user.email})
    return Token(access_token=access_token)

@router.get("/me", response_model=UserPublic)
async def get_me(
    current_user: Annotated[UserInDB, Depends(get_current_user)]
):
    return UserPublic(id=current_user.id, email=current_user.email)
chat.py
from typing import Annotated

from fastapi import APIRouter, Depends
from langchain_core.messages import HumanMessage, SystemMessage

from app.core.llm import llm
from app.db.mongo import notes_collection
from app.deps.auth import get_current_user
from app.schemas.user import UserInDB
from app.schemas.chat import ChatRequest, ChatResponse

router = APIRouter(prefix="/chat", tags=["chat"])

@router.post("/", response_model=ChatResponse)
async def chat_with_ai(
    body: ChatRequest,
    current_user: Annotated[UserInDB, Depends(get_current_user)],
    # LangChain + OpenAI を使用し、MongoDB からいくらかのコンテキストを取り込みます。
):
    print(current_user)

    notes_cursor = (
        notes_collection.find({"user_id": current_user.id})
        .sort("_id", -1)
        .limit(3)
    )
    notes = await notes_cursor.to_list(length=3)

    context_text = "
".join(
        note.get("text", "") for note in notes if note.get("text")
    )
    used_context = bool(context_text)
system_prompt = (
        "あなたは、ユーザーがメモを作成するのを手助けするアシスタントです。"
        " "
        " "
        "関連する場合は、次のコンテキストを使用してください。そうでない場合は、通常どおりに回答してください。

"
        f"コンテキスト:
{context_text or '((コンテキストは利用できません))'}"
    )
    messages = [
        SystemMessage(content=system_prompt),
        HumanMessage(content=body.question),
    ]

    response = await llm.ainvoke(messages)

    return ChatResponse(answer=response.content, used_context=used_context)
items.py
from typing import List, Annotated

from fastapi import APIRouter, Depends

from app.db.mongo import items_collection
from app.schemas.item import Item
from app.schemas.user import UserInDB
from app.deps.auth import get_current_user

router = APIRouter(prefix="/items", tags=["items"])

@router.get("/", response_model=List[Item])
async def list_items(
    current_user: Annotated[UserInDB, Depends(get_current_user)]
):
    # Motor を使った非同期 Mongo クエリの例。
    # デモ: コレクションが空の場合は items をシードする
    count = await items_collection.count_documents({})
    if count == 0:
        await items_collection.insert_many(
            [
                {"name": "Book", "price": 10.5},
                {"name": "Laptop", "price": 999.99},
            ]
        )

    docs = await items_collection.find().to_list(length=100)
    return [
        Item(id=str(doc["_id"]), name=doc["name"], price=float(doc["price"]))
        for doc in docs
    ]
notes.py
from typing import Annotated

from fastapi import APIRouter, Depends
from langchain_core.messages import HumanMessage, SystemMessage

返却形式: {"translated": "翻訳されたHTML"}from app.core.llm import llm
from app.db.mongo import notes_collection
from app.deps.auth import get_current_user
from app.schemas.user import UserInDB
from app.schemas.chat import ChatRequest, ChatResponse
from app.schemas.notes import NotesCreate, NotesInDB

router = APIRouter(prefix="/notes", tags=["notes"])

@router.post("/", response_model=NotesInDB)
async def create_note(body: NotesCreate,current_user: Annotated[UserInDB, Depends(get_current_user)]):
    print(current_user)

    note = await notes_collection.insert_one({"text": body.text, "user_id": current_user.id})
    return NotesInDB(id=str(note.inserted_id), text=body.text, user_id=current_user.id)

Main.py

from fastapi import FastAPI

from app.routers import auth, items, chat, notes

app = FastAPI(title="FastAPI + MongoDB + JWT + LangChain Example")

@app.get("/")
async def root():
    return {"message": "FastAPI + MongoDB + JWT + LangChain example"}

# ルーターを含める
app.include_router(auth.router)
app.include_router(items.router)
app.include_router(chat.router)
app.include_router(notes.router)

Application execution

メインフォルダで、次のコマンドを実行できます:

uvicorn app.main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

http://127.0.0.1:8000/docs# にアクセスすると、デフォルトで作成された Swagger ドキュメントを確認できます。

Users creation

新しいユーザーを作成するには、次のコマンドを実行できます:

curl -X 'POST' \
  'http://127.0.0.1:8000/auth/register' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "email": "user@example.com",
  "password": "string" 
}'

または、vscode の Rest Api Extension がある場合は、次を実行できます。
POST http://127.0.0.1:8000/auth/register
Accept: application/json
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "string"
}

上記のコマンドは、ハッシュ化されたパスワードで新しいユーザーを作成します:

返却形式: {"translated": "翻訳されたHTML"}

ユーザー認証

ユーザーを認証し、ベアラートークンを取得するには、以下のコマンドを実行してください。

curl -X 'POST' \
  'http://127.0.0.1:8000/auth/login' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=password&username=user%40example.com&password=string&scope=&client_id=string&client_secret=string'
Rest API extension
POST http://127.0.0.1:8000/auth/login
Content-Type: application/x-www-form-urlencoded
accept: application/json

grant_type=password&username=test@example.com&password=123&scope=&client_id=string&client_secret=string

認証が成功すると、次の出力が返されます。トークンは、残りのルートで認証するために重要です。

HTTP/1.1 200 OK
date: Tue, 02 Dec 2025 17:40:11 GMT
server: uvicorn
content-length: 180
content-type: application/json
Connection: close

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0QGV4YW1wbGUuY29tIiwiZXhwIjoxNzY0NzAwODExfQ.riXj1vvLZSyzyU4T7kG3ygYaUU8sgvgCjK_Os_uggvo",
  "token_type": "bearer"
}

アイデア作成

このアプリケーションの主な目的は、エンドユーザーが持っているアイデアに基づいて提案を行うことです。以下のリクエストが、それらのノートを作成します。

POST http://127.0.0.1:8000/notes/
Content-Type: application/json
Authorization: Bearer {{token}}

{
  "text": "testing123"
}

チャットのやり取り

このアプリケーションは現在、データベースに保存されたユーザーのノートに基づいて助言を提供します。LLMとのやり取りを有効にするために、chat.pyファイルでチャットの挙動を定義します。これはプロンプトエンジニアリングの一例であり、必要であればここでプロンプトの言語や内容を変更できます。

system_prompt = (
        "あなたは、ユーザーのノートを手助けするアシスタントです。"
        " "
        "関連する場合は、次のコンテキストを使用してください。そうでない場合は、通常どおりに答えてください。

"
        f"Context:
{context_text or '(コンテキストは利用できません)'}"
    )

実行例:

POST http://127.0.0.1:8000/chat/
Content-Type: application/json
Authorization: Bearer {{token}}

{
  "question": "What i need to do"
}

実行結果:

{
  "answer": "目標である、より多くのお金を貯めてプロジェクトを完了するために役立つよう、実行可能なステップをいくつか紹介します:

**より多くのお金を貯める方法:**

1. **支出を記録する**:お金の行き先を理解するために、たとえ小さくても、すべての取引を1〜2週間書き出します。
2. **予算を作る**:収入と支出に基づいて、毎月の貯蓄用に一定額を割り当てます。
3. **貯蓄を自動化する**:当座預金(チェック口座)から貯蓄口座へ、自動振替を設定します。
4. **不要な出費を減らす**:外食やサブスクリプションなど、削減できそうな支出の領域を特定します。
5. **貯蓄チャレンジを検討する**: "52週間貯蓄チャレンジ"のように、週の番号に応じた金額を貯める方法を試します(例:第1週:$1を貯める、第2週:$2を貯める…など)。

**プロジェクトを完了する方法:**

1. **プロジェクトを小さなタスクに分解する**:プロジェクトを扱いやすい作業に分けることで、圧倒される感覚を減らします。
2. **スケジュールを作る**:各タスクに具体的な締め切りを設定し、それを守ります。
3. **タスクに優先順位を付ける**:まず最も重要なタスクに集中し、その後重要度の低いものへ進みます。
4. **気を散らすものを取り除く**:潜在的な気が散る要因(例:SNS、メール、電話の通知)を特定し、作業中は排除します。
5. **定期的に休憩を取る**:短い休憩を挟んで回復し、生産性を維持します。

これらのステップのうち、どれから始めたいですか?,
"used_context": true
}

Docker(任意)

私たちのアプリケーションは現在動作しています。ただし、別の環境で実行するには、必要な依存関係をインストールする必要があります。Dockerは、このデプロイ手順を容易にし、効率化することができます。

Dockerfileを作成し、以下のコードを貼り付けます:

# Dockerfile
FROM python:3.11-slim

# コンテナ内の作業ディレクトリを設定
WORKDIR /app

# システム依存関係をインストール(任意だが、多くのライブラリで役立つ)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# 最初にrequirementsだけコピー(Dockerのキャッシュ効率を高めるため)
COPY requirements.txt .

# Python依存関係をインストール
RUN pip install --no-cache-dir -r requirements.txt

# プロジェクトの残りをコピー
COPY . .

# FastAPIのポートを公開
EXPOSE 8000

# デフォルトコマンド:uvicornを実行
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.ymlを作成します:

version: "3.8"
services:
  fastapi:
    build: .
    container_name: fastapi-langchain
    ports:
      - "8000:8000"
    env_file:
      - .env # 任意:もし用意している場合
    extra_hosts:
      - "host.docker.internal:host-gateway"
    restart: unless-stopped

これで、dockerをビルドして実行できます:

docker-compose build
docker-compose up -d

結論

このチュートリアルでは、FastAPI、LangChain、MongoDBをシームレスに統合することで、モダンでデータ駆動型のアプリケーションを構築する、完全で実践的なデモを提供しました。

私たちは以下を取り上げました:

  • FastAPI:ユーザー登録やJWTベースの認証を含む、堅牢で高速、かつドキュメント化されたREST APIを作成するために使用します。
  • MongoDB(Motorを使用):ユーザーデータやアプリ固有のメモを扱いながら、非同期でスケーラブルなドキュメントストレージを提供します。
  • LangChain(Ollamaを使用):保存されたユーザーメモを動的なコンテキストとして活用し、パーソナライズされた役立つ提案や回答を生成できる強力なAI機能を可能にします。

例のアプリケーション(アイデア生成アシスタント)は、このスタックを、データの永続化、安全なユーザーアクセス、最先端の大規模言語モデルの統合が必要な複雑なプロジェクトにどう活用できるかを示す明確な設計図として機能します。さらに、OllamaによるローカルLLMを使用することで、スタック全体をローカルマシン上で実行可能にし、素早いプロトタイピングと開発を可能にしました。

この統合戦略――FastAPIの高速性、MongoDBの柔軟性、LangChainのインテリジェンスを組み合わせる――は、次世代のインテリジェントなWebアプリケーションを開発するうえで非常に効果的なパターンです。本ガイドが、あなたの今後のAI活用プロジェクトの確かな土台になれば幸いです。