Overview

5 Prompt engineering in web applications

This chapter explains how to move beyond generic prompts and use prompt engineering to deliver precise, reliable AI behavior in web applications. It frames prompt engineering as the systematic design of instructions and context to guide models, then grounds the reader in core mechanics that affect quality and cost: tokenization, context-window and billing constraints, and the role of control tokens. It also clarifies how different prompt types work in the Vercel AI SDK—basic text prompts for single turns, richer message prompts (including compound and tool-call messages) for multi-turn interactions, and system prompts for setting global behavior and personas.

From there, the chapter turns to operational practices for managing prompts at scale. It recommends storing prompts outside of code for dynamic updates, access control, and versioning, and suggests semantic versioning schemes tied to model providers. Because deterministic unit tests are hard with probabilistic outputs, it proposes practical evaluation strategies: mocking LLM calls to test surrounding logic, semantic similarity scoring to check meaning rather than exact wording, and constraint validation to enforce formats and rules. The material also covers token counting approaches across providers and outlines a lightweight prompt management architecture that can evolve with product needs.

The chapter then dives into three high-impact techniques. Few-shot learning uses a handful of well-chosen examples to shape style, structure, and tone for tasks like support chat; chain-of-thought prompting improves reasoning by asking models to show step-by-step logic; and embeddings encode meaning as vectors to power semantic search and recommendations. It demonstrates embeddings in the Vercel AI SDK (embed and embedMany), explains why to store vectors for efficiency and cost, and shows how to retrieve relevant content via similarity (e.g., cosine) while noting caveats like model specificity and versioning. It closes by noting that these foundations are evolving and previews advanced strategies—Tree of Thoughts, Self-Refine, and LLM-as-a-Judge—before leading into broader orchestration with tools like LangChain.

This chapter covers prompt versioning, focusing on the iterative refinement of prompts, and prompt testing, a method for evaluating prompt effectiveness across various scenarios. We'll then examine few-shot learning, which uses examples to guide AI responses, and chain-of-thought learning, which encourages step-by-step reasoning. Finally, we'll look into embeddings, which are numerical representations of text for AI processing.
This diagram illustrates the end-to-end process of how human input is transformed, processed by a Large Language Model (LLM), and converted back into human-readable output.
This diagram illustrates the classification of prompt types used in the Vercel AI SDK. At the top level, prompts are divided into three main categories: Basic Text prompts, Message prompts and System prompts. The Message prompts category is further subdivided into three types: Simple, Compound and Tool Call messages.
Architecture of the PlantUML diagram generation system using tool calls in the Vercel AI SDK. The system allows users to request diagrams, and the PromptLibrary class handles the generation process by creating prompts, determining the diagram type, and interacting with the Vercel AI SDK to generate the diagram using the AI (OpenAI gpt-4 or other) model and tool calls.
This diagram illustrates the step-by-step procedure for Few-Shot learning, where users provide a few examples to guide the AI model. The process involves compiling these examples into a prompt, generating output using the AI model, and then reviewing and adjusting the output as needed to achieve the desired results.
This screenshot depicts the output of the few-shot learning responses from the AI model.
This diagram outlines the key steps involved in creating chain of thought prompts that encourage large language models to articulate their reasoning process step-by-step. We define the prompt structure, we provide examples, and we require step-by-step explanations, we test for consistency, and we iterate on the prompts to ensure a uniform user experience across different queries and applications.
This diagram illustrates the concept of embeddings using a restaurant menu analogy. The "Embedding Space" represents a multidimensional space where both customer orders (queries) and menu items are mapped as vectors. Each menu item (e.g., Spaghetti Carbonara) is a pre-computed vector, while the customer order is converted to a query vector. Similarity between items is determined by their proximity in this space. Attributes like "Pasta" or "Creamy" represent dimensions of the embedding space. A similarity search finds the closest match and similar items to the query, mirroring how embedding-based systems in machine learning find relevant results for given inputs.
This figure displays a 2D projection of word embeddings in a 200-dimensional space, focusing on the term "reproductive" and its semantic neighbors. The visualization shows 10,000 points, with 101 points selected for detailed view. The right panel lists the 10 nearest neighbors to "reproductive" in the original space, with their cosine distances. This representation demonstrates how word embeddings capture semantic relationships together in the vector space. (src: https://projector.tensorflow.org/)
This diagram illustrates the workflow of an information retrieval system that utilizes embeddings to enhance user query responses. An admin provides content, such as common questions and knowledge base articles, to the application, which generates embeddings for this content and stores them in a database. When a user submits a query, the application generates a corresponding query embedding and stores it as well. The system then retrieves similar embeddings from the database and calculates similarity scores to identify the most relevant results. Finally, these results are returned to the user.

Summary

  • Prompt engineering is a critical technique for optimizing AI model outputs in web applications, enhancing user interactions and experiences.
  • Few-shot learning enables AI models to adapt quickly to new tasks by providing a limited number of examples, making it especially beneficial in scenarios with limited training data.
  • Chain-of-thought prompting encourages AI models to engage in step-by-step reasoning, improving accuracy by breaking complex tasks into manageable components.
  • Embeddings facilitate semantic search and content recommendations, allowing for more context-aware interactions and personalized user experiences.
  • Tokenization transforms natural language instructions into a format that AI models can efficiently process, ensuring effective communication between users and models.
  • Max tokens refer to the maximum number of tokens an AI model can process in a single interaction, encompassing both input and output, which is crucial for ensuring requests are not rejected.
  • Control tokens guide the behavior and output of AI models, allowing developers to define specific rules and instructions within prompts.
  • Different types of prompts include basic text prompts, message prompts, and system prompts, each designed for distinct use cases and interactions with AI models.
  • Effective prompt management involves storing prompts in a database for dynamic updates, version control, scalability, and access control.
  • Prompt versioning allows developers to track changes to prompts over time, assessing their impact on AI outputs and user experiences.
  • The chapter establishes foundational concepts of prompt engineering, setting the stage for deeper exploration of advanced techniques and strategies in subsequent chapters.

FAQ

What is prompt engineering and why does it matter for web applications?Prompt engineering is the practice of crafting and refining prompts and context so AI models return accurate, useful outputs. In web apps, well-designed prompts improve relevance, tone, and formatting, which leads to better UX and lower costs. This chapter shows how to move beyond generic prompts by adding examples, reasoning steps, and structured context tailored to your app’s needs.
How do tokens, tokenization, and max tokens affect cost and reliability?LLMs convert inputs and outputs into tokens; providers bill on total tokens processed (input + output). Each model has a context window (max tokens per request). If your prompt is too long, the model may truncate or reject it. Use a local tokenizer (e.g., tiktoken for OpenAI) to count tokens; Gemini reports usage in its API response. Keep prompts concise so enough tokens remain for the model’s answer.
Do I need to add special/control tokens like <|startoftext|> to my prompts?No. Control tokens (start/end of text, role markers, padding) exist under the hood, but the API and SDKs handle them for you. Understanding them helps when inspecting raw logs or debugging, but you typically send structured messages (system/user/assistant) and let the provider insert the special tokens automatically.
What prompt types does the Vercel AI SDK support, and when should I use each?- Basic text prompt: a single-turn string; simple but no conversation history. - Message prompts: multi-turn context with roles; supports simple, compound (attachments like images), and tool-call messages for function/API execution. - System prompt: sets global behavior/persona for the session. Use message prompts for most apps; add system prompts to enforce tone, policy, or persona.
How should I manage and version prompts in production?Store prompts in a database for dynamic updates, A/B tests, access control, and scale. Keep multiple versions per provider/model and use semantic versioning (MAJOR.MINOR.PATCH) in names. You can also track prompt files in Git, but DB-backed libraries make rollout, rollback, and experimentation easier across environments.
How can I test and evaluate prompt changes effectively?LLM outputs are probabilistic, so prefer strategies beyond exact string matches: - Mock responses to test your app logic quickly. - Use semantic similarity (e.g., cosine) to compare meaning rather than wording. - Validate constraints (word count, required keywords, format). These techniques, paired with Vitest/Jest, help catch regressions while controlling cost and flakiness.
What is few-shot learning, and how do I design good examples?Few-shot learning guides the model with a handful of input–output examples inside the prompt. Provide clear, diverse, high-quality examples that match your target format, tone, and constraints. Be explicit about counts or structure (e.g., “List 5 items”). A general recipe: set context, list use cases, show user–assistant examples, then ask the model to respond in that style.
What is chain-of-thought prompting and when should I use it?Chain-of-thought prompting asks the model to reason step by step, improving correctness on tasks like math, debugging, or planning. It’s easy to adopt (no fine-tuning), but it doesn’t guarantee each step is correct—validate critical steps or results. Use it when transparency and intermediate reasoning improve trust and accuracy.
What are embeddings and how do I use them with the Vercel AI SDK?Embeddings are vectors that capture the meaning of text (or other media). With the Vercel AI SDK, use embed for a single value and embedMany for batches. Store embeddings in a vector-capable database, then run similarity search (e.g., cosine) to power semantic search, recommendations, or RAG. Embeddings are generally deterministic per model version.
Are embeddings interchangeable across models, and where should I store them?Embeddings are model-specific; don’t mix vectors from different models or versions in the same index. Always embed queries with the same model used for your corpus and record model/version metadata. Store vectors in a vector database (Pinecone, Milvus) or general DB with vector search (PostgreSQL + pgvector, MongoDB, etc.) to enable fast, scalable similarity queries and reduce repeated API costs.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build AI-Enhanced Web Apps ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build AI-Enhanced Web Apps ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build AI-Enhanced Web Apps ebook for free