Improve AI responses by providing demonstrations and examples in your prompts
Few-shot learning is a powerful prompting technique where you provide examples of the desired input-output pattern before making your actual request. This approach dramatically improves response quality, consistency, and accuracy by showing the AI exactly what you want.
Few-shot prompting involves including one or more examples in your prompt to demonstrate the pattern, style, format, or approach you want the AI to follow.
The term “few-shot” refers to the number of examples:
Transform this error message to be user-friendly.Example:Technical: "ERR_CONN_REFUSED: Connection refused at port 5432"User-friendly: "We're having trouble connecting to our database. Please try again in a moment."Now transform:Technical: "TypeError: Cannot read property 'id' of undefined at line 42"User-friendly:
Generate API endpoint documentation following this pattern:Example 1:Endpoint: POST /api/usersDescription: Creates a new user account with the provided details.Authentication: Required (Bearer token)Rate limit: 10 requests per minuteExample 2:Endpoint: GET /api/users/:idDescription: Retrieves detailed information for a specific user by their ID.Authentication: Required (Bearer token)Rate limit: 100 requests per minuteExample 3:Endpoint: DELETE /api/users/:idDescription: Permanently deletes a user account and all associated data.Authentication: Required (Bearer token + Admin role)Rate limit: 5 requests per minuteNow document this endpoint:Endpoint: PATCH /api/users/:id/preferences[Provide details about updating user preferences]
Write product feature announcements in this style:Example 1:Feature: Dark ModeWe've added dark mode to reduce eye strain during late-night coding sessions. Toggle between light and dark themes in your settings, and your preference will sync across all your devices. Your eyes (and sleep schedule) will thank you.Example 2:Feature: Collaborative EditingWork together in real-time with your team. See cursor positions, edits, and comments as they happen. No more "did you get my latest changes?" messages cluttering your Slack channels.Example 3:Feature: Smart SearchFind anything instantly with our new semantic search. Type natural language queries like "authentication bug from last week" instead of hunting through titles and tags. It's like having a conversation with your project history.Now write an announcement for:Feature: Auto-save with Version History
Start with simple examples and increase complexity:
Copy
Extract structured data from text following this pattern:Example 1 (Simple):Text: "Meeting with John tomorrow at 2pm"Output:{ "type": "meeting", "participants": ["John"], "date": "tomorrow", "time": "14:00"}Example 2 (Multiple participants):Text: "Team standup with Sarah, Mike, and Lisa on Friday at 9am"Output:{ "type": "meeting", "participants": ["Sarah", "Mike", "Lisa"], "date": "Friday", "time": "09:00"}Example 3 (With location):Text: "Product review meeting with the design team next Monday at 3pm in Conference Room B"Output:{ "type": "meeting", "participants": ["design team"], "date": "next Monday", "time": "15:00", "location": "Conference Room B"}Now extract from:Text: "Quarterly planning session with all department heads on March 15th at 10:30am via Zoom"
Generate SQL queries for an e-commerce database:Example 1 - Find high-value customers:Query: "customers who spent over $1000 in the last 6 months"SQL:SELECT c.customer_id, c.email, SUM(o.total_amount) as total_spentFROM customers cJOIN orders o ON c.customer_id = o.customer_idWHERE o.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)GROUP BY c.customer_id, c.emailHAVING SUM(o.total_amount) > 1000ORDER BY total_spent DESC;Example 2 - Popular products:Query: "top 10 products by units sold this month"SQL:SELECT p.product_id, p.product_name, SUM(oi.quantity) as units_soldFROM products pJOIN order_items oi ON p.product_id = oi.product_idJOIN orders o ON oi.order_id = o.order_idWHERE MONTH(o.order_date) = MONTH(CURRENT_DATE) AND YEAR(o.order_date) = YEAR(CURRENT_DATE)GROUP BY p.product_id, p.product_nameORDER BY units_sold DESCLIMIT 10;Now generate SQL for:Query: "customers who abandoned carts in the last 24 hours with cart value over $50"
Few-shot prompting works well with other approaches:
Few-shot + Chain-of-thought
Few-shot + Role-based
Copy
Solve these debugging problems step by step:Example 1:Bug: "React component not re-rendering when state changes"Analysis:1. Check if state is being mutated directly (mutation won't trigger re-render)2. Verify useState is being used correctly3. Confirm component isn't memoized incorrectlySolution: Replace `items.push(newItem)` with `setItems([...items, newItem])`Explanation: Direct array mutation doesn't trigger React re-renders. Use immutable updates.Example 2:Bug: "API returns 401 but user is logged in"Analysis:1. Check if token is being sent in request2. Verify token hasn't expired3. Confirm token is in correct formatSolution: Include token in Authorization header: `Authorization: Bearer ${token}`Explanation: Token must be sent with each API request using proper header format.Now debug:Bug: "Form submission triggers twice on button click"
Copy
As a senior code reviewer, provide code review feedback:Example 1:Code: `if (user.isActive == true)`Feedback: ⚠️ **Unnecessary comparison** - `isActive` is already boolean. Use `if (user.isActive)` instead.Impact: Minor - readabilitySuggestion: `if (user.isActive)`Example 2:Code: `const data = JSON.parse(response);`Feedback: 🔴 **Missing error handling** - JSON.parse can throw. Wrap in try-catch.Impact: High - potential runtime errorSuggestion:```javascripttry { const data = JSON.parse(response);} catch (error) { console.error('Invalid JSON:', error);}
Now review this code:
Copy
async function updateUser(id, data) { await fetch(`/api/users/${id}`, { method: 'POST', body: data });}