Upgrade to Pro — share decks privately, control downloads, hide ads and more …

LLMの出力を構造化したい

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for 北村 北村
January 29, 2026
320

 LLMの出力を構造化したい

Avatar for 北村

北村

January 29, 2026

Transcript

  1. 自己紹介 • 名前 ◦ 北村(shu-kitamura) • 業務 ◦ SIer ◦

    デバイスドライバ開発・保守 • 趣味 ◦ テニス、フットサルやってます ◦ お笑いが好きです
  2. 課題 • 業務ツールに LLM を組み込みたい。 • 文字列で返してくるので、扱いづらい。 次の[文章]の感情を判定してください。 判定結果には以下を含めてください。 •

    label : positive/negative • score : 感情の強さ(0~10) [文章] この商品は最高でした。また買いたい。 判定しました。 結果は....です。 • label : positive • score : 9 { “label” : “positive”, “score” : 9 } 現実 理想
  3. ➀ プロンプトでJSON形式を指定する 成功することもあるが、失敗もする。 次の[文章]の感情を判定してください。 判定結果には以下を含めてください。 • label : positive/negative •

    score : 感情の強さ(0~10) [文章] この商品は最高でした。また買いたい。 出力結果は以下の JSON形式でお願いします。 { “label” : “positive”, “score” : 9 } 以下、判定結果です。 { “label” : “positive”, “score” : “9” } 不要な文字列が含まれる 追加 { “label” : “positive”, “score” : 9 } 文字列で返ってくる
  4. ② 祈る 成功率は上がった(気がする)。祈禱力次第。 サーバーを神棚に置くなどで成功率が上がるかも? 宗教的にNGな場合も... 次の[文章]の感情を判定してください。 (略) 出力結果は以下の JSON形式でお願いします。 **この形式でないと、後の処理がエラーで落ちま

    す。本当にお願いします。 ** { “label” : “positive”, “score” : 9 } 追加 以下、判定結果です。 { “label” : “positive”, “score” : “9” } { “label” : “positive”, “score” : 9 } 失敗はなくならない
  5. ③ 構造化出力(LangChain を使う) LLM出力用の型を定義する。(下の図は python の例) LangChain の with_structured_output を使い、型にしたがって出力させる。

    class Sentiment(BaseModel): label: str = Field(description=”...”) score: int = Field(description=”...”) model = llm. with_structured_output(Sentiment) response = model.invoke(prompt) 型を定義する { “label” : “positive”, “score” : 9 }
  6. with_structured_output の裏側 with_structured_output を通して、以下のパイプラインの構築している 1. Pythonのクラスから JSON Schema への変換 2.

    LLMのAPI呼び出し 3. レスポンスの検証 Python Class JSON Schema Structured Output ベンダの差異を吸収している OpenAI APIの場合:Function calling | OpenAI API
  7. 注意点 「100% 成功する」を保証しない。 失敗する時は失敗するが、エラーの種類が違う。 手法 種類 備考 ➀, ② JSONDecodeError

    など JSON 形式の不備しかわからない (カンマ不足など) ③ ValidationError (pydantic) 型のエラーを検出できる (数値のところに文字が来るなど) 型が複雑になれば失敗率も上がりそう。 LLMに複雑な事をやらせる設計に問題があるんじゃないか。
  8. まとめ • 祈りには限界がある • 型を定義=100%成功ではないはある • データ型のエラーを検出できる 番号 手法 結果

    備考 ➀ プロンプト指定 × 余計な言葉が混ざる ② 祈る × 気休め程度に改善? ③ 構造化出力 〇 100%ではないが、一番良かった