0Pricing
Prompt Engineering & LLM Optimization for Developers · 课时

输出解析与验证

实现可靠的解析和验证机制,确保 LLM 输出符合所需格式和指定的质量标准。

输出解析与验证 是 CoddyKit 上的免费 Prompt Engineering & LLM Optimization for Developers 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Prompt Engineering & LLM Optimization for Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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!

常见问题解答

「输出解析与验证」课时是免费的吗?

是的 — 「输出解析与验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Prompt Engineering & LLM Optimization for Developers 课程的其余内容,请升级到 CoddyKit PRO。 Prompt Engineering & LLM Optimization for Developers 课程共包含 4 节课。

「输出解析与验证」这节课中我会学到什么?

实现可靠的解析和验证机制,确保 LLM 输出符合所需格式和指定的质量标准。 你通过在浏览器中直接运行的动手代码来练习 Prompt Engineering & LLM Optimization for Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Prompt Engineering & LLM Optimization for Developers 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Prompt Engineering & LLM Optimization for Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「输出解析与验证」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Prompt Engineering & LLM Optimization for Developers 课中编写并运行代码吗?

能。每节 Prompt Engineering & LLM Optimization for Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 令牌效率与上下文管理
  2. 降低延迟的技术
  3. 输出解析与验证
  4. 通过缓存与批处理降低 LLM 成本
← 返回 Prompt Engineering & LLM Optimization for Developers