Prompt Engineering
✕Prompt Engineering Concept
- Effective prompts is key to getting high-quality outputs from LLMs.
- Strong prompts save time, reduce errors, turns a general model into specialized.
- It's an iterative process of refining prompts based on model output.
- Think of it like a recipe — good ingredients (context) and clear steps (instructions) yield reliable results.
Principles of Effective Prompt Design
- Action Verbs: Start with direct verbs like
Write,Explain,Summarize,Extract,Classify. Avoid vague verbs likeUnderstand,Think,Try. - Specific: Mention
exact requirements,constraints,tone,length,target audience,output format. - Context: Provide relevant background information, examples to guide model.
- Delimiters: Use clear delimiters to separate instructions and data.
- Iterate: Refine prompts based on output quality and errors.
Sample Prompts
Prompt Examples and their Effects:
| Weak Prompt | Improved Prompt |
|---|---|
| Write a summary of this article. | Write a concise summary of the following article in 3 sentences, highlighting the main points and key takeaways. |
| Write a poem on rain. | Write a poem on topic rain in two paragraph for student of grade two. |
| What are the benefits of exercise? | List 5 scientifically proven benefits of regular exercise, including physical and mental health effects. |
| Translate this text to Spanish. | Translate the English text inside triple backticks to Spanish, ensuring that the tone is formal and the meaning is preserved: ``Hello, how are you?`` |
| five must watch action movies? | Create a two-column table of 5 must-watch action movies released in the last decade with headings "Movie Title" and "Release Year" (no extra commentary). |
| Generate title for given text. | Generate a catchy and SEO-friendly title for the following blog post content inside triple backticks. Ouput has to be in json form as {"title": "generated_title"}. Input text: ``your_text`` |
Examples of weak prompts and their improved versions with specific instructions and context.
Conditional and Role-based Prompts
- Conditional Rules: Add simple logic to keep outputs on track.
language checks,keyword checks. - Role-playing: Assign a persona to control tone and content.
financial analyst,support agentetc. - You will be given text between triple backticks. If it's in English, suggest a title. Otherwise, reply: 'I only understand English.' ``
{}`` - Act as a gentle customer support agent. If the question is not about our products, reply: 'I can help with product questions only.' Now answer: ``
What app features do you offer?``.
Example:
One-shot and Few-shot Prompting
- To teach the model our desired
format,reasoning style,constraintsby giving exmples. - Make examples short, diverse and representative of edge cases.
- One-shot: Provide one example.
- Few-shot: Provide 2-5 examples to improve consistency and quality.
- One-shot:
Q: Sum the numbers 3, 5, and 6. A: 14 Q: Sum the numbers 2, 4, and 7. A: - Few-shot:
Text: Today the weather is fantastic => Classification: positive Text: The furniture is small => Classification: neutral Text: I don't like your attitude => Classification: negative Text: That shot selection was awful => Classification:
Example:
Multistep Reasoning Prompts
- Break down complex tasks into smaller steps to guide the model through the reasoning process.
- Use explicit instructions to perform each step sequentially.
- This can improve accuracy for tasks that require logical reasoning or multi-step calculations.
Step 1: Identify the main topic of the input text. Step 2: Determine the sentiment associated with the topic. Step 3: Output the classification in JSON format.
Example:
Prompt in Action
- Extract 'Product Name', 'Display Size', 'Camera Resolution' from text inside triple quotes. Return result in json as:
{"product_name": "", "display_size": "", "camera_resolution": ""}. Text: ``The Samsung Galaxy S23 features a 6.1-inch Dynamic AMOLED display and a 50 MP main camera for high-quality photography.`` - Extract all nepali phone numbers and email addresses from the text inside triple ticks. Return the result in JSON format as:
{"phone_numbers": [], "emails": []}. Text: ``Ram Sharma from Kathmandu asked me to email the report to [email protected]. If anything is unclear, he said I can call him at 9841234567. Later I spoke with Sita Gurung about the meeting. She told me to confirm the details at [email protected] or reach her on +977-9851023344. For finance matters, Bikash Adhikari said the quickest way is the office landline +977-1-4789123.``
Common Prompting Pitfalls
- Vague instructions leading to inconsistent outputs.
- Overly complex prompts that confuse the model.
- Lack of context causing irrelevant or incorrect responses.
- Not iterating and refining prompts based on output quality.
Summary
Prompt Engineering Principles at a Glance:
| Type | What it does | Best for | Example |
|---|---|---|---|
| Zero-shot | No examples, just instructions. | Fast general tasks. | Summarize text inside triple ticks in 3 bullets |
| One/Few-shot | Include 1 or more examples. | Style, format, reasoning consistency. | Q: … A: … Now answer: … |
| Role Playing | Assign a persona. | Tone and domain control. | Act as a calm customer support agent… |
| Conditional | Add conditional rules. | Guardrails, Routing | ... If text is not English, reply 'I only understand English'. |
| Multistep Reasoning | Break down complex tasks into steps. | Complex / Sequential tasks. | Step 1: ... Step 2: ... Step 3: ... |
Integrating Gemini API in Python
- Get your API key from Google AI Studio.
- Click on
Create API Key. (Click new project if asked) - Copy the generated API key and keep it secure.
- Install the Gemini API client library:
pip install google-genai from google import genai API_KEY = "your-api-key-here" client = genai.Client(api_key=API_KEY) user_input = "Write a short poem about AI in 3 lines." response = client.models.generate_content(model="gemini-2.5-flash", contents=user_input) print(response.text)
Setup Gemini API Access
Sample Python Code to Call Gemini API
System Instruction
- System Prompt: Set context, rules, tone, output format, guideline.
- User Prompt: The actual input from the end-user.
- Assistant: The model's response based on the system and user prompts.
- Some System instructions: - You are a helpful assistant. - Answer in a formal tone. - Provide concise responses. - Only use information from the provided text.
system_instruction = "You are a language translator who translates English into Nepali Language. If you receive input other than English reply content has to be 'Not an English Text' else the converted one. Provide output in JSON as {'Input': user_word, 'Output': converted_word'}" user_input = "Hello, How are you doing?" response = client.models.generate_content(model="gemini-2.5-flash", config={'system_instruction': system_instruction}, contents=user_input) print(response.text)
Examples:
Practice QuestionsNot started
Zero Shot classification
Question 1 of 5
- Write a function
get_sector(company_name)that takes a company name (e.g., Tesla) and returns only its industry sector (e.g., Automotive) in a single word. - Write a function
is_urgent(email_body)that analyzes a customer email and returnsTrueif customer sounds frustrated or mentions a deadline, andFalseotherwise. - Write a function
classify_sentiment(text)that classifies the sentiment of a given text aspositive,negative, orneutral. - Write a function
to_kg(weight_str)that takes strings like 150 lbs or 2 tons and returns the numerical value converted to kilograms as a float.
- Write a function
Few Shot classification
Question 2 of 5
- Write a function
extract_skills(job_description)that extracts and returns a list of required skills mentioned in a job description using 2 examples. - Write a function
standardize_date(date_str)that provides 3 examples of converting messy dates (e.g., Jan 5th 22, 05/01/2022) into the YYYY-MM-DD format - Write a function
parse_address(raw_text)that uses 2 examples to show how to turn a string like 123 Main St, New York, NY into a JSON with street, city, state keys. - Write a function
text_to_sql(user_query)that uses 4 examples to teach the model how to convert a natural language request (e.g., Show me top 5 users by spend) into a valid SELECT statement for a table named Users
- Write a function
Role Playing
Question 3 of 5
- Write a function
explain_p_value(p_val)where the model acts as a Senior Statistician. It should explain the significance of the input p_val to a non-technical product manager. - Write a function
check_pii(text_data)where the model acts as a Privacy Auditor. It must scan a string and return a list of any sensitive information found (emails,phone numbers,names). - Write a function
review_code(python_snippet)where the model acts as a Lead Engineer. It should return exactly two bullet points: one for a bug found and one for a performance improvement.
- Write a function
Conditional Prompting
Question 4 of 5
- Write a function
translate_if_needed(text)that checks the input language. If it is English, return the text as-is; else return the English translation. - Write a function
safe_summary(news_article)that summarizes a text, but adds a rule: "If the article contains political bias, start the response with 'Warning: Subjective Content' before the summary." - Write a function
route_query(user_query)that checks if the input is a technical support question (e.g., contains words like "error", "issue", "help"). If it is, return "Route to Tech Support"; otherwise, return "Route to Sales".
- Write a function
Multistep Reasoning
Question 5 of 5
- Write a function
plan_experiment(business_problem)that takes a problem like "Users are leaving the checkout page." Step 1: State a null hypothesis. Step 2: Propose an A/B test change (e.g., button color). Step 3: Define the "Success Metric" to track.
- Write a function
