Title: Examples Of Handling Llm Responses
Course: LLM_Prompt_Engineering_For_Developers > Section: Module 80: Examples Of Handling Llm Responses

Examples of Handling LLM Responses

Example 1: Parsing Structured Responses

When you prompt an LLM to return data in a structured format (like JSON), it’s important to handle that response properly.

Prompt:

"Provide the details of a book in JSON format. Title, Author, and Year of Publication."


LLM Response:

{
    "Title": "Example Book",
    "Author": "Jane Doe",
    "Year": 2023
}


Handling the Response:

You may parse this JSON response in your application as follows:

import json

response = '{"Title": "Example Book", "Author": "Jane Doe", "Year": 2023}'
book_info = json.loads(response)

print(f"Title: {book_info['Title']}, Author: {book_info['Author']}, Year: {book_info['Year']}")


Example 2: Filtering and Validating Outputs

If your application requires a specific format or certain keywords, you should filter and validate the LLM responses.

Prompt:

"List three programming languages."


Possible LLM Response:

1. Python
2. Banana
3. Java


Handling the Response:

You will want to validate the response to ensure it only contains programming languages.

response = "1. Python\n2. Banana\n3. Java"

valid_languages = ["Python", "Java", "JavaScript", "C#", "C++", "Ruby"]
lines = response.split('\n')
filtered_languages = [line.split('. ')[1] for line in lines if line.split('. ')[1] in valid_languages]

print("Valid Programming Languages:", filtered_languages)


Example 3: Dealing with Uncertainty and Errors

When the LLM generates inconsistent or incorrect responses, building an error-handling layer is essential.

Prompt:

"Tell me a fact about mars."


LLM Response:

"Mars is known for its blue oceans."


Handling the Response:

Check for accuracy before displaying the information:

response = "Mars is known for its blue oceans."
correct_facts = [
    "Mars is known for its red surface.",
    "Mars has two moons, Phobos and Deimos."
]

if response not in correct_facts:
    print("The information may be inaccurate. Please verify.")
else:
    print(response)


Conclusion