Sub topic 2
Giving Context and Separating Input from Instructions
Assume you know how to use a chat-based AI assistant, can read short Python code, and understand basic JSON. This chapter focuses on making prompts reliable when they contain both instructions and user-provided data.
Giving Context and Separating Input from Instructions
A model uses the complete prompt to predict a response. It may confuse data with instructions when the boundaries are unclear. State the task first, then place the input inside delimiters such as triple quotes or XML-like tags.
Summarize the support ticket for an engineering manager.
Use at most three bullet points. State customer impact first.
If the cause is not stated, write "Cause unknown".
Ticket:
"""
{ticket_text}
"""The delimiters do not create a security boundary by themselves. They make the prompt easier to read and reduce accidental mixing. Treat the delimited text as untrusted data. A ticket might contain text such as “ignore previous instructions,” which should remain part of the ticket rather than changing the task.
Setting a Role with System Prompts
A system prompt is an instruction placed in a higher-priority message by the application. It can define the assistant’s general role, such as “You are a support-ticket classifier.” A user prompt then supplies the current task and data.
Roles help establish vocabulary, priorities, and boundaries. They do not guarantee accuracy. Do not use a role prompt as a substitute for explicit task instructions or validation.
Teaching by Example: Zero-Shot and Few-Shot Prompts
A zero-shot prompt gives instructions without examples. A few-shot prompt includes labeled examples that demonstrate the expected behavior.
def build_prompt(examples, new_review):
parts = [
"Classify each review as positive, negative, or neutral.",
""
]
for review, label in examples:
parts.append(f"Review: {review}\nSentiment: {label}\n")
parts.append(f"Review: {new_review}\nSentiment:")
return "\n".join(parts)
examples = [
("The battery lasts all week.", "positive"),
("It stopped working after two days.", "negative"),
]
print(build_prompt(examples, "Setup was confusing."))Use examples that match real inputs. Inconsistent examples can teach the wrong rule.
Getting Predictable Output Formats
Specify the format, allowed values, and behavior for invalid or missing information. For machine-readable output, validate the response instead of trusting the instruction.
import json
def parse_reply(reply):
try:
value = json.loads(reply)
except json.JSONDecodeError:
return None
if not isinstance(value, dict):
return None
if value.get("sentiment") not in {"positive", "negative", "neutral"}:
return None
return value
print(parse_reply('{"sentiment": "positive"}'))Exercise
What should you change first when a model treats text inside a ticket as a new instruction?
Show answer
State the task before the ticket and place the ticket inside clear delimiters, then validate the response.