LangChain / RAG / Vector DBs · Lezione

Creare parser di output personalizzati

Trasformi il testo grezzo dell’LLM in dati strutturati affidabili con i parser di output personalizzati e integrati di LangChain.

Lezione 4 di 413 passaggi

Creare parser di output personalizzati è una lezione LangChain / RAG / Vector DBs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento LangChain / RAG / Vector DBs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso LangChain / RAG / Vector DBs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 type
  • get_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 n

Putting 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 parse and get_format_instructions
  • Use PydanticOutputParser for rich schemas
  • Pipe parsers into chains with |
  • Wrap with OutputFixingParser for resilience
Gratis per iniziare

Impara LangChain / RAG / Vector DBs con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Creare parser di output personalizzati» è gratuita?

Sì — il testo completo di «Creare parser di output personalizzati» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso LangChain / RAG / Vector DBs, passa a CoddyKit PRO. Il corso LangChain / RAG / Vector DBs include 4 lezioni in totale.

Cosa imparerò in «Creare parser di output personalizzati»?

Trasformi il testo grezzo dell’LLM in dati strutturati affidabili con i parser di output personalizzati e integrati di LangChain. Eserciti LangChain / RAG / Vector DBs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare LangChain / RAG / Vector DBs?

Non è richiesta alcuna esperienza precedente. LangChain / RAG / Vector DBs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Creare parser di output personalizzati»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione LangChain / RAG / Vector DBs?

Sì. Ogni lezione LangChain / RAG / Vector DBs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Sviluppo di loader personalizzati per documenti
  2. Integrazione di modelli di embedding personalizzati
  3. Estensione delle catene di retrieval con logica personalizzata
  4. Creare parser di output personalizzati
← Torna a LangChain / RAG / Vector DBs