0Pricing
Prompt Engineering & LLM Optimization for Developers · Lezione

Parsing e convalida dell'output

Implementi solidi meccanismi di parsing e convalida per garantire che gli output dell'LLM siano nel formato desiderato e rispettino gli standard di qualità specificati.

Parsing e convalida dell'output è una lezione Prompt Engineering & LLM Optimization for Developers gratuita su CoddyKit. Questa è la lezione 3 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 Prompt Engineering & LLM Optimization for Developers, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Prompt Engineering & LLM Optimization for Developers include 4 lezioni in totale.

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

Why Parse LLM Output?

Large Language Models (LLMs) are powerful, but their raw text outputs can be unpredictable. For applications, we often need structured, reliable data.

Output parsing is the process of converting an LLM's free-form text response into a structured format your application can easily use, like JSON or a specific data type.

The Need for Validation

Even after parsing, the extracted data might not be valid. An LLM might hallucinate a number, provide an incorrect type, or miss a required field.

Output validation ensures the parsed data adheres to predefined rules, data types, ranges, or custom business logic, preventing errors downstream in your application.

Challenges with Raw LLM Output

LLMs can sometimes include conversational filler, extra explanations, or slightly deviate from the requested format. Consider an LLM asked to return a user's ID and name:

  • "Here is the user: ID:123, Name:Alice."
  • "User info -> {id: 456, name: Bob}"
  • "ID is 789, Name is Charlie. Hope this helps!"

Each needs a different approach to extract the data.

Basic String Manipulation

For very simple and highly constrained outputs, basic string methods can work. This is suitable when you have strong control over the prompt and expect minimal deviation.

Common methods include trim(), substring(), indexOf(), and split() to isolate and extract parts of the string.

String Manipulation Example

Here's how to extract data from a simple "ID:123,Name:Alice" string using basic Java string methods:

public class Main {
  public static void main(String[] args) {
    String llmOutput = "ID:123,Name:Alice";
    
    String[] parts = llmOutput.split(",");
    String idStr = parts[0].replace("ID:", "").trim();
    String nameStr = parts[1].replace("Name:", "").trim();
    
    System.out.println("ID: " + idStr);
    System.out.println("Name: " + nameStr);
  }
}

Regular Expressions (Regex)

When output patterns are more complex, or you need to match specific formats with variations, Regular Expressions (Regex) are incredibly powerful. They define search patterns for strings.

Regex can extract data even if there's extra text, inconsistent spacing, or different ordering of elements.

Regex Parsing Example

Let's use regex to extract a number from a string that might have various prefixes or suffixes. This Java example uses java.util.regex.Pattern and Matcher.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    String llmOutput = "The magic number is 42! Please use it.";
    Pattern pattern = Pattern.compile("\\d+"); // Matches one or more digits
    Matcher matcher = pattern.matcher(llmOutput);
    
    if (matcher.find()) {
      System.out.println("Found number: " + matcher.group());
    } else {
      System.out.println("No number found.");
    }
  }
}

Parsing JSON Outputs

For structured data, JSON (JavaScript Object Notation) is the preferred format. LLMs can be prompted to output JSON directly. You'll need a JSON parsing library to convert the string into an object.

This allows you to access fields by name (e.g., data.get("id")) instead of relying on string positions.

JSON Parsing in Java

Using a library like org.json (or Jackson/Gson for more complex cases) simplifies parsing JSON. Here's how to parse a simple JSON string:

import org.json.JSONObject;

public class Main {
  public static void main(String[] args) {
    String jsonString = "{"id":123, "name":"Alice"}";
    try {
      JSONObject json = new JSONObject(jsonString);
      int id = json.getInt("id");
      String name = json.getString("name");
      
      System.out.println("User ID: " + id);
      System.out.println("User Name: " + name);
    } catch (Exception e) {
      System.err.println("Error parsing JSON: " + e.getMessage());
    }
  }
}

Implementing Data Validation

After parsing, validate the data. This involves checking data types, ranges, and business rules. For JSON, you might check if required fields exist, if numbers are within expected bounds, or if strings match certain patterns.

Example checks: age > 0, email.contains("@"), list.size() > 0.

Quick Check: Output Handling

When working with LLM outputs, what are effective strategies to ensure the data is usable and correct in your application?

Recap & Next Steps

In this lesson, you learned that robust LLM integration requires more than just prompting. You need to implement solid output parsing to extract data from raw text and output validation to ensure that data meets your application's requirements.

  • Basic string methods for simple cases.
  • Regular Expressions for pattern matching.
  • JSON parsing libraries for structured data.
  • Validation logic to check data types, ranges, and rules.

Mastering these techniques will significantly improve the reliability and stability of your LLM-powered applications. Next, explore advanced techniques like Retrieval Augmented Generation (RAG) to ground LLM responses in external knowledge!

Domande Frequenti

La lezione «Parsing e convalida dell'output» è gratuita?

Sì — il testo completo di «Parsing e convalida dell'output» è 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 Prompt Engineering & LLM Optimization for Developers, passa a CoddyKit PRO. Il corso Prompt Engineering & LLM Optimization for Developers include 4 lezioni in totale.

Cosa imparerò in «Parsing e convalida dell'output»?

Implementi solidi meccanismi di parsing e convalida per garantire che gli output dell'LLM siano nel formato desiderato e rispettino gli standard di qualità specificati. Eserciti Prompt Engineering & LLM Optimization for Developers 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 Prompt Engineering & LLM Optimization for Developers?

Non è richiesta alcuna esperienza precedente. Prompt Engineering & LLM Optimization for Developers su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Parsing e convalida dell'output»?

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 Prompt Engineering & LLM Optimization for Developers?

Sì. Ogni lezione Prompt Engineering & LLM Optimization for Developers 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. Efficienza dei token e gestione del contesto
  2. Tecniche di riduzione della latenza
  3. Parsing e convalida dell'output
  4. Caching e batching per ridurre i costi degli LLM
← Torna a Prompt Engineering & LLM Optimization for Developers