Prompt engineering
Prompt engineering is the process of designing and instructing a Large Language Model in order to get the desired output.
The more detailed and specific the prompt is, the closer to the expected results you get from the LLM; the more accurate, relevant, and creative results are delivered. Crafting effective prompts can maximize the power of large language models, and providing detailed and accurate prompts enables these models to understand the intent of the instructions.
Prompt Engineering Concepts
In everyday life, for example, think of ordering a turkey sandwich. If you said I’d like a turkey sandwich,” you may get two pieces of bread and turkey from the sandwich maker. You then may have to give it back and say you want mayo on it. A better way would be to provide the person with specific details of how you like the sandwich. “I’d like a turkey sandwich with lettuce, tomato, and mayo on whole wheat bread. Now the person can deliver the sandwich exactly the way you want or expect it to be.
When building prompts, there are some important concepts to consider:
Persona - When designing prompts, it is helpful to define a role or identity you want the LLM to take on depending upon the task you want to complete. It can also be used to have the LLM deliver a tone or perspective.
Generally, we would ask the LLM to “Act as a” Project Manager, Python developer, Financial Analyst, Editor, or Professor for expertise results or persona used to craft messages to sound like a toddler, teenager, grandparent, or busy mom.
When using expertise like a Python developer, the LMM can focus on vast amounts of code it has analyzed and provide results.
Using a tone persona can deliver simple or pleasant-sounding results like a grade school teacher.
Task - Refers to the specific task that you want the model to generate. It should clearly define the action you need produced. Use strong verbs like summarize, extract, provide, deliver, define, and explain as calls to action. The task needs to be clear as to what you want.
Context - Is the background you provide to the LLM? It provides the setting for your task. It explains the scenario on which the answer is based by providing specific issues related to the task's need.
For example, I need a daily workout plan to get in shape. I can add the context - I’m a 25-year-old man slightly overweight. Or I draft a presentation of the benefits of AI. Context - Presenting to high-level executives who have been skeptical of its use.
Constraints - The limitations you provide to the model in order to narrow the output for usable results. They provide a set of rules for the model's response.
Some constraints may be “Limit response to 500 words” because of a publishing limitation. “Do not use technical words” due to concern that it may confuse the audience, or “limit bullet points to 5” to ensure results don’t seem too cluttered. They allow more focused results.
instructions. Detailed, specific, and accurately designed to complete the task. The more precise the expected outcome, the better the results.
Format - It instructs the model on how the output should be formatted. It tells the model that the output needs to be in Python code, a CSV file, JSON, or spreadsheet format.
Prompting Techniques
There are several techniques to use prompt engineering in your favor.
Zero-Shot Prompting - The simplest technique to instruct an AI model. You just give the model a single straightforward task to retrieve basic results.
Some examples include translating this document into Spanish or extracting the text from this image.
Few-Shot Prompting is a technique used to provide examples to the LLM model of the output you want it to deliver.
You provide exact outputs or a format you expect, giving the model a pattern to follow.
An example is providing multiple data examples and showing how they should look when finished. The model can observe the formatting that you want.
Chain-of-Thought Prompting - Instructs the AI model to use a step-by-step process that yields a series of logical solutions that contribute to the overall answer. It allows the model to follow a more reasoned path than the quick answer.
Take, for example, a company whose shipping costs increased by 10% while our orders grew by 5%. Show why this may have happened. The model can then provide possible reasons for this increase in a step-by-step process.
Effective Prompt Strategies
LLMs use pattern recognition to identify relationships between the words entered and the data the model is trained on.
The results are based on training data, and they use probability, not facts, to state results, which can lead to hallucinations or false results
Effective prompts have a clear job description.
Persona or expertise level -. “Act as a Python developer”
Specific action to be taken - “Summarize this earnings report”
Context - “Focus on income growth”
Input data - “file upload or attachment”
Format - “data should be in JSON format”
Constraint - “keep report under 300 words”
Some Examples or Use Cases
Ask questions, looking for a model to return answers.
Code generation, debugging code, modifying code for new requirements.
Document creation, writing essays, emails, correspondence.
Summarization: Distilling long documents into executive bullet points.
Ask Questions
What has been the revenue growth for Google in the last 12 months?Instructions only focus on SEC filings
According to Alphabet Inc.’s SEC filings (Form 10-K for FY 2025 and Form 10-Qs / Form 8-Ks for recent quarters), Alphabet generated $422.50 billion in revenue over the trailing 12-month (TTM) period ending March 31, 2026, representing a 17.5% year-over-year increase compared to the prior 12-month period.
In this example, you can use grounding or constraining the source as a way to prevent AI hallucinations. SEC filings are the most accurate source for a company's financial data.
Code Generation
Using prompt engineering to generate code can accelerate development, help debug programs, or adjust code from GitHub repositories for specific use.
You would tell the model the task e.g historical prices and volumes for Google for the last 12 months. Give it a persona like a Python developer and provide the source you want to use.
As a Python developer, create a Python script that will pull the last 3 months of price and volume data for Google (GOOGL) using the finance API and store it in a CSV file.
The result:
Instructions to install libraries needed
pip install yfinance pandas
And the code
from pathlib import Path
import pandas as pd
import yfinance as yf
def fetch_and_save_stock_data(
ticker: str = "GOOGL",
period: str = "3mo",
output_filename: str = "googl_3mo_data.csv",
) -> None:
"""Fetches historical stock market data (price & volume) for a ticker
and exports selected columns to a CSV file.
Parameters:
ticker (str): The stock ticker symbol. Default is 'GOOGL'.
period (str): The time period to pull (e.g., '3mo', '6mo', '1y'). Default is '3mo'.
output_filename (str): Target CSV file path.
"""
try:
print(f"Fetching {period} of data for {ticker}...")
# Initialize ticker object
stock = yf.Ticker(ticker)
# Download historical data for the given period
df = stock.history(period=period)
if df.empty:
print(f"No data returned for ticker '{ticker}'. Please check symbol.")
return
# Keep relevant price and volume columns
columns_to_keep = ["Open", "High", "Low", "Close", "Volume"]
df_filtered = df[columns_to_keep].copy()
# Format Date index into a clean string (YYYY-MM-DD)
df_filtered.index = df_filtered.index.strftime("%Y-%m-%d")
df_filtered.index.name = "Date"
# Round numeric values for clean output
df_filtered = df_filtered.round(2)
# Export to CSV
output_path = Path(output_filename)
df_filtered.to_csv(output_path)
print(f"Successfully saved data to: {output_path.resolve()}")
print("\n--- First 5 Rows ---")
print(df_filtered.head())
except Exception as e:
print(f"An error occurred while processing market data: {e}")
if __name__ == "__main__":
fetch_and_save_stock_data(
ticker="GOOGL", period="3mo", output_filename="GOOGL_3mo_prices.csv"
)
Document generation
You can use prompt engineering to help craft communications. In this example, I will have Gemini build an email to solicit funds for a youth STEM program in Stamford, CT.
As a youth center manager in Stamford, CT, I need to draft an email to ask local companies for money to develop a STEM program for middle school students in the community.
Once the code is created, you can continue to ask the model to modify or add functionality to the program. Because Gemini has memory of what you asked in the session, iteration becomes simple and commands do not need to incorporate any of the previous instructions.
Document Summarization
We can use prompt engineering to summarize documents for presentation purposes to specific audiences.
Executive Summary: Alphabet Inc. (GOOGL) – Q2 2026
Recommendation: BUY
Thesis: Full-stack AI execution is accelerating top-line growth across Search and Enterprise Cloud, expanding margins, and reinforcing market dominance.
Top 5 Highlights
Accelerated Top-Line Growth: Consolidated revenues grew 24% YoY to $119.8B, marking 12 straight quarters of double-digit expansion.
Hyper-Growth in Cloud: Google Cloud surged 82% YoY to $24.8B, with segment operating income scaling to $8.8B.
Search Moat Intact: Core Search & other revenue increased 17% YoY to $63.3B, proving AI integration drives query volume rather than cannibalization.
Margin Expansion: Consolidated operating income rose 30% YoY to $40.8B, driving operating margins up 200 bps to 34%.
Massive Enterprise AI Scale: Gemini Enterprise is deployed by nearly 90% of the Fortune 100, with Gemini API handling 22B tokens/minute and the consumer app reaching 950M MAUs.
Key Positives & Commentary
Clear AI Monetization: Cloud's 82% growth demonstrates enterprise demand for GCP AI Infrastructure and Gemini, translating heavy CapEx directly into high-margin revenue.
AI Generates Search Engagement: AI features are boosting total queries, disproving disruption fears and strengthening Google's primary profit engine.
Strong Operating Leverage: Revenues grew 24% while operating income grew 30%, showing disciplined operational cost management alongside heavy AI compute expansion.
When using generative AI, make sure that you allow for a human in the loop to evaluate for bias, hallucinations, or false results. It is important not to use sensitive or confidential information as input to a public data model. Finally, try to provide clear objectives by using action verbs like create, classify, summarize, and translate to yield the best results.
One valuable use of AI is to summarize a long report or document, giving you a high-level understanding without reading the entire document. Let's take the latest Nvidia earnings release. I can instruct Gemini to summarize the text from a specific link.
First, I’ll ask Gemini to find the link I need.
Then I will get Gemini to summarize the link
SUMMARIZE THE TEXT FROM THIS LINK - https://nvidianews.nvidia.com/news/nvidia-announces-financial-results-for-fourth-quarter-and-fiscal-2026
NVIDIA reported record-breaking financial results for the fourth quarter and full fiscal year 2026, driven by the "exponential" growth of agentic AI and accelerated computing.
Financial Highlights
Q4 Revenue: Record $68.1 billion, up 73% year-over-year and 20% from the previous quarter.
Full-Year Revenue: Record $215.9 billion, a 65% increase from fiscal 2025.
Earnings per Share (EPS): * GAAP: $1.76 (up 98% YoY).
Non-GAAP: $1.62 (up 82% YoY).
Gross Margin: Remained strong at 75.0% (GAAP) for the quarter.
Shareholder Returns: NVIDIA returned $41.1 billion to shareholders in fiscal 2026 through share repurchases and dividends.
Segment Performance
Data Center: The primary growth engine, reaching a record $62.3 billion in Q4 revenue (up 75% YoY). This was driven by the shift to AI infrastructure and the ramp-up of the Blackwell platform.
Gaming: Q4 revenue was $3.7 billion (up 47% YoY), supported by strong Blackwell demand, though down 13% sequentially due to post-holiday inventory normalization.
Professional Visualization: Revenue rose to $1.3 billion (up 159% YoY).
Automotive and Robotics: Achieved record full-year revenue of $2.3 billion (up 39% YoY).
Future Outlook & Strategic Moves
Q1 FY2027 Guidance: NVIDIA expects revenue of $78.0 billion (± 2%).
New Platforms: CEO Jensen Huang highlighted the arrival of the Rubin platform (the successor to Blackwell), which aims to reduce AI inference costs by up to 10x.
Partnerships: The company announced major collaborations with Meta (deploying millions of GPUs), AWS, Microsoft Azure, and Anthropic.
Policy Change: Starting in Q1 FY2027, NVIDIA will include stock-based compensation in its non-GAAP financial measures.
CEO Quote: Jensen Huang stated, "The agentic AI inflection point has arrived... Our customers are racing to invest in AI compute — the factories powering the AI industrial revolution."
No comments:
Post a Comment