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?

Python で LM Studio を操作し、YAML から入力・タイトル生成して出力ファイルを作る方法

0
Posted at

0. この記事について

LMStudioをスクリプトから呼び出してしたことがなかったので手を動かしながら勉強がてらやってみたので、自分用ログ残し
コード部分はいろいろと試しつつやったので未整理状態


1️. 目的

  • LM Studio の LLM を Python から呼び出す
  • 質問と回答をファイルに保存する際に
    • input/ に質問文(YAML)を置く
    • output/ に日時+タイトル付きテキストを自動生成

2️. 必要なパッケージ

  • pyyaml : YAML ファイル読み込み用
  • lmstudio : LM Studio SDK (Python API)

3️. ディレクトリ構成

project/
├─ test.py          ← スクリプト本体
├─ input/                  ← 質問を格納するフォルダ
│   └─ input.yml           ← YAML ファイル(質問・タイトル)
└─ output/                 ← 出力結果用フォルダ (自動生成)

output は実行時に自動で作成されます。


4️. 実装コード

import os
from datetime import datetime
import re
import yaml
import lmstudio as lms

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
INPUT_DIR  = os.path.join(BASE_DIR, "input")
OUTPUT_DIR = os.path.join(BASE_DIR, "output")

# フォルダが無ければ作成
os.makedirs(INPUT_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)

# ────── YAML 読み込み ──────
yaml_path = os.path.join(INPUT_DIR, "input.yml")
with open(yaml_path, "r", encoding="utf-8") as f:
    cfg = yaml.safe_load(f)

question_text = cfg.get("question")
title_base   = cfg.get("title", "回答")

# ────── LM Studio で回答取得 ──────
model = lms.llm("openai/gpt-oss-20b")
response_obj = model.respond(question_text)

def get_text_from_result(result):
    for attr in ("output_text", "text", "content"):
        if hasattr(result, attr):
            txt = getattr(result, attr).strip()
            if txt:
                return txt
    print("[DEBUG] 利用できる属性:", dir(result))
    return ""

answer_text = get_text_from_result(response_obj)

# ────── タイトルをファイル名に変換 (日本語 OK) ──────
now          = datetime.now()
timestamp    = now.strftime("%y%m%d_%H%M")
safe_title   = re.sub(r'[\\/:*?"<>|]', "_", title_base.strip())
output_file_name = f"{timestamp}_{safe_title}.txt"
output_path      = os.path.join(OUTPUT_DIR, output_file_name)

# ────── 出力ファイルを書き込む ──────
with open(output_path, "w", encoding="utf-8") as f:
    f.write(answer_text)

print(f"[INFO] 出力が完了しました: {output_path}")

重要ポイント

セクション 内容
YAML 読み込み yaml.safe_load() で安全に辞書へ変換。
回答取得 model.respond() が返すオブジェクトは SDK バージョンによって属性名が異なるため、output_text / text / content を順にチェック。
ファイル名作成
  • timestamp = now.strftime("%y%m%d_%H%M") → YYMMDD_HHMM
  • タイトル中の「\ / : * ? " < > |」を _ に置換し、先頭/末尾空白を除去。 |
    | フォルダ作成 | os.makedirs(..., exist_ok=True) で既存の場合は何もしない。 |

5️. YAML の書き方(補足)

# key: value   ← シンプルな文字列
title:   "余剰次元理論の説明"

# 複数行文字列はパイプ `|` を使う
question: |
  あなたが持っている最新情報内での、余剰次元理論とは何か、
  また余剰次元理論の使われ方とどういう扱いなのかを1000字以内で教えてください。
  • インデントは 2 スペース以上(タブは不可)
  • | の直後に改行し、本文をインデントして書く

6️. まとめ

  1. 入力ファイル (input/input.yml) に質問とタイトルを書き込む。
  2. スクリプトで YAML を読み込み、LM Studio の LLM に投げて回答取得。
  3. タイトルを安全にファイル名へ変換し、output/YYMMDD_HHMM_タイトル.txt として保存。

これで「質問 → 回答 → ファイル化」の一連の流れが実行可能

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?