Article
prompt-engineeringllmopenaipythonfew-shot-promptingstructured-outputsystem-promptapi
Practical Prompt Engineering for Better AI Results
Learn the foundational skill of Prompt Engineering to control and improve AI outputs. This guide covers crafting system prompts, providing clear instructions with examples (few-shot), and structuring responses for reliable, programmatic use. Get more predictable results from your LLM.
beginner30 min5 steps
The play
- Set the Stage with a System PromptUse a system prompt to define the AI's persona, role, and high-level rules. This 'constitution' guides all subsequent interactions and is a key part of effective Prompt Engineering. It sets the context before the user's query is processed.
- Write Clear, Specific InstructionsAvoid ambiguity. Tell the model exactly what you want, including the desired tone, format, and length. Provide all necessary context within the prompt itself to prevent the model from guessing or making assumptions. This reduces variability in responses.
- Guide with Examples (Few-Shot Prompting)Show, don't just tell. Including a few examples ('shots') of the desired input-output pattern within your prompt is one of the most powerful Prompt Engineering techniques. This helps the model understand complex formats and styles without lengthy explanations.
- Demand Structured OutputFor application development, force the model to respond in a machine-readable format like JSON. Explicitly state the desired schema in your prompt, as shown in the few-shot example. This ensures consistent, parseable results you can use programmatically.
- Iterate and RefineYour first prompt is rarely your best. Prompt Engineering is an iterative process. Analyze the model's output, identify weaknesses in your prompt (e.g., incorrect format, hallucinations), and refine it. Test different phrasing, add more context, or adjust your examples until you get the desired result consistently.
Starter code
import os
import openai
import json
# Make sure to `pip install openai`
# Set your OpenAI API key as an environment variable: export OPENAI_API_KEY='your-key-here'
client = openai.OpenAI()
# This prompt combines a system message, clear instructions, and few-shot examples.
# It also demands a specific JSON output structure.
messages = [
{
"role": "system",
"content": "You are an expert data extractor. Given a user's text, you will extract the name of the person, their job title, and the company they work for. You must respond with only a single, valid JSON object."
},
{
"role": "user",
"content": """
Here are some examples:
Text: "We're excited to have Sarah Jones join us as the new CEO of InnovateCorp."
Output: {"person_name": "Sarah Jones", "job_title": "CEO", "company": "InnovateCorp"}
Text: "The keynote was delivered by Alex Chen, the lead data scientist at QuantumLeap."
Output: {"person_name": "Alex Chen", "job_title": "Lead Data Scientist", "company": "QuantumLeap"}
Now, extract the details from the following text:
Text: "The new project manager at FutureGadget is named Ben Carter."
Output:
"""
}
]
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=0.1 # Lower temperature for more predictable, structured output
)
response_content = response.choices[0].message.content
print("--- Raw Model Output ---")
print(response_content)
print("\n--- Parsed JSON Object ---")
parsed_json = json.loads(response_content)
print(json.dumps(parsed_json, indent=2))
except openai.APIConnectionError as e:
print("The server could not be reached")
print(e.__cause__)
except openai.RateLimitError as e:
print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
print("Another non-200-range status code was received")
print(f"Status: {e.status_code}")
print(f"Response: {e.response}")
except Exception as e:
print(f"An unexpected error occurred: {e}")