カスタム出力パーサーを作成する
カスタムおよび組み込みの LangChain output parsers を使い、生の LLM テキストを信頼性の高い構造化データに変換します。
「カスタム出力パーサーを作成する」はCoddyKit上の無料LangChain / RAG / Vector DBsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはLangChain / RAG / Vector DBs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 LangChain / RAG / Vector DBsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Parse Output?
LLMs return free-form text, but applications need structured data: objects, lists, enums. An output parser converts the raw string into something your code can use safely.
The Parser Interface
A LangChain output parser implements two key methods.
parse(text)turns the string into your typeget_format_instructions()tells the model how to format its reply
A Minimal Custom Parser
Subclass BaseOutputParser and implement parse. This one splits a comma-separated reply into a list.
from langchain_core.output_parsers import BaseOutputParser
class CommaListParser(BaseOutputParser):
def parse(self, text):
return [t.strip() for t in text.split(",")]
print(CommaListParser().parse("a, b, c")) # ["a", "b", "c"]Format Instructions
Override get_format_instructions so the prompt nudges the model toward a parseable shape. The instructions are injected into your prompt template.
def get_format_instructions(self):
return "Reply with items separated by commas, no numbering."Pydantic Output Parser
For rich objects, LangChain ships a PydanticOutputParser. You define a schema and it generates instructions plus validation automatically.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
# parser = PydanticOutputParser(pydantic_object=Person)Wiring a Parser into a Chain
With LCEL you pipe the model output straight into the parser using the | operator.
chain = prompt | llm | CommaListParser()
result = chain.invoke({"topic": "fruits"})Handling Malformed Output
Models sometimes ignore the format. A robust parser validates and raises a clear error, or attempts a best-effort recovery, instead of crashing downstream.
def parse(self, text):
try:
return json.loads(text)
except json.JSONDecodeError:
raise ValueError("Model did not return valid JSON")The OutputFixingParser
Wrap any parser in an OutputFixingParser. When parsing fails, it sends the bad output and the error back to an LLM to repair it.
Streaming and Parsers
Some parsers support incremental parsing of streamed tokens. For structured types this is hard, so streaming parsers often emit partial objects as fields complete.
Validation Beyond Types
You can add business rules inside parse: ranges, allowed values, required combinations. Reject anything that would corrupt your application state.
def parse(self, text):
n = int(text.strip())
if not 1 <= n <= 5:
raise ValueError("Rating must be 1-5")
return nPutting It Together
Define the parser, expose format instructions, inject them into the prompt, and pipe everything in a chain. The result is reliable structured output.
prompt = template.partial(
format=parser.get_format_instructions()
)
chain = prompt | llm | parser
chain.invoke({"input": "..."})Quick Check
Test your understanding of output parsers.
Recap
You built custom output parsing:
- Implement
parseandget_format_instructions - Use
PydanticOutputParserfor rich schemas - Pipe parsers into chains with
| - Wrap with
OutputFixingParserfor resilience
よくある質問
「カスタム出力パーサーを作成する」レッスンは無料ですか?
はい。「カスタム出力パーサーを作成する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、LangChain / RAG / Vector DBsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 LangChain / RAG / Vector DBsコースには全4レッスンが含まれています。
「カスタム出力パーサーを作成する」で何を学びますか?
カスタムおよび組み込みの LangChain output parsers を使い、生の LLM テキストを信頼性の高い構造化データに変換します。 ブラウザで直接実行するハンズオンコードでLangChain / RAG / Vector DBsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
LangChain / RAG / Vector DBsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのLangChain / RAG / Vector DBsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「カスタム出力パーサーを作成する」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このLangChain / RAG / Vector DBsレッスンでコードを書いて実行できますか?
はい。すべてのLangChain / RAG / Vector DBsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- カスタムドキュメントローダーの開発
- カスタム埋め込みモデルの統合
- カスタムロジックによる検索チェーンの拡張
- カスタム出力パーサーを作成する