読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 PythonからLLMを呼ぶ

2.1 設定と、LLMを呼ぶクラス

練習ファイルは practice/vol1 にあります。FastAPIシリーズと同じく、設定は settings.py で読みます。

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env")

    database_url: str
    llm_base_url: str = "http://localhost:11434"
    chat_model: str = "qwen2.5:3b"
    llm_timeout_seconds: float = 60

llm_base_url と chat_model には初期値を書きました。秘密の値ではなく、書き忘れても安全に動くためです。モデルを替えたいときは、.env に CHAT_MODEL=qwen2.5:1.5b のように書きます。

LLMを呼ぶ処理は、llm.py の OllamaClient にまとめます。

class OllamaClient:
    def __init__(self, base_url: str, chat_model: str, timeout: float):
        self.base_url = base_url
        self.chat_model = chat_model
        self.timeout = timeout

    def chat(self, messages: list[dict], schema: dict | None = None) -> str:
        body = {
            "model": self.chat_model,
            "messages": messages,
            "stream": False,
            "options": {"temperature": 0},
        }
        if schema is not None:
            body["format"] = schema
        data = self._post("/api/chat", body)
        return data["message"]["content"]

chat は、会話(messages)を受け取り、モデルの答えの文章だけを返します。schema は4節で使います。呼ぶ側は、OllamaのJSONの形を知らなくても使えます。

6 / 20